dad1ccadcb84a64827aa801064d9d1baf67f06aa
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * @defgroup Parser Parser
4 *
5 * @file
6 * @ingroup Parser
7 * File for Parser and related classes
8 */
9
10
11 /**
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
16 *
17 * <pre>
18 * There are five main entry points into the Parser class:
19 * parse()
20 * produces HTML output
21 * preSaveTransform().
22 * produces altered wiki markup.
23 * preprocess()
24 * removes HTML comments and expands templates
25 * cleanSig()
26 * Cleans a signature before saving it to preferences
27 * extractSections()
28 * Extracts sections from an article for section editing
29 *
30 * Globals used:
31 * objects: $wgLang, $wgContLang
32 *
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
34 *
35 * settings:
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
39 * $wgMaxArticleSize*
40 *
41 * * only within ParserOptions
42 * </pre>
43 *
44 * @ingroup Parser
45 */
46 class Parser
47 {
48 /**
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
52 */
53 const VERSION = '1.6.4';
54
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH = 1;
58 const SFH_OBJECT_ARGS = 2;
59
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
65
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT = 0;
68 const COLON_STATE_TAG = 1;
69 const COLON_STATE_TAGSTART = 2;
70 const COLON_STATE_CLOSETAG = 3;
71 const COLON_STATE_TAGSLASH = 4;
72 const COLON_STATE_COMMENT = 5;
73 const COLON_STATE_COMMENTDASH = 6;
74 const COLON_STATE_COMMENTDASHDASH = 7;
75
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION = 1;
78
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
81 const OT_HTML = 1;
82 const OT_WIKI = 2;
83 const OT_PREPROCESS = 3;
84 const OT_MSG = 3;
85
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX = "-QINU\x7f";
88
89 /**#@+
90 * @private
91 */
92 # Persistent:
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf,
96 $mFunctionTagHooks, $mDoTitleConvert, $mDoContentConvert;
97
98
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mLinkHolders, $mLinkID;
103 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
104 var $mTplExpandCache; // empty-frame expansion cache
105 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
106 var $mExpensiveFunctionCount; // number of expensive parser function calls
107
108 # Temporary
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
117
118 /**#@-*/
119
120 /**
121 * Constructor
122 *
123 * @public
124 */
125 function __construct( $conf = array() ) {
126 $this->mConf = $conf;
127 $this->mTagHooks = array();
128 $this->mTransparentTagHooks = array();
129 $this->mFunctionHooks = array();
130 $this->mFunctionTagHooks = array();
131 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
132 $this->mDefaultStripList = $this->mStripList = array( 'nowiki', 'gallery', 'a' );
133 $this->mUrlProtocols = wfUrlProtocols();
134 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
135 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
136 $this->mVarCache = array();
137 if ( isset( $conf['preprocessorClass'] ) ) {
138 $this->mPreprocessorClass = $conf['preprocessorClass'];
139 } elseif ( extension_loaded( 'domxml' ) ) {
140 // PECL extension that conflicts with the core DOM extension (bug 13770)
141 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
142 $this->mPreprocessorClass = 'Preprocessor_Hash';
143 } elseif ( extension_loaded( 'dom' ) ) {
144 $this->mPreprocessorClass = 'Preprocessor_DOM';
145 } else {
146 $this->mPreprocessorClass = 'Preprocessor_Hash';
147 }
148 $this->mMarkerIndex = 0;
149 $this->mFirstCall = true;
150 $this->mDoTitleConvert = true;
151 $this->mDoContentConvert = true;
152 }
153
154 /**
155 * Reduce memory usage to reduce the impact of circular references
156 */
157 function __destruct() {
158 if ( isset( $this->mLinkHolders ) ) {
159 $this->mLinkHolders->__destruct();
160 }
161 foreach ( $this as $name => $value ) {
162 unset( $this->$name );
163 }
164 }
165
166 /**
167 * Do various kinds of initialisation on the first call of the parser
168 */
169 function firstCallInit() {
170 if ( !$this->mFirstCall ) {
171 return;
172 }
173 $this->mFirstCall = false;
174
175 wfProfileIn( __METHOD__ );
176
177 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
178 CoreParserFunctions::register( $this );
179 $this->initialiseVariables();
180
181 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
182 wfProfileOut( __METHOD__ );
183 }
184
185 /**
186 * Clear Parser state
187 *
188 * @private
189 */
190 function clearState() {
191 wfProfileIn( __METHOD__ );
192 if ( $this->mFirstCall ) {
193 $this->firstCallInit();
194 }
195 $this->mOutput = new ParserOutput;
196 $this->mAutonumber = 0;
197 $this->mLastSection = '';
198 $this->mDTopen = false;
199 $this->mIncludeCount = array();
200 $this->mStripState = new StripState;
201 $this->mArgStack = false;
202 $this->mInPre = false;
203 $this->mLinkHolders = new LinkHolderArray( $this );
204 $this->mLinkID = 0;
205 $this->mRevisionTimestamp = $this->mRevisionId = null;
206 $this->mVarCache = array();
207
208 /**
209 * Prefix for temporary replacement strings for the multipass parser.
210 * \x07 should never appear in input as it's disallowed in XML.
211 * Using it at the front also gives us a little extra robustness
212 * since it shouldn't match when butted up against identifier-like
213 * string constructs.
214 *
215 * Must not consist of all title characters, or else it will change
216 * the behaviour of <nowiki> in a link.
217 */
218 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
219 # Changed to \x7f to allow XML double-parsing -- TS
220 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
221
222
223 # Clear these on every parse, bug 4549
224 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
225
226 $this->mShowToc = true;
227 $this->mForceTocPosition = false;
228 $this->mIncludeSizes = array(
229 'post-expand' => 0,
230 'arg' => 0,
231 );
232 $this->mPPNodeCount = 0;
233 $this->mDefaultSort = false;
234 $this->mHeadings = array();
235 $this->mDoubleUnderscores = array();
236 $this->mExpensiveFunctionCount = 0;
237
238 # Fix cloning
239 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
240 $this->mPreprocessor = null;
241 }
242
243 wfRunHooks( 'ParserClearState', array( &$this ) );
244 wfProfileOut( __METHOD__ );
245 }
246
247 function setOutputType( $ot ) {
248 $this->mOutputType = $ot;
249 // Shortcut alias
250 $this->ot = array(
251 'html' => $ot == self::OT_HTML,
252 'wiki' => $ot == self::OT_WIKI,
253 'pre' => $ot == self::OT_PREPROCESS,
254 );
255 }
256
257 /**
258 * Set the context title
259 */
260 function setTitle( $t ) {
261 if ( !$t || $t instanceof FakeTitle ) {
262 $t = Title::newFromText( 'NO TITLE' );
263 }
264 if ( strval( $t->getFragment() ) !== '' ) {
265 # Strip the fragment to avoid various odd effects
266 $this->mTitle = clone $t;
267 $this->mTitle->setFragment( '' );
268 } else {
269 $this->mTitle = $t;
270 }
271 }
272
273 /**
274 * Accessor for mUniqPrefix.
275 *
276 * @public
277 */
278 function uniqPrefix() {
279 if( !isset( $this->mUniqPrefix ) ) {
280 // @todo Fixme: this is probably *horribly wrong*
281 // LanguageConverter seems to want $wgParser's uniqPrefix, however
282 // if this is called for a parser cache hit, the parser may not
283 // have ever been initialized in the first place.
284 // Not really sure what the heck is supposed to be going on here.
285 return '';
286 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
287 }
288 return $this->mUniqPrefix;
289 }
290
291 /**
292 * Convert wikitext to HTML
293 * Do not call this function recursively.
294 *
295 * @param $text String: text we want to parse
296 * @param $title A title object
297 * @param $options ParserOptions
298 * @param $linestart boolean
299 * @param $clearState boolean
300 * @param $revid Int: number to pass in {{REVISIONID}}
301 * @return ParserOutput a ParserOutput
302 */
303 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
304 /**
305 * First pass--just handle <nowiki> sections, pass the rest off
306 * to internalParse() which does all the real work.
307 */
308
309 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
310 $fname = __METHOD__.'-' . wfGetCaller();
311 wfProfileIn( __METHOD__ );
312 wfProfileIn( $fname );
313
314 if ( $clearState ) {
315 $this->clearState();
316 }
317
318 $this->mOptions = $options;
319 $this->setTitle( $title ); // Page title has to be set for the pre-processor
320
321 $oldRevisionId = $this->mRevisionId;
322 $oldRevisionTimestamp = $this->mRevisionTimestamp;
323 if( $revid !== null ) {
324 $this->mRevisionId = $revid;
325 $this->mRevisionTimestamp = null;
326 }
327 $this->setOutputType( self::OT_HTML );
328 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
329 # No more strip!
330 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
331 $text = $this->internalParse( $text );
332 // internalParse took care of the notitleconvert bit, so title conversion is here.
333 if ( $this->mDoTitleConvert && !$this->mTitle->isConversionTable()) {
334 $converted = $wgContLang->convert( $title );
335 if ( !$converted instanceOf Title ) {
336 $converted = Title::newFromText( $converted );
337 }
338 $this->setTitle( $converted );
339 }
340
341 $text = $this->mStripState->unstripGeneral( $text );
342
343 # Clean up special characters, only run once, next-to-last before doBlockLevels
344 $fixtags = array(
345 # french spaces, last one Guillemet-left
346 # only if there is something before the space
347 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&nbsp;\\2',
348 # french spaces, Guillemet-right
349 '/(\\302\\253) /' => '\\1&nbsp;',
350 '/&nbsp;(!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
351 );
352 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
353
354 $text = $this->doBlockLevels( $text, $linestart );
355
356 $this->replaceLinkHolders( $text );
357
358 # the position of the convert() call should not be changed. it
359 # assumes that the links are all replaced and the only thing left
360 # is the <nowiki> mark.
361 if ( $this->mDoContentConvert && !$this->mTitle->isConversionTable()) {
362 $text = $wgContLang->convert( $text );
363 }
364
365 $text = $this->mStripState->unstripNoWiki( $text );
366
367 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
368
369 //!JF Move to its own function
370
371 $uniq_prefix = $this->mUniqPrefix;
372 $matches = array();
373 $elements = array_keys( $this->mTransparentTagHooks );
374 $text = self::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
375
376 foreach( $matches as $marker => $data ) {
377 list( $element, $content, $params, $tag ) = $data;
378 $tagName = strtolower( $element );
379 if( isset( $this->mTransparentTagHooks[$tagName] ) ) {
380 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
381 array( $content, $params, $this ) );
382 } else {
383 $output = $tag;
384 }
385 $this->mStripState->general->setPair( $marker, $output );
386 }
387 $text = $this->mStripState->unstripGeneral( $text );
388
389 $text = Sanitizer::normalizeCharReferences( $text );
390
391 if ( ( $wgUseTidy && $this->mOptions->mTidy ) || $wgAlwaysUseTidy ) {
392 $text = MWTidy::tidy( $text );
393 } else {
394 # attempt to sanitize at least some nesting problems
395 # (bug #2702 and quite a few others)
396 $tidyregs = array(
397 # ''Something [http://www.cool.com cool''] -->
398 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
399 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
400 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
401 # fix up an anchor inside another anchor, only
402 # at least for a single single nested link (bug 3695)
403 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
404 '\\1\\2</a>\\3</a>\\1\\4</a>',
405 # fix div inside inline elements- doBlockLevels won't wrap a line which
406 # contains a div, so fix it up here; replace
407 # div with escaped text
408 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
409 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
410 # remove empty italic or bold tag pairs, some
411 # introduced by rules above
412 '/<([bi])><\/\\1>/' => '',
413 );
414
415 $text = preg_replace(
416 array_keys( $tidyregs ),
417 array_values( $tidyregs ),
418 $text );
419 }
420 global $wgExpensiveParserFunctionLimit;
421 if ( $this->mExpensiveFunctionCount > $wgExpensiveParserFunctionLimit ) {
422 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount, $wgExpensiveParserFunctionLimit );
423 }
424
425 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
426
427 # Information on include size limits, for the benefit of users who try to skirt them
428 if ( $this->mOptions->getEnableLimitReport() ) {
429 global $wgExpensiveParserFunctionLimit;
430 $max = $this->mOptions->getMaxIncludeSize();
431 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
432 $limitReport =
433 "NewPP limit report\n" .
434 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
435 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
436 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
437 $PFreport;
438 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
439 $text .= "\n<!-- \n$limitReport-->\n";
440 }
441 $this->mOutput->setText( $text );
442 $this->mRevisionId = $oldRevisionId;
443 $this->mRevisionTimestamp = $oldRevisionTimestamp;
444 wfProfileOut( $fname );
445 wfProfileOut( __METHOD__ );
446
447 return $this->mOutput;
448 }
449
450 /**
451 * Recursive parser entry point that can be called from an extension tag
452 * hook.
453 *
454 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
455 *
456 * @param $text String: text extension wants to have parsed
457 * @param PPFrame $frame: The frame to use for expanding any template variables
458 */
459 function recursiveTagParse( $text, $frame=false ) {
460 wfProfileIn( __METHOD__ );
461 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
462 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
463 $text = $this->internalParse( $text, false, $frame );
464 wfProfileOut( __METHOD__ );
465 return $text;
466 }
467
468 /**
469 * Expand templates and variables in the text, producing valid, static wikitext.
470 * Also removes comments.
471 */
472 function preprocess( $text, $title, $options, $revid = null ) {
473 wfProfileIn( __METHOD__ );
474 $this->clearState();
475 $this->setOutputType( self::OT_PREPROCESS );
476 $this->mOptions = $options;
477 $this->setTitle( $title );
478 if( $revid !== null ) {
479 $this->mRevisionId = $revid;
480 }
481 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
482 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
483 $text = $this->replaceVariables( $text );
484 $text = $this->mStripState->unstripBoth( $text );
485 wfProfileOut( __METHOD__ );
486 return $text;
487 }
488
489 /**
490 * Get a random string
491 *
492 * @private
493 * @static
494 */
495 function getRandomString() {
496 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
497 }
498
499 function &getTitle() { return $this->mTitle; }
500 function getOptions() { return $this->mOptions; }
501 function getRevisionId() { return $this->mRevisionId; }
502 function getOutput() { return $this->mOutput; }
503 function nextLinkID() { return $this->mLinkID++; }
504
505 function getFunctionLang() {
506 global $wgLang, $wgContLang;
507
508 $target = $this->mOptions->getTargetLanguage();
509 if ( $target !== null ) {
510 return $target;
511 } else {
512 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
513 }
514 }
515
516 /**
517 * Get a preprocessor object
518 */
519 function getPreprocessor() {
520 if ( !isset( $this->mPreprocessor ) ) {
521 $class = $this->mPreprocessorClass;
522 $this->mPreprocessor = new $class( $this );
523 }
524 return $this->mPreprocessor;
525 }
526
527 /**
528 * Replaces all occurrences of HTML-style comments and the given tags
529 * in the text with a random marker and returns the next text. The output
530 * parameter $matches will be an associative array filled with data in
531 * the form:
532 * 'UNIQ-xxxxx' => array(
533 * 'element',
534 * 'tag content',
535 * array( 'param' => 'x' ),
536 * '<element param="x">tag content</element>' ) )
537 *
538 * @param $elements list of element names. Comments are always extracted.
539 * @param $text Source text string.
540 * @param $uniq_prefix
541 *
542 * @public
543 * @static
544 */
545 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
546 static $n = 1;
547 $stripped = '';
548 $matches = array();
549
550 $taglist = implode( '|', $elements );
551 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
552
553 while ( $text != '' ) {
554 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
555 $stripped .= $p[0];
556 if( count( $p ) < 5 ) {
557 break;
558 }
559 if( count( $p ) > 5 ) {
560 // comment
561 $element = $p[4];
562 $attributes = '';
563 $close = '';
564 $inside = $p[5];
565 } else {
566 // tag
567 $element = $p[1];
568 $attributes = $p[2];
569 $close = $p[3];
570 $inside = $p[4];
571 }
572
573 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . self::MARKER_SUFFIX;
574 $stripped .= $marker;
575
576 if ( $close === '/>' ) {
577 // Empty element tag, <tag />
578 $content = null;
579 $text = $inside;
580 $tail = null;
581 } else {
582 if( $element === '!--' ) {
583 $end = '/(-->)/';
584 } else {
585 $end = "/(<\\/$element\\s*>)/i";
586 }
587 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
588 $content = $q[0];
589 if( count( $q ) < 3 ) {
590 # No end tag -- let it run out to the end of the text.
591 $tail = '';
592 $text = '';
593 } else {
594 $tail = $q[1];
595 $text = $q[2];
596 }
597 }
598
599 $matches[$marker] = array( $element,
600 $content,
601 Sanitizer::decodeTagAttributes( $attributes ),
602 "<$element$attributes$close$content$tail" );
603 }
604 return $stripped;
605 }
606
607 /**
608 * Get a list of strippable XML-like elements
609 */
610 function getStripList() {
611 global $wgRawHtml;
612 $elements = $this->mStripList;
613 if( $wgRawHtml ) {
614 $elements[] = 'html';
615 }
616 if( $this->mOptions->getUseTeX() ) {
617 $elements[] = 'math';
618 }
619 return $elements;
620 }
621
622 /**
623 * @deprecated use replaceVariables
624 */
625 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
626 return $text;
627 }
628
629 /**
630 * Restores pre, math, and other extensions removed by strip()
631 *
632 * always call unstripNoWiki() after this one
633 * @private
634 * @deprecated use $this->mStripState->unstrip()
635 */
636 function unstrip( $text, $state ) {
637 return $state->unstripGeneral( $text );
638 }
639
640 /**
641 * Always call this after unstrip() to preserve the order
642 *
643 * @private
644 * @deprecated use $this->mStripState->unstrip()
645 */
646 function unstripNoWiki( $text, $state ) {
647 return $state->unstripNoWiki( $text );
648 }
649
650 /**
651 * @deprecated use $this->mStripState->unstripBoth()
652 */
653 function unstripForHTML( $text ) {
654 return $this->mStripState->unstripBoth( $text );
655 }
656
657 /**
658 * Add an item to the strip state
659 * Returns the unique tag which must be inserted into the stripped text
660 * The tag will be replaced with the original text in unstrip()
661 *
662 * @private
663 */
664 function insertStripItem( $text ) {
665 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
666 $this->mMarkerIndex++;
667 $this->mStripState->general->setPair( $rnd, $text );
668 return $rnd;
669 }
670
671 /**
672 * Interface with html tidy
673 * @deprecated Use MWTidy::tidy()
674 */
675 public static function tidy( $text ) {
676 wfDeprecated( __METHOD__ );
677 return MWTidy::tidy( $text );
678 }
679
680 /**
681 * parse the wiki syntax used to render tables
682 *
683 * @private
684 */
685 function doTableStuff ( $text ) {
686 wfProfileIn( __METHOD__ );
687
688 $lines = StringUtils::explode( "\n", $text );
689 $out = '';
690 $td_history = array (); // Is currently a td tag open?
691 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
692 $tr_history = array (); // Is currently a tr tag open?
693 $tr_attributes = array (); // history of tr attributes
694 $has_opened_tr = array(); // Did this table open a <tr> element?
695 $indent_level = 0; // indent level of the table
696
697 foreach ( $lines as $outLine ) {
698 $line = trim( $outLine );
699
700 if( $line == '' ) { // empty line, go to next line
701 $out .= $outLine."\n";
702 continue;
703 }
704 $first_character = $line[0];
705 $matches = array();
706
707 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
708 // First check if we are starting a new table
709 $indent_level = strlen( $matches[1] );
710
711 $attributes = $this->mStripState->unstripBoth( $matches[2] );
712 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
713
714 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
715 array_push ( $td_history , false );
716 array_push ( $last_tag_history , '' );
717 array_push ( $tr_history , false );
718 array_push ( $tr_attributes , '' );
719 array_push ( $has_opened_tr , false );
720 } else if ( count ( $td_history ) == 0 ) {
721 // Don't do any of the following
722 $out .= $outLine."\n";
723 continue;
724 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
725 // We are ending a table
726 $line = '</table>' . substr ( $line , 2 );
727 $last_tag = array_pop ( $last_tag_history );
728
729 if ( !array_pop ( $has_opened_tr ) ) {
730 $line = "<tr><td></td></tr>{$line}";
731 }
732
733 if ( array_pop ( $tr_history ) ) {
734 $line = "</tr>{$line}";
735 }
736
737 if ( array_pop ( $td_history ) ) {
738 $line = "</{$last_tag}>{$line}";
739 }
740 array_pop ( $tr_attributes );
741 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
742 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
743 // Now we have a table row
744 $line = preg_replace( '#^\|-+#', '', $line );
745
746 // Whats after the tag is now only attributes
747 $attributes = $this->mStripState->unstripBoth( $line );
748 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
749 array_pop ( $tr_attributes );
750 array_push ( $tr_attributes , $attributes );
751
752 $line = '';
753 $last_tag = array_pop ( $last_tag_history );
754 array_pop ( $has_opened_tr );
755 array_push ( $has_opened_tr , true );
756
757 if ( array_pop ( $tr_history ) ) {
758 $line = '</tr>';
759 }
760
761 if ( array_pop ( $td_history ) ) {
762 $line = "</{$last_tag}>{$line}";
763 }
764
765 $outLine = $line;
766 array_push ( $tr_history , false );
767 array_push ( $td_history , false );
768 array_push ( $last_tag_history , '' );
769 }
770 else if ( $first_character === '|' || $first_character === '!' || substr ( $line , 0 , 2 ) === '|+' ) {
771 // This might be cell elements, td, th or captions
772 if ( substr ( $line , 0 , 2 ) === '|+' ) {
773 $first_character = '+';
774 $line = substr ( $line , 1 );
775 }
776
777 $line = substr ( $line , 1 );
778
779 if ( $first_character === '!' ) {
780 $line = str_replace ( '!!' , '||' , $line );
781 }
782
783 // Split up multiple cells on the same line.
784 // FIXME : This can result in improper nesting of tags processed
785 // by earlier parser steps, but should avoid splitting up eg
786 // attribute values containing literal "||".
787 $cells = StringUtils::explodeMarkup( '||' , $line );
788
789 $outLine = '';
790
791 // Loop through each table cell
792 foreach ( $cells as $cell )
793 {
794 $previous = '';
795 if ( $first_character !== '+' )
796 {
797 $tr_after = array_pop ( $tr_attributes );
798 if ( !array_pop ( $tr_history ) ) {
799 $previous = "<tr{$tr_after}>\n";
800 }
801 array_push ( $tr_history , true );
802 array_push ( $tr_attributes , '' );
803 array_pop ( $has_opened_tr );
804 array_push ( $has_opened_tr , true );
805 }
806
807 $last_tag = array_pop ( $last_tag_history );
808
809 if ( array_pop ( $td_history ) ) {
810 $previous = "</{$last_tag}>{$previous}";
811 }
812
813 if ( $first_character === '|' ) {
814 $last_tag = 'td';
815 } else if ( $first_character === '!' ) {
816 $last_tag = 'th';
817 } else if ( $first_character === '+' ) {
818 $last_tag = 'caption';
819 } else {
820 $last_tag = '';
821 }
822
823 array_push ( $last_tag_history , $last_tag );
824
825 // A cell could contain both parameters and data
826 $cell_data = explode ( '|' , $cell , 2 );
827
828 // Bug 553: Note that a '|' inside an invalid link should not
829 // be mistaken as delimiting cell parameters
830 if ( strpos( $cell_data[0], '[[' ) !== false ) {
831 $cell = "{$previous}<{$last_tag}>{$cell}";
832 } else if ( count ( $cell_data ) == 1 )
833 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
834 else {
835 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
836 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
837 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
838 }
839
840 $outLine .= $cell;
841 array_push ( $td_history , true );
842 }
843 }
844 $out .= $outLine . "\n";
845 }
846
847 // Closing open td, tr && table
848 while ( count ( $td_history ) > 0 )
849 {
850 if ( array_pop ( $td_history ) ) {
851 $out .= "</td>\n";
852 }
853 if ( array_pop ( $tr_history ) ) {
854 $out .= "</tr>\n";
855 }
856 if ( !array_pop ( $has_opened_tr ) ) {
857 $out .= "<tr><td></td></tr>\n" ;
858 }
859
860 $out .= "</table>\n";
861 }
862
863 // Remove trailing line-ending (b/c)
864 if ( substr( $out, -1 ) === "\n" ) {
865 $out = substr( $out, 0, -1 );
866 }
867
868 // special case: don't return empty table
869 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
870 $out = '';
871 }
872
873 wfProfileOut( __METHOD__ );
874
875 return $out;
876 }
877
878 /**
879 * Helper function for parse() that transforms wiki markup into
880 * HTML. Only called for $mOutputType == self::OT_HTML.
881 *
882 * @private
883 */
884 function internalParse( $text, $isMain = true, $frame=false ) {
885 wfProfileIn( __METHOD__ );
886
887 $origText = $text;
888
889 # Hook to suspend the parser in this state
890 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
891 wfProfileOut( __METHOD__ );
892 return $text ;
893 }
894
895 // if $frame is provided, then use $frame for replacing any variables
896 if ($frame) {
897 // use frame depth to infer how include/noinclude tags should be handled
898 // depth=0 means this is the top-level document; otherwise it's an included document
899 if( !$frame->depth )
900 $flag = 0;
901 else
902 $flag = Parser::PTD_FOR_INCLUSION;
903 $dom = $this->preprocessToDom( $text, $flag );
904 $text = $frame->expand( $dom );
905 }
906 // if $frame is not provided, then use old-style replaceVariables
907 else {
908 $text = $this->replaceVariables( $text );
909 }
910
911 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
912 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
913
914 // Tables need to come after variable replacement for things to work
915 // properly; putting them before other transformations should keep
916 // exciting things like link expansions from showing up in surprising
917 // places.
918 $text = $this->doTableStuff( $text );
919
920 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
921
922 $text = $this->doDoubleUnderscore( $text );
923
924 $text = $this->doHeadings( $text );
925 if( $this->mOptions->getUseDynamicDates() ) {
926 $df = DateFormatter::getInstance();
927 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
928 }
929 $text = $this->doAllQuotes( $text );
930 $text = $this->replaceInternalLinks( $text );
931 $text = $this->replaceExternalLinks( $text );
932
933 # replaceInternalLinks may sometimes leave behind
934 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
935 $text = str_replace($this->mUniqPrefix.'NOPARSE', '', $text);
936
937 $text = $this->doMagicLinks( $text );
938 $text = $this->formatHeadings( $text, $origText, $isMain );
939
940 wfProfileOut( __METHOD__ );
941 return $text;
942 }
943
944 /**
945 * Replace special strings like "ISBN xxx" and "RFC xxx" with
946 * magic external links.
947 *
948 * DML
949 * @private
950 */
951 function doMagicLinks( $text ) {
952 wfProfileIn( __METHOD__ );
953 $prots = $this->mUrlProtocols;
954 $urlChar = self::EXT_LINK_URL_CLASS;
955 $text = preg_replace_callback(
956 '!(?: # Start cases
957 (<a.*?</a>) | # m[1]: Skip link text
958 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
959 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
960 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
961 ISBN\s+(\b # m[5]: ISBN, capture number
962 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
963 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
964 [0-9Xx] # check digit
965 \b)
966 )!x', array( &$this, 'magicLinkCallback' ), $text );
967 wfProfileOut( __METHOD__ );
968 return $text;
969 }
970
971 function magicLinkCallback( $m ) {
972 if ( isset( $m[1] ) && $m[1] !== '' ) {
973 # Skip anchor
974 return $m[0];
975 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
976 # Skip HTML element
977 return $m[0];
978 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
979 # Free external link
980 return $this->makeFreeExternalLink( $m[0] );
981 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
982 # RFC or PMID
983 $CssClass = '';
984 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
985 $keyword = 'RFC';
986 $urlmsg = 'rfcurl';
987 $CssClass = 'mw-magiclink-rfc';
988 $id = $m[4];
989 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
990 $keyword = 'PMID';
991 $urlmsg = 'pubmedurl';
992 $CssClass = 'mw-magiclink-pmid';
993 $id = $m[4];
994 } else {
995 throw new MWException( __METHOD__.': unrecognised match type "' .
996 substr($m[0], 0, 20 ) . '"' );
997 }
998 $url = wfMsg( $urlmsg, $id);
999 $sk = $this->mOptions->getSkin();
1000 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1001 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1002 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1003 # ISBN
1004 $isbn = $m[5];
1005 $num = strtr( $isbn, array(
1006 '-' => '',
1007 ' ' => '',
1008 'x' => 'X',
1009 ));
1010 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1011 return'<a href="' .
1012 $titleObj->escapeLocalUrl() .
1013 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1014 } else {
1015 return $m[0];
1016 }
1017 }
1018
1019 /**
1020 * Make a free external link, given a user-supplied URL
1021 * @return HTML
1022 * @private
1023 */
1024 function makeFreeExternalLink( $url ) {
1025 global $wgContLang;
1026 wfProfileIn( __METHOD__ );
1027
1028 $sk = $this->mOptions->getSkin();
1029 $trail = '';
1030
1031 # The characters '<' and '>' (which were escaped by
1032 # removeHTMLtags()) should not be included in
1033 # URLs, per RFC 2396.
1034 $m2 = array();
1035 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1036 $trail = substr($url, $m2[0][1]) . $trail;
1037 $url = substr($url, 0, $m2[0][1]);
1038 }
1039
1040 # Move trailing punctuation to $trail
1041 $sep = ',;\.:!?';
1042 # If there is no left bracket, then consider right brackets fair game too
1043 if ( strpos( $url, '(' ) === false ) {
1044 $sep .= ')';
1045 }
1046
1047 $numSepChars = strspn( strrev( $url ), $sep );
1048 if ( $numSepChars ) {
1049 $trail = substr( $url, -$numSepChars ) . $trail;
1050 $url = substr( $url, 0, -$numSepChars );
1051 }
1052
1053 $url = Sanitizer::cleanUrl( $url );
1054
1055 # Is this an external image?
1056 $text = $this->maybeMakeExternalImage( $url );
1057 if ( $text === false ) {
1058 # Not an image, make a link
1059 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1060 $this->getExternalLinkAttribs( $url ) );
1061 # Register it in the output object...
1062 # Replace unnecessary URL escape codes with their equivalent characters
1063 $pasteurized = self::replaceUnusualEscapes( $url );
1064 $this->mOutput->addExternalLink( $pasteurized );
1065 }
1066 wfProfileOut( __METHOD__ );
1067 return $text . $trail;
1068 }
1069
1070
1071 /**
1072 * Parse headers and return html
1073 *
1074 * @private
1075 */
1076 function doHeadings( $text ) {
1077 wfProfileIn( __METHOD__ );
1078 for ( $i = 6; $i >= 1; --$i ) {
1079 $h = str_repeat( '=', $i );
1080 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1081 "<h$i>\\1</h$i>", $text );
1082 }
1083 wfProfileOut( __METHOD__ );
1084 return $text;
1085 }
1086
1087 /**
1088 * Replace single quotes with HTML markup
1089 * @private
1090 * @return string the altered text
1091 */
1092 function doAllQuotes( $text ) {
1093 wfProfileIn( __METHOD__ );
1094 $outtext = '';
1095 $lines = StringUtils::explode( "\n", $text );
1096 foreach ( $lines as $line ) {
1097 $outtext .= $this->doQuotes( $line ) . "\n";
1098 }
1099 $outtext = substr($outtext, 0,-1);
1100 wfProfileOut( __METHOD__ );
1101 return $outtext;
1102 }
1103
1104 /**
1105 * Helper function for doAllQuotes()
1106 */
1107 public function doQuotes( $text ) {
1108 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1109 if ( count( $arr ) == 1 )
1110 return $text;
1111 else
1112 {
1113 # First, do some preliminary work. This may shift some apostrophes from
1114 # being mark-up to being text. It also counts the number of occurrences
1115 # of bold and italics mark-ups.
1116 $i = 0;
1117 $numbold = 0;
1118 $numitalics = 0;
1119 foreach ( $arr as $r )
1120 {
1121 if ( ( $i % 2 ) == 1 )
1122 {
1123 # If there are ever four apostrophes, assume the first is supposed to
1124 # be text, and the remaining three constitute mark-up for bold text.
1125 if ( strlen( $arr[$i] ) == 4 )
1126 {
1127 $arr[$i-1] .= "'";
1128 $arr[$i] = "'''";
1129 }
1130 # If there are more than 5 apostrophes in a row, assume they're all
1131 # text except for the last 5.
1132 else if ( strlen( $arr[$i] ) > 5 )
1133 {
1134 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1135 $arr[$i] = "'''''";
1136 }
1137 # Count the number of occurrences of bold and italics mark-ups.
1138 # We are not counting sequences of five apostrophes.
1139 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1140 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1141 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1142 }
1143 $i++;
1144 }
1145
1146 # If there is an odd number of both bold and italics, it is likely
1147 # that one of the bold ones was meant to be an apostrophe followed
1148 # by italics. Which one we cannot know for certain, but it is more
1149 # likely to be one that has a single-letter word before it.
1150 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1151 {
1152 $i = 0;
1153 $firstsingleletterword = -1;
1154 $firstmultiletterword = -1;
1155 $firstspace = -1;
1156 foreach ( $arr as $r )
1157 {
1158 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1159 {
1160 $x1 = substr ($arr[$i-1], -1);
1161 $x2 = substr ($arr[$i-1], -2, 1);
1162 if ($x1 === ' ') {
1163 if ($firstspace == -1) $firstspace = $i;
1164 } else if ($x2 === ' ') {
1165 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1166 } else {
1167 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1168 }
1169 }
1170 $i++;
1171 }
1172
1173 # If there is a single-letter word, use it!
1174 if ($firstsingleletterword > -1)
1175 {
1176 $arr [ $firstsingleletterword ] = "''";
1177 $arr [ $firstsingleletterword-1 ] .= "'";
1178 }
1179 # If not, but there's a multi-letter word, use that one.
1180 else if ($firstmultiletterword > -1)
1181 {
1182 $arr [ $firstmultiletterword ] = "''";
1183 $arr [ $firstmultiletterword-1 ] .= "'";
1184 }
1185 # ... otherwise use the first one that has neither.
1186 # (notice that it is possible for all three to be -1 if, for example,
1187 # there is only one pentuple-apostrophe in the line)
1188 else if ($firstspace > -1)
1189 {
1190 $arr [ $firstspace ] = "''";
1191 $arr [ $firstspace-1 ] .= "'";
1192 }
1193 }
1194
1195 # Now let's actually convert our apostrophic mush to HTML!
1196 $output = '';
1197 $buffer = '';
1198 $state = '';
1199 $i = 0;
1200 foreach ($arr as $r)
1201 {
1202 if (($i % 2) == 0)
1203 {
1204 if ($state === 'both')
1205 $buffer .= $r;
1206 else
1207 $output .= $r;
1208 }
1209 else
1210 {
1211 if (strlen ($r) == 2)
1212 {
1213 if ($state === 'i')
1214 { $output .= '</i>'; $state = ''; }
1215 else if ($state === 'bi')
1216 { $output .= '</i>'; $state = 'b'; }
1217 else if ($state === 'ib')
1218 { $output .= '</b></i><b>'; $state = 'b'; }
1219 else if ($state === 'both')
1220 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1221 else # $state can be 'b' or ''
1222 { $output .= '<i>'; $state .= 'i'; }
1223 }
1224 else if (strlen ($r) == 3)
1225 {
1226 if ($state === 'b')
1227 { $output .= '</b>'; $state = ''; }
1228 else if ($state === 'bi')
1229 { $output .= '</i></b><i>'; $state = 'i'; }
1230 else if ($state === 'ib')
1231 { $output .= '</b>'; $state = 'i'; }
1232 else if ($state === 'both')
1233 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1234 else # $state can be 'i' or ''
1235 { $output .= '<b>'; $state .= 'b'; }
1236 }
1237 else if (strlen ($r) == 5)
1238 {
1239 if ($state === 'b')
1240 { $output .= '</b><i>'; $state = 'i'; }
1241 else if ($state === 'i')
1242 { $output .= '</i><b>'; $state = 'b'; }
1243 else if ($state === 'bi')
1244 { $output .= '</i></b>'; $state = ''; }
1245 else if ($state === 'ib')
1246 { $output .= '</b></i>'; $state = ''; }
1247 else if ($state === 'both')
1248 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1249 else # ($state == '')
1250 { $buffer = ''; $state = 'both'; }
1251 }
1252 }
1253 $i++;
1254 }
1255 # Now close all remaining tags. Notice that the order is important.
1256 if ($state === 'b' || $state === 'ib')
1257 $output .= '</b>';
1258 if ($state === 'i' || $state === 'bi' || $state === 'ib')
1259 $output .= '</i>';
1260 if ($state === 'bi')
1261 $output .= '</b>';
1262 # There might be lonely ''''', so make sure we have a buffer
1263 if ($state === 'both' && $buffer)
1264 $output .= '<b><i>'.$buffer.'</i></b>';
1265 return $output;
1266 }
1267 }
1268
1269 /**
1270 * Replace external links (REL)
1271 *
1272 * Note: this is all very hackish and the order of execution matters a lot.
1273 * Make sure to run maintenance/parserTests.php if you change this code.
1274 *
1275 * @private
1276 */
1277 function replaceExternalLinks( $text ) {
1278 global $wgContLang;
1279 wfProfileIn( __METHOD__ );
1280
1281 $sk = $this->mOptions->getSkin();
1282
1283 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1284 $s = array_shift( $bits );
1285
1286 $i = 0;
1287 while ( $i<count( $bits ) ) {
1288 $url = $bits[$i++];
1289 $protocol = $bits[$i++];
1290 $text = $bits[$i++];
1291 $trail = $bits[$i++];
1292
1293 # The characters '<' and '>' (which were escaped by
1294 # removeHTMLtags()) should not be included in
1295 # URLs, per RFC 2396.
1296 $m2 = array();
1297 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1298 $text = substr($url, $m2[0][1]) . ' ' . $text;
1299 $url = substr($url, 0, $m2[0][1]);
1300 }
1301
1302 # If the link text is an image URL, replace it with an <img> tag
1303 # This happened by accident in the original parser, but some people used it extensively
1304 $img = $this->maybeMakeExternalImage( $text );
1305 if ( $img !== false ) {
1306 $text = $img;
1307 }
1308
1309 $dtrail = '';
1310
1311 # Set linktype for CSS - if URL==text, link is essentially free
1312 $linktype = ($text === $url) ? 'free' : 'text';
1313
1314 # No link text, e.g. [http://domain.tld/some.link]
1315 if ( $text == '' ) {
1316 # Autonumber if allowed. See bug #5918
1317 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1318 $langObj = $this->getFunctionLang();
1319 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1320 $linktype = 'autonumber';
1321 } else {
1322 # Otherwise just use the URL
1323 $text = htmlspecialchars( $url );
1324 $linktype = 'free';
1325 }
1326 } else {
1327 # Have link text, e.g. [http://domain.tld/some.link text]s
1328 # Check for trail
1329 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1330 }
1331
1332 $text = $wgContLang->markNoConversion($text);
1333
1334 $url = Sanitizer::cleanUrl( $url );
1335
1336 # Use the encoded URL
1337 # This means that users can paste URLs directly into the text
1338 # Funny characters like &ouml; aren't valid in URLs anyway
1339 # This was changed in August 2004
1340 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1341 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1342
1343 # Register link in the output object.
1344 # Replace unnecessary URL escape codes with the referenced character
1345 # This prevents spammers from hiding links from the filters
1346 $pasteurized = self::replaceUnusualEscapes( $url );
1347 $this->mOutput->addExternalLink( $pasteurized );
1348 }
1349
1350 wfProfileOut( __METHOD__ );
1351 return $s;
1352 }
1353
1354 /**
1355 * Get an associative array of additional HTML attributes appropriate for a
1356 * particular external link. This currently may include rel => nofollow
1357 * (depending on configuration, namespace, and the URL's domain) and/or a
1358 * target attribute (depending on configuration).
1359 *
1360 * @param string $url Optional URL, to extract the domain from for rel =>
1361 * nofollow if appropriate
1362 * @return array Associative array of HTML attributes
1363 */
1364 function getExternalLinkAttribs( $url = false ) {
1365 $attribs = array();
1366 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1367 $ns = $this->mTitle->getNamespace();
1368 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1369 $attribs['rel'] = 'nofollow';
1370
1371 global $wgNoFollowDomainExceptions;
1372 if ( $wgNoFollowDomainExceptions ) {
1373 $bits = wfParseUrl( $url );
1374 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1375 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1376 if( substr( $bits['host'], -strlen( $domain ) )
1377 == $domain ) {
1378 unset( $attribs['rel'] );
1379 break;
1380 }
1381 }
1382 }
1383 }
1384 }
1385 if ( $this->mOptions->getExternalLinkTarget() ) {
1386 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1387 }
1388 return $attribs;
1389 }
1390
1391
1392 /**
1393 * Replace unusual URL escape codes with their equivalent characters
1394 * @param string
1395 * @return string
1396 * @static
1397 * @todo This can merge genuinely required bits in the path or query string,
1398 * breaking legit URLs. A proper fix would treat the various parts of
1399 * the URL differently; as a workaround, just use the output for
1400 * statistical records, not for actual linking/output.
1401 */
1402 static function replaceUnusualEscapes( $url ) {
1403 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1404 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1405 }
1406
1407 /**
1408 * Callback function used in replaceUnusualEscapes().
1409 * Replaces unusual URL escape codes with their equivalent character
1410 * @static
1411 * @private
1412 */
1413 private static function replaceUnusualEscapesCallback( $matches ) {
1414 $char = urldecode( $matches[0] );
1415 $ord = ord( $char );
1416 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1417 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1418 // No, shouldn't be escaped
1419 return $char;
1420 } else {
1421 // Yes, leave it escaped
1422 return $matches[0];
1423 }
1424 }
1425
1426 /**
1427 * make an image if it's allowed, either through the global
1428 * option, through the exception, or through the on-wiki whitelist
1429 * @private
1430 */
1431 function maybeMakeExternalImage( $url ) {
1432 $sk = $this->mOptions->getSkin();
1433 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1434 $imagesexception = !empty($imagesfrom);
1435 $text = false;
1436 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1437 if( $imagesexception && is_array( $imagesfrom ) ) {
1438 $imagematch = false;
1439 foreach( $imagesfrom as $match ) {
1440 if( strpos( $url, $match ) === 0 ) {
1441 $imagematch = true;
1442 break;
1443 }
1444 }
1445 } elseif( $imagesexception ) {
1446 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1447 } else {
1448 $imagematch = false;
1449 }
1450 if ( $this->mOptions->getAllowExternalImages()
1451 || ( $imagesexception && $imagematch ) ) {
1452 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1453 # Image found
1454 $text = $sk->makeExternalImage( $url );
1455 }
1456 }
1457 if( !$text && $this->mOptions->getEnableImageWhitelist()
1458 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1459 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1460 foreach( $whitelist as $entry ) {
1461 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1462 if( strpos( $entry, '#' ) === 0 || $entry === '' )
1463 continue;
1464 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1465 # Image matches a whitelist entry
1466 $text = $sk->makeExternalImage( $url );
1467 break;
1468 }
1469 }
1470 }
1471 return $text;
1472 }
1473
1474 /**
1475 * Process [[ ]] wikilinks
1476 * @return processed text
1477 *
1478 * @private
1479 */
1480 function replaceInternalLinks( $s ) {
1481 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1482 return $s;
1483 }
1484
1485 /**
1486 * Process [[ ]] wikilinks (RIL)
1487 * @return LinkHolderArray
1488 *
1489 * @private
1490 */
1491 function replaceInternalLinks2( &$s ) {
1492 global $wgContLang;
1493
1494 wfProfileIn( __METHOD__ );
1495
1496 wfProfileIn( __METHOD__.'-setup' );
1497 static $tc = FALSE, $e1, $e1_img;
1498 # the % is needed to support urlencoded titles as well
1499 if ( !$tc ) {
1500 $tc = Title::legalChars() . '#%';
1501 # Match a link having the form [[namespace:link|alternate]]trail
1502 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1503 # Match cases where there is no "]]", which might still be images
1504 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1505 }
1506
1507 $sk = $this->mOptions->getSkin();
1508 $holders = new LinkHolderArray( $this );
1509
1510 #split the entire text string on occurences of [[
1511 $a = StringUtils::explode( '[[', ' ' . $s );
1512 #get the first element (all text up to first [[), and remove the space we added
1513 $s = $a->current();
1514 $a->next();
1515 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1516 $s = substr( $s, 1 );
1517
1518 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1519 $e2 = null;
1520 if ( $useLinkPrefixExtension ) {
1521 # Match the end of a line for a word that's not followed by whitespace,
1522 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1523 $e2 = wfMsgForContent( 'linkprefix' );
1524 }
1525
1526 if( is_null( $this->mTitle ) ) {
1527 wfProfileOut( __METHOD__.'-setup' );
1528 wfProfileOut( __METHOD__ );
1529 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1530 }
1531 $nottalk = !$this->mTitle->isTalkPage();
1532
1533 if ( $useLinkPrefixExtension ) {
1534 $m = array();
1535 if ( preg_match( $e2, $s, $m ) ) {
1536 $first_prefix = $m[2];
1537 } else {
1538 $first_prefix = false;
1539 }
1540 } else {
1541 $prefix = '';
1542 }
1543
1544 if($wgContLang->hasVariants()) {
1545 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1546 } else {
1547 $selflink = array($this->mTitle->getPrefixedText());
1548 }
1549 $useSubpages = $this->areSubpagesAllowed();
1550 wfProfileOut( __METHOD__.'-setup' );
1551
1552 # Loop for each link
1553 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1554 # Check for excessive memory usage
1555 if ( $holders->isBig() ) {
1556 # Too big
1557 # Do the existence check, replace the link holders and clear the array
1558 $holders->replace( $s );
1559 $holders->clear();
1560 }
1561
1562 if ( $useLinkPrefixExtension ) {
1563 wfProfileIn( __METHOD__.'-prefixhandling' );
1564 if ( preg_match( $e2, $s, $m ) ) {
1565 $prefix = $m[2];
1566 $s = $m[1];
1567 } else {
1568 $prefix='';
1569 }
1570 # first link
1571 if($first_prefix) {
1572 $prefix = $first_prefix;
1573 $first_prefix = false;
1574 }
1575 wfProfileOut( __METHOD__.'-prefixhandling' );
1576 }
1577
1578 $might_be_img = false;
1579
1580 wfProfileIn( __METHOD__."-e1" );
1581 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1582 $text = $m[2];
1583 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1584 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1585 # the real problem is with the $e1 regex
1586 # See bug 1300.
1587 #
1588 # Still some problems for cases where the ] is meant to be outside punctuation,
1589 # and no image is in sight. See bug 2095.
1590 #
1591 if( $text !== '' &&
1592 substr( $m[3], 0, 1 ) === ']' &&
1593 strpos($text, '[') !== false
1594 )
1595 {
1596 $text .= ']'; # so that replaceExternalLinks($text) works later
1597 $m[3] = substr( $m[3], 1 );
1598 }
1599 # fix up urlencoded title texts
1600 if( strpos( $m[1], '%' ) !== false ) {
1601 # Should anchors '#' also be rejected?
1602 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1603 }
1604 $trail = $m[3];
1605 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1606 $might_be_img = true;
1607 $text = $m[2];
1608 if ( strpos( $m[1], '%' ) !== false ) {
1609 $m[1] = urldecode($m[1]);
1610 }
1611 $trail = "";
1612 } else { # Invalid form; output directly
1613 $s .= $prefix . '[[' . $line ;
1614 wfProfileOut( __METHOD__."-e1" );
1615 continue;
1616 }
1617 wfProfileOut( __METHOD__."-e1" );
1618 wfProfileIn( __METHOD__."-misc" );
1619
1620 # Don't allow internal links to pages containing
1621 # PROTO: where PROTO is a valid URL protocol; these
1622 # should be external links.
1623 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1624 $s .= $prefix . '[[' . $line ;
1625 wfProfileOut( __METHOD__."-misc" );
1626 continue;
1627 }
1628
1629 # Make subpage if necessary
1630 if ( $useSubpages ) {
1631 $link = $this->maybeDoSubpageLink( $m[1], $text );
1632 } else {
1633 $link = $m[1];
1634 }
1635
1636 $noforce = (substr( $m[1], 0, 1 ) !== ':');
1637 if (!$noforce) {
1638 # Strip off leading ':'
1639 $link = substr( $link, 1 );
1640 }
1641
1642 wfProfileOut( __METHOD__."-misc" );
1643 wfProfileIn( __METHOD__."-title" );
1644 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
1645 if ( $nt === null ) {
1646 $s .= $prefix . '[[' . $line;
1647 wfProfileOut( __METHOD__."-title" );
1648 continue;
1649 }
1650
1651 $ns = $nt->getNamespace();
1652 $iw = $nt->getInterWiki();
1653 wfProfileOut( __METHOD__."-title" );
1654
1655 if ( $might_be_img ) { # if this is actually an invalid link
1656 wfProfileIn( __METHOD__."-might_be_img" );
1657 if ( $ns == NS_FILE && $noforce ) { #but might be an image
1658 $found = false;
1659 while ( true ) {
1660 #look at the next 'line' to see if we can close it there
1661 $a->next();
1662 $next_line = $a->current();
1663 if ( $next_line === false || $next_line === null ) {
1664 break;
1665 }
1666 $m = explode( ']]', $next_line, 3 );
1667 if ( count( $m ) == 3 ) {
1668 # the first ]] closes the inner link, the second the image
1669 $found = true;
1670 $text .= "[[{$m[0]}]]{$m[1]}";
1671 $trail = $m[2];
1672 break;
1673 } elseif ( count( $m ) == 2 ) {
1674 #if there's exactly one ]] that's fine, we'll keep looking
1675 $text .= "[[{$m[0]}]]{$m[1]}";
1676 } else {
1677 #if $next_line is invalid too, we need look no further
1678 $text .= '[[' . $next_line;
1679 break;
1680 }
1681 }
1682 if ( !$found ) {
1683 # we couldn't find the end of this imageLink, so output it raw
1684 #but don't ignore what might be perfectly normal links in the text we've examined
1685 $holders->merge( $this->replaceInternalLinks2( $text ) );
1686 $s .= "{$prefix}[[$link|$text";
1687 # note: no $trail, because without an end, there *is* no trail
1688 wfProfileOut( __METHOD__."-might_be_img" );
1689 continue;
1690 }
1691 } else { #it's not an image, so output it raw
1692 $s .= "{$prefix}[[$link|$text";
1693 # note: no $trail, because without an end, there *is* no trail
1694 wfProfileOut( __METHOD__."-might_be_img" );
1695 continue;
1696 }
1697 wfProfileOut( __METHOD__."-might_be_img" );
1698 }
1699
1700 $wasblank = ( $text == '' );
1701 if ( $wasblank ) $text = $link;
1702
1703 # Link not escaped by : , create the various objects
1704 if ( $noforce ) {
1705
1706 # Interwikis
1707 wfProfileIn( __METHOD__."-interwiki" );
1708 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1709 $this->mOutput->addLanguageLink( $nt->getFullText() );
1710 $s = rtrim($s . $prefix);
1711 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1712 wfProfileOut( __METHOD__."-interwiki" );
1713 continue;
1714 }
1715 wfProfileOut( __METHOD__."-interwiki" );
1716
1717 if ( $ns == NS_FILE ) {
1718 wfProfileIn( __METHOD__."-image" );
1719 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1720 if ( $wasblank ) {
1721 # if no parameters were passed, $text
1722 # becomes something like "File:Foo.png",
1723 # which we don't want to pass on to the
1724 # image generator
1725 $text = '';
1726 } else {
1727 # recursively parse links inside the image caption
1728 # actually, this will parse them in any other parameters, too,
1729 # but it might be hard to fix that, and it doesn't matter ATM
1730 $text = $this->replaceExternalLinks($text);
1731 $holders->merge( $this->replaceInternalLinks2( $text ) );
1732 }
1733 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1734 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1735 }
1736 $this->mOutput->addImage( $nt->getDBkey() );
1737 wfProfileOut( __METHOD__."-image" );
1738 continue;
1739
1740 }
1741
1742 if ( $ns == NS_CATEGORY ) {
1743 wfProfileIn( __METHOD__."-category" );
1744 $s = rtrim($s . "\n"); # bug 87
1745
1746 if ( $wasblank ) {
1747 $sortkey = $this->getDefaultSort();
1748 } else {
1749 $sortkey = $text;
1750 }
1751 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1752 $sortkey = str_replace( "\n", '', $sortkey );
1753 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1754 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1755
1756 /**
1757 * Strip the whitespace Category links produce, see bug 87
1758 * @todo We might want to use trim($tmp, "\n") here.
1759 */
1760 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1761
1762 wfProfileOut( __METHOD__."-category" );
1763 continue;
1764 }
1765 }
1766
1767 # Self-link checking
1768 if( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
1769 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1770 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1771 continue;
1772 }
1773 }
1774
1775 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1776 # FIXME: Should do batch file existence checks, see comment below
1777 if( $ns == NS_MEDIA ) {
1778 wfProfileIn( __METHOD__."-media" );
1779 # Give extensions a chance to select the file revision for us
1780 $skip = $time = false;
1781 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1782 if ( $skip ) {
1783 $link = $sk->link( $nt );
1784 } else {
1785 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1786 }
1787 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1788 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1789 $this->mOutput->addImage( $nt->getDBkey() );
1790 wfProfileOut( __METHOD__."-media" );
1791 continue;
1792 }
1793
1794 wfProfileIn( __METHOD__."-always_known" );
1795 # Some titles, such as valid special pages or files in foreign repos, should
1796 # be shown as bluelinks even though they're not included in the page table
1797 #
1798 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1799 # batch file existence checks for NS_FILE and NS_MEDIA
1800 if( $iw == '' && $nt->isAlwaysKnown() ) {
1801 $this->mOutput->addLink( $nt );
1802 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1803 } else {
1804 # Links will be added to the output link list after checking
1805 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1806 }
1807 wfProfileOut( __METHOD__."-always_known" );
1808 }
1809 wfProfileOut( __METHOD__ );
1810 return $holders;
1811 }
1812
1813 /**
1814 * Make a link placeholder. The text returned can be later resolved to a real link with
1815 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1816 * parsing of interwiki links, and secondly to allow all existence checks and
1817 * article length checks (for stub links) to be bundled into a single query.
1818 *
1819 * @deprecated
1820 */
1821 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1822 return $this->mLinkHolders->makeHolder( $nt, $text, $query, $trail, $prefix );
1823 }
1824
1825 /**
1826 * Render a forced-blue link inline; protect against double expansion of
1827 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1828 * Since this little disaster has to split off the trail text to avoid
1829 * breaking URLs in the following text without breaking trails on the
1830 * wiki links, it's been made into a horrible function.
1831 *
1832 * @param Title $nt
1833 * @param string $text
1834 * @param string $query
1835 * @param string $trail
1836 * @param string $prefix
1837 * @return string HTML-wikitext mix oh yuck
1838 */
1839 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1840 list( $inside, $trail ) = Linker::splitTrail( $trail );
1841 $sk = $this->mOptions->getSkin();
1842 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1843 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1844 return $this->armorLinks( $link ) . $trail;
1845 }
1846
1847 /**
1848 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1849 * going to go through further parsing steps before inline URL expansion.
1850 *
1851 * Not needed quite as much as it used to be since free links are a bit
1852 * more sensible these days. But bracketed links are still an issue.
1853 *
1854 * @param string more-or-less HTML
1855 * @return string less-or-more HTML with NOPARSE bits
1856 */
1857 function armorLinks( $text ) {
1858 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1859 "{$this->mUniqPrefix}NOPARSE$1", $text );
1860 }
1861
1862 /**
1863 * Return true if subpage links should be expanded on this page.
1864 * @return bool
1865 */
1866 function areSubpagesAllowed() {
1867 # Some namespaces don't allow subpages
1868 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
1869 }
1870
1871 /**
1872 * Handle link to subpage if necessary
1873 * @param string $target the source of the link
1874 * @param string &$text the link text, modified as necessary
1875 * @return string the full name of the link
1876 * @private
1877 */
1878 function maybeDoSubpageLink($target, &$text) {
1879 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
1880 }
1881
1882 /**#@+
1883 * Used by doBlockLevels()
1884 * @private
1885 */
1886 /* private */ function closeParagraph() {
1887 $result = '';
1888 if ( $this->mLastSection != '' ) {
1889 $result = '</' . $this->mLastSection . ">\n";
1890 }
1891 $this->mInPre = false;
1892 $this->mLastSection = '';
1893 return $result;
1894 }
1895 # getCommon() returns the length of the longest common substring
1896 # of both arguments, starting at the beginning of both.
1897 #
1898 /* private */ function getCommon( $st1, $st2 ) {
1899 $fl = strlen( $st1 );
1900 $shorter = strlen( $st2 );
1901 if ( $fl < $shorter ) { $shorter = $fl; }
1902
1903 for ( $i = 0; $i < $shorter; ++$i ) {
1904 if ( $st1{$i} != $st2{$i} ) { break; }
1905 }
1906 return $i;
1907 }
1908 # These next three functions open, continue, and close the list
1909 # element appropriate to the prefix character passed into them.
1910 #
1911 /* private */ function openList( $char ) {
1912 $result = $this->closeParagraph();
1913
1914 if ( '*' === $char ) { $result .= '<ul><li>'; }
1915 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1916 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1917 elseif ( ';' === $char ) {
1918 $result .= '<dl><dt>';
1919 $this->mDTopen = true;
1920 }
1921 else { $result = '<!-- ERR 1 -->'; }
1922
1923 return $result;
1924 }
1925
1926 /* private */ function nextItem( $char ) {
1927 if ( '*' === $char || '#' === $char ) { return '</li><li>'; }
1928 elseif ( ':' === $char || ';' === $char ) {
1929 $close = '</dd>';
1930 if ( $this->mDTopen ) { $close = '</dt>'; }
1931 if ( ';' === $char ) {
1932 $this->mDTopen = true;
1933 return $close . '<dt>';
1934 } else {
1935 $this->mDTopen = false;
1936 return $close . '<dd>';
1937 }
1938 }
1939 return '<!-- ERR 2 -->';
1940 }
1941
1942 /* private */ function closeList( $char ) {
1943 if ( '*' === $char ) { $text = '</li></ul>'; }
1944 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1945 elseif ( ':' === $char ) {
1946 if ( $this->mDTopen ) {
1947 $this->mDTopen = false;
1948 $text = '</dt></dl>';
1949 } else {
1950 $text = '</dd></dl>';
1951 }
1952 }
1953 else { return '<!-- ERR 3 -->'; }
1954 return $text."\n";
1955 }
1956 /**#@-*/
1957
1958 /**
1959 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1960 *
1961 * @param $linestart bool whether or not this is at the start of a line.
1962 * @private
1963 * @return string the lists rendered as HTML
1964 */
1965 function doBlockLevels( $text, $linestart ) {
1966 wfProfileIn( __METHOD__ );
1967
1968 # Parsing through the text line by line. The main thing
1969 # happening here is handling of block-level elements p, pre,
1970 # and making lists from lines starting with * # : etc.
1971 #
1972 $textLines = StringUtils::explode( "\n", $text );
1973
1974 $lastPrefix = $output = '';
1975 $this->mDTopen = $inBlockElem = false;
1976 $prefixLength = 0;
1977 $paragraphStack = false;
1978
1979 foreach ( $textLines as $oLine ) {
1980 # Fix up $linestart
1981 if ( !$linestart ) {
1982 $output .= $oLine;
1983 $linestart = true;
1984 continue;
1985 }
1986 // * = ul
1987 // # = ol
1988 // ; = dt
1989 // : = dd
1990
1991 $lastPrefixLength = strlen( $lastPrefix );
1992 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1993 $preOpenMatch = preg_match('/<pre/i', $oLine );
1994 // If not in a <pre> element, scan for and figure out what prefixes are there.
1995 if ( !$this->mInPre ) {
1996 # Multiple prefixes may abut each other for nested lists.
1997 $prefixLength = strspn( $oLine, '*#:;' );
1998 $prefix = substr( $oLine, 0, $prefixLength );
1999
2000 # eh?
2001 // ; and : are both from definition-lists, so they're equivalent
2002 // for the purposes of determining whether or not we need to open/close
2003 // elements.
2004 $prefix2 = str_replace( ';', ':', $prefix );
2005 $t = substr( $oLine, $prefixLength );
2006 $this->mInPre = (bool)$preOpenMatch;
2007 } else {
2008 # Don't interpret any other prefixes in preformatted text
2009 $prefixLength = 0;
2010 $prefix = $prefix2 = '';
2011 $t = $oLine;
2012 }
2013
2014 # List generation
2015 if( $prefixLength && $lastPrefix === $prefix2 ) {
2016 # Same as the last item, so no need to deal with nesting or opening stuff
2017 $output .= $this->nextItem( substr( $prefix, -1 ) );
2018 $paragraphStack = false;
2019
2020 if ( substr( $prefix, -1 ) === ';') {
2021 # The one nasty exception: definition lists work like this:
2022 # ; title : definition text
2023 # So we check for : in the remainder text to split up the
2024 # title and definition, without b0rking links.
2025 $term = $t2 = '';
2026 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2027 $t = $t2;
2028 $output .= $term . $this->nextItem( ':' );
2029 }
2030 }
2031 } elseif( $prefixLength || $lastPrefixLength ) {
2032 // We need to open or close prefixes, or both.
2033
2034 # Either open or close a level...
2035 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2036 $paragraphStack = false;
2037
2038 // Close all the prefixes which aren't shared.
2039 while( $commonPrefixLength < $lastPrefixLength ) {
2040 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2041 --$lastPrefixLength;
2042 }
2043
2044 // Continue the current prefix if appropriate.
2045 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2046 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2047 }
2048
2049 // Open prefixes where appropriate.
2050 while ( $prefixLength > $commonPrefixLength ) {
2051 $char = substr( $prefix, $commonPrefixLength, 1 );
2052 $output .= $this->openList( $char );
2053
2054 if ( ';' === $char ) {
2055 # FIXME: This is dupe of code above
2056 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2057 $t = $t2;
2058 $output .= $term . $this->nextItem( ':' );
2059 }
2060 }
2061 ++$commonPrefixLength;
2062 }
2063 $lastPrefix = $prefix2;
2064 }
2065
2066 // If we have no prefixes, go to paragraph mode.
2067 if( 0 == $prefixLength ) {
2068 wfProfileIn( __METHOD__."-paragraph" );
2069 # No prefix (not in list)--go to paragraph mode
2070 // XXX: use a stack for nestable elements like span, table and div
2071 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2072 $closematch = preg_match(
2073 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2074 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2075 if ( $openmatch or $closematch ) {
2076 $paragraphStack = false;
2077 # TODO bug 5718: paragraph closed
2078 $output .= $this->closeParagraph();
2079 if ( $preOpenMatch and !$preCloseMatch ) {
2080 $this->mInPre = true;
2081 }
2082 if ( $closematch ) {
2083 $inBlockElem = false;
2084 } else {
2085 $inBlockElem = true;
2086 }
2087 } else if ( !$inBlockElem && !$this->mInPre ) {
2088 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' or trim($t) != '' ) ) {
2089 // pre
2090 if ($this->mLastSection !== 'pre') {
2091 $paragraphStack = false;
2092 $output .= $this->closeParagraph().'<pre>';
2093 $this->mLastSection = 'pre';
2094 }
2095 $t = substr( $t, 1 );
2096 } else {
2097 // paragraph
2098 if ( trim($t) == '' ) {
2099 if ( $paragraphStack ) {
2100 $output .= $paragraphStack.'<br />';
2101 $paragraphStack = false;
2102 $this->mLastSection = 'p';
2103 } else {
2104 if ($this->mLastSection !== 'p' ) {
2105 $output .= $this->closeParagraph();
2106 $this->mLastSection = '';
2107 $paragraphStack = '<p>';
2108 } else {
2109 $paragraphStack = '</p><p>';
2110 }
2111 }
2112 } else {
2113 if ( $paragraphStack ) {
2114 $output .= $paragraphStack;
2115 $paragraphStack = false;
2116 $this->mLastSection = 'p';
2117 } else if ($this->mLastSection !== 'p') {
2118 $output .= $this->closeParagraph().'<p>';
2119 $this->mLastSection = 'p';
2120 }
2121 }
2122 }
2123 }
2124 wfProfileOut( __METHOD__."-paragraph" );
2125 }
2126 // somewhere above we forget to get out of pre block (bug 785)
2127 if($preCloseMatch && $this->mInPre) {
2128 $this->mInPre = false;
2129 }
2130 if ($paragraphStack === false) {
2131 $output .= $t."\n";
2132 }
2133 }
2134 while ( $prefixLength ) {
2135 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2136 --$prefixLength;
2137 }
2138 if ( $this->mLastSection != '' ) {
2139 $output .= '</' . $this->mLastSection . '>';
2140 $this->mLastSection = '';
2141 }
2142
2143 wfProfileOut( __METHOD__ );
2144 return $output;
2145 }
2146
2147 /**
2148 * Split up a string on ':', ignoring any occurences inside tags
2149 * to prevent illegal overlapping.
2150 * @param string $str the string to split
2151 * @param string &$before set to everything before the ':'
2152 * @param string &$after set to everything after the ':'
2153 * return string the position of the ':', or false if none found
2154 */
2155 function findColonNoLinks($str, &$before, &$after) {
2156 wfProfileIn( __METHOD__ );
2157
2158 $pos = strpos( $str, ':' );
2159 if( $pos === false ) {
2160 // Nothing to find!
2161 wfProfileOut( __METHOD__ );
2162 return false;
2163 }
2164
2165 $lt = strpos( $str, '<' );
2166 if( $lt === false || $lt > $pos ) {
2167 // Easy; no tag nesting to worry about
2168 $before = substr( $str, 0, $pos );
2169 $after = substr( $str, $pos+1 );
2170 wfProfileOut( __METHOD__ );
2171 return $pos;
2172 }
2173
2174 // Ugly state machine to walk through avoiding tags.
2175 $state = self::COLON_STATE_TEXT;
2176 $stack = 0;
2177 $len = strlen( $str );
2178 for( $i = 0; $i < $len; $i++ ) {
2179 $c = $str{$i};
2180
2181 switch( $state ) {
2182 // (Using the number is a performance hack for common cases)
2183 case 0: // self::COLON_STATE_TEXT:
2184 switch( $c ) {
2185 case "<":
2186 // Could be either a <start> tag or an </end> tag
2187 $state = self::COLON_STATE_TAGSTART;
2188 break;
2189 case ":":
2190 if( $stack == 0 ) {
2191 // We found it!
2192 $before = substr( $str, 0, $i );
2193 $after = substr( $str, $i + 1 );
2194 wfProfileOut( __METHOD__ );
2195 return $i;
2196 }
2197 // Embedded in a tag; don't break it.
2198 break;
2199 default:
2200 // Skip ahead looking for something interesting
2201 $colon = strpos( $str, ':', $i );
2202 if( $colon === false ) {
2203 // Nothing else interesting
2204 wfProfileOut( __METHOD__ );
2205 return false;
2206 }
2207 $lt = strpos( $str, '<', $i );
2208 if( $stack === 0 ) {
2209 if( $lt === false || $colon < $lt ) {
2210 // We found it!
2211 $before = substr( $str, 0, $colon );
2212 $after = substr( $str, $colon + 1 );
2213 wfProfileOut( __METHOD__ );
2214 return $i;
2215 }
2216 }
2217 if( $lt === false ) {
2218 // Nothing else interesting to find; abort!
2219 // We're nested, but there's no close tags left. Abort!
2220 break 2;
2221 }
2222 // Skip ahead to next tag start
2223 $i = $lt;
2224 $state = self::COLON_STATE_TAGSTART;
2225 }
2226 break;
2227 case 1: // self::COLON_STATE_TAG:
2228 // In a <tag>
2229 switch( $c ) {
2230 case ">":
2231 $stack++;
2232 $state = self::COLON_STATE_TEXT;
2233 break;
2234 case "/":
2235 // Slash may be followed by >?
2236 $state = self::COLON_STATE_TAGSLASH;
2237 break;
2238 default:
2239 // ignore
2240 }
2241 break;
2242 case 2: // self::COLON_STATE_TAGSTART:
2243 switch( $c ) {
2244 case "/":
2245 $state = self::COLON_STATE_CLOSETAG;
2246 break;
2247 case "!":
2248 $state = self::COLON_STATE_COMMENT;
2249 break;
2250 case ">":
2251 // Illegal early close? This shouldn't happen D:
2252 $state = self::COLON_STATE_TEXT;
2253 break;
2254 default:
2255 $state = self::COLON_STATE_TAG;
2256 }
2257 break;
2258 case 3: // self::COLON_STATE_CLOSETAG:
2259 // In a </tag>
2260 if( $c === ">" ) {
2261 $stack--;
2262 if( $stack < 0 ) {
2263 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2264 wfProfileOut( __METHOD__ );
2265 return false;
2266 }
2267 $state = self::COLON_STATE_TEXT;
2268 }
2269 break;
2270 case self::COLON_STATE_TAGSLASH:
2271 if( $c === ">" ) {
2272 // Yes, a self-closed tag <blah/>
2273 $state = self::COLON_STATE_TEXT;
2274 } else {
2275 // Probably we're jumping the gun, and this is an attribute
2276 $state = self::COLON_STATE_TAG;
2277 }
2278 break;
2279 case 5: // self::COLON_STATE_COMMENT:
2280 if( $c === "-" ) {
2281 $state = self::COLON_STATE_COMMENTDASH;
2282 }
2283 break;
2284 case self::COLON_STATE_COMMENTDASH:
2285 if( $c === "-" ) {
2286 $state = self::COLON_STATE_COMMENTDASHDASH;
2287 } else {
2288 $state = self::COLON_STATE_COMMENT;
2289 }
2290 break;
2291 case self::COLON_STATE_COMMENTDASHDASH:
2292 if( $c === ">" ) {
2293 $state = self::COLON_STATE_TEXT;
2294 } else {
2295 $state = self::COLON_STATE_COMMENT;
2296 }
2297 break;
2298 default:
2299 throw new MWException( "State machine error in " . __METHOD__ );
2300 }
2301 }
2302 if( $stack > 0 ) {
2303 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2304 return false;
2305 }
2306 wfProfileOut( __METHOD__ );
2307 return false;
2308 }
2309
2310 /**
2311 * Return value of a magic variable (like PAGENAME)
2312 *
2313 * @private
2314 */
2315 function getVariableValue( $index, $frame=false ) {
2316 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2317 global $wgScriptPath, $wgStylePath;
2318
2319 /**
2320 * Some of these require message or data lookups and can be
2321 * expensive to check many times.
2322 */
2323 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2324 if ( isset( $this->mVarCache[$index] ) ) {
2325 return $this->mVarCache[$index];
2326 }
2327 }
2328
2329 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2330 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2331
2332 # Use the time zone
2333 global $wgLocaltimezone;
2334 if ( isset( $wgLocaltimezone ) ) {
2335 $oldtz = date_default_timezone_get();
2336 date_default_timezone_set( $wgLocaltimezone );
2337 }
2338
2339 $localTimestamp = date( 'YmdHis', $ts );
2340 $localMonth = date( 'm', $ts );
2341 $localMonth1 = date( 'n', $ts );
2342 $localMonthName = date( 'n', $ts );
2343 $localDay = date( 'j', $ts );
2344 $localDay2 = date( 'd', $ts );
2345 $localDayOfWeek = date( 'w', $ts );
2346 $localWeek = date( 'W', $ts );
2347 $localYear = date( 'Y', $ts );
2348 $localHour = date( 'H', $ts );
2349 if ( isset( $wgLocaltimezone ) ) {
2350 date_default_timezone_set( $oldtz );
2351 }
2352
2353 switch ( $index ) {
2354 case 'currentmonth':
2355 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2356 break;
2357 case 'currentmonth1':
2358 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2359 break;
2360 case 'currentmonthname':
2361 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2362 break;
2363 case 'currentmonthnamegen':
2364 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2365 break;
2366 case 'currentmonthabbrev':
2367 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2368 break;
2369 case 'currentday':
2370 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2371 break;
2372 case 'currentday2':
2373 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2374 break;
2375 case 'localmonth':
2376 $value = $wgContLang->formatNum( $localMonth );
2377 break;
2378 case 'localmonth1':
2379 $value = $wgContLang->formatNum( $localMonth1 );
2380 break;
2381 case 'localmonthname':
2382 $value = $wgContLang->getMonthName( $localMonthName );
2383 break;
2384 case 'localmonthnamegen':
2385 $value = $wgContLang->getMonthNameGen( $localMonthName );
2386 break;
2387 case 'localmonthabbrev':
2388 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2389 break;
2390 case 'localday':
2391 $value = $wgContLang->formatNum( $localDay );
2392 break;
2393 case 'localday2':
2394 $value = $wgContLang->formatNum( $localDay2 );
2395 break;
2396 case 'pagename':
2397 $value = wfEscapeWikiText( $this->mTitle->getText() );
2398 break;
2399 case 'pagenamee':
2400 $value = $this->mTitle->getPartialURL();
2401 break;
2402 case 'fullpagename':
2403 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2404 break;
2405 case 'fullpagenamee':
2406 $value = $this->mTitle->getPrefixedURL();
2407 break;
2408 case 'subpagename':
2409 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2410 break;
2411 case 'subpagenamee':
2412 $value = $this->mTitle->getSubpageUrlForm();
2413 break;
2414 case 'basepagename':
2415 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2416 break;
2417 case 'basepagenamee':
2418 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2419 break;
2420 case 'talkpagename':
2421 if( $this->mTitle->canTalk() ) {
2422 $talkPage = $this->mTitle->getTalkPage();
2423 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2424 } else {
2425 $value = '';
2426 }
2427 break;
2428 case 'talkpagenamee':
2429 if( $this->mTitle->canTalk() ) {
2430 $talkPage = $this->mTitle->getTalkPage();
2431 $value = $talkPage->getPrefixedUrl();
2432 } else {
2433 $value = '';
2434 }
2435 break;
2436 case 'subjectpagename':
2437 $subjPage = $this->mTitle->getSubjectPage();
2438 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2439 break;
2440 case 'subjectpagenamee':
2441 $subjPage = $this->mTitle->getSubjectPage();
2442 $value = $subjPage->getPrefixedUrl();
2443 break;
2444 case 'revisionid':
2445 // Let the edit saving system know we should parse the page
2446 // *after* a revision ID has been assigned.
2447 $this->mOutput->setFlag( 'vary-revision' );
2448 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2449 $value = $this->mRevisionId;
2450 break;
2451 case 'revisionday':
2452 // Let the edit saving system know we should parse the page
2453 // *after* a revision ID has been assigned. This is for null edits.
2454 $this->mOutput->setFlag( 'vary-revision' );
2455 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2456 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2457 break;
2458 case 'revisionday2':
2459 // Let the edit saving system know we should parse the page
2460 // *after* a revision ID has been assigned. This is for null edits.
2461 $this->mOutput->setFlag( 'vary-revision' );
2462 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2463 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2464 break;
2465 case 'revisionmonth':
2466 // Let the edit saving system know we should parse the page
2467 // *after* a revision ID has been assigned. This is for null edits.
2468 $this->mOutput->setFlag( 'vary-revision' );
2469 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2470 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2471 break;
2472 case 'revisionyear':
2473 // Let the edit saving system know we should parse the page
2474 // *after* a revision ID has been assigned. This is for null edits.
2475 $this->mOutput->setFlag( 'vary-revision' );
2476 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2477 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2478 break;
2479 case 'revisiontimestamp':
2480 // Let the edit saving system know we should parse the page
2481 // *after* a revision ID has been assigned. This is for null edits.
2482 $this->mOutput->setFlag( 'vary-revision' );
2483 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2484 $value = $this->getRevisionTimestamp();
2485 break;
2486 case 'revisionuser':
2487 // Let the edit saving system know we should parse the page
2488 // *after* a revision ID has been assigned. This is for null edits.
2489 $this->mOutput->setFlag( 'vary-revision' );
2490 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2491 $value = $this->getRevisionUser();
2492 break;
2493 case 'namespace':
2494 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2495 break;
2496 case 'namespacee':
2497 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2498 break;
2499 case 'talkspace':
2500 $value = $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2501 break;
2502 case 'talkspacee':
2503 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2504 break;
2505 case 'subjectspace':
2506 $value = $this->mTitle->getSubjectNsText();
2507 break;
2508 case 'subjectspacee':
2509 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2510 break;
2511 case 'currentdayname':
2512 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2513 break;
2514 case 'currentyear':
2515 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2516 break;
2517 case 'currenttime':
2518 $value = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2519 break;
2520 case 'currenthour':
2521 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2522 break;
2523 case 'currentweek':
2524 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2525 // int to remove the padding
2526 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2527 break;
2528 case 'currentdow':
2529 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2530 break;
2531 case 'localdayname':
2532 $value = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2533 break;
2534 case 'localyear':
2535 $value = $wgContLang->formatNum( $localYear, true );
2536 break;
2537 case 'localtime':
2538 $value = $wgContLang->time( $localTimestamp, false, false );
2539 break;
2540 case 'localhour':
2541 $value = $wgContLang->formatNum( $localHour, true );
2542 break;
2543 case 'localweek':
2544 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2545 // int to remove the padding
2546 $value = $wgContLang->formatNum( (int)$localWeek );
2547 break;
2548 case 'localdow':
2549 $value = $wgContLang->formatNum( $localDayOfWeek );
2550 break;
2551 case 'numberofarticles':
2552 $value = $wgContLang->formatNum( SiteStats::articles() );
2553 break;
2554 case 'numberoffiles':
2555 $value = $wgContLang->formatNum( SiteStats::images() );
2556 break;
2557 case 'numberofusers':
2558 $value = $wgContLang->formatNum( SiteStats::users() );
2559 break;
2560 case 'numberofactiveusers':
2561 $value = $wgContLang->formatNum( SiteStats::activeUsers() );
2562 break;
2563 case 'numberofpages':
2564 $value = $wgContLang->formatNum( SiteStats::pages() );
2565 break;
2566 case 'numberofadmins':
2567 $value = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
2568 break;
2569 case 'numberofedits':
2570 $value = $wgContLang->formatNum( SiteStats::edits() );
2571 break;
2572 case 'numberofviews':
2573 $value = $wgContLang->formatNum( SiteStats::views() );
2574 break;
2575 case 'currenttimestamp':
2576 $value = wfTimestamp( TS_MW, $ts );
2577 break;
2578 case 'localtimestamp':
2579 $value = $localTimestamp;
2580 break;
2581 case 'currentversion':
2582 $value = SpecialVersion::getVersion();
2583 break;
2584 case 'sitename':
2585 return $wgSitename;
2586 case 'server':
2587 return $wgServer;
2588 case 'servername':
2589 return $wgServerName;
2590 case 'scriptpath':
2591 return $wgScriptPath;
2592 case 'stylepath':
2593 return $wgStylePath;
2594 case 'directionmark':
2595 return $wgContLang->getDirMark();
2596 case 'contentlanguage':
2597 global $wgContLanguageCode;
2598 return $wgContLanguageCode;
2599 default:
2600 $ret = null;
2601 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) )
2602 return $ret;
2603 else
2604 return null;
2605 }
2606
2607 if ( $index )
2608 $this->mVarCache[$index] = $value;
2609
2610 return $value;
2611 }
2612
2613 /**
2614 * initialise the magic variables (like CURRENTMONTHNAME)
2615 *
2616 * @private
2617 */
2618 function initialiseVariables() {
2619 wfProfileIn( __METHOD__ );
2620 $variableIDs = MagicWord::getVariableIDs();
2621
2622 $this->mVariables = new MagicWordArray( $variableIDs );
2623 wfProfileOut( __METHOD__ );
2624 }
2625
2626 /**
2627 * Preprocess some wikitext and return the document tree.
2628 * This is the ghost of replace_variables().
2629 *
2630 * @param string $text The text to parse
2631 * @param integer flags Bitwise combination of:
2632 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2633 * included. Default is to assume a direct page view.
2634 *
2635 * The generated DOM tree must depend only on the input text and the flags.
2636 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2637 *
2638 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2639 * change in the DOM tree for a given text, must be passed through the section identifier
2640 * in the section edit link and thus back to extractSections().
2641 *
2642 * The output of this function is currently only cached in process memory, but a persistent
2643 * cache may be implemented at a later date which takes further advantage of these strict
2644 * dependency requirements.
2645 *
2646 * @private
2647 */
2648 function preprocessToDom ( $text, $flags = 0 ) {
2649 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2650 return $dom;
2651 }
2652
2653 /*
2654 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2655 */
2656 public static function splitWhitespace( $s ) {
2657 $ltrimmed = ltrim( $s );
2658 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2659 $trimmed = rtrim( $ltrimmed );
2660 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2661 if ( $diff > 0 ) {
2662 $w2 = substr( $ltrimmed, -$diff );
2663 } else {
2664 $w2 = '';
2665 }
2666 return array( $w1, $trimmed, $w2 );
2667 }
2668
2669 /**
2670 * Replace magic variables, templates, and template arguments
2671 * with the appropriate text. Templates are substituted recursively,
2672 * taking care to avoid infinite loops.
2673 *
2674 * Note that the substitution depends on value of $mOutputType:
2675 * self::OT_WIKI: only {{subst:}} templates
2676 * self::OT_PREPROCESS: templates but not extension tags
2677 * self::OT_HTML: all templates and extension tags
2678 *
2679 * @param string $tex The text to transform
2680 * @param PPFrame $frame Object describing the arguments passed to the template.
2681 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2682 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2683 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2684 * @private
2685 */
2686 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2687 # Is there any text? Also, Prevent too big inclusions!
2688 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2689 return $text;
2690 }
2691 wfProfileIn( __METHOD__ );
2692
2693 if ( $frame === false ) {
2694 $frame = $this->getPreprocessor()->newFrame();
2695 } elseif ( !( $frame instanceof PPFrame ) ) {
2696 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2697 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2698 }
2699
2700 $dom = $this->preprocessToDom( $text );
2701 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2702 $text = $frame->expand( $dom, $flags );
2703
2704 wfProfileOut( __METHOD__ );
2705 return $text;
2706 }
2707
2708 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2709 static function createAssocArgs( $args ) {
2710 $assocArgs = array();
2711 $index = 1;
2712 foreach( $args as $arg ) {
2713 $eqpos = strpos( $arg, '=' );
2714 if ( $eqpos === false ) {
2715 $assocArgs[$index++] = $arg;
2716 } else {
2717 $name = trim( substr( $arg, 0, $eqpos ) );
2718 $value = trim( substr( $arg, $eqpos+1 ) );
2719 if ( $value === false ) {
2720 $value = '';
2721 }
2722 if ( $name !== false ) {
2723 $assocArgs[$name] = $value;
2724 }
2725 }
2726 }
2727
2728 return $assocArgs;
2729 }
2730
2731 /**
2732 * Warn the user when a parser limitation is reached
2733 * Will warn at most once the user per limitation type
2734 *
2735 * @param string $limitationType, should be one of:
2736 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2737 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2738 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2739 * @params int $current, $max When an explicit limit has been
2740 * exceeded, provide the values (optional)
2741 */
2742 function limitationWarn( $limitationType, $current=null, $max=null) {
2743 //does no harm if $current and $max are present but are unnecessary for the message
2744 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2745 $this->mOutput->addWarning( $warning );
2746 $this->addTrackingCategory( "$limitationType-category" );
2747 }
2748
2749 /**
2750 * Return the text of a template, after recursively
2751 * replacing any variables or templates within the template.
2752 *
2753 * @param array $piece The parts of the template
2754 * $piece['title']: the title, i.e. the part before the |
2755 * $piece['parts']: the parameter array
2756 * $piece['lineStart']: whether the brace was at the start of a line
2757 * @param PPFrame The current frame, contains template arguments
2758 * @return string the text of the template
2759 * @private
2760 */
2761 function braceSubstitution( $piece, $frame ) {
2762 global $wgContLang, $wgNonincludableNamespaces;
2763 wfProfileIn( __METHOD__ );
2764 wfProfileIn( __METHOD__.'-setup' );
2765
2766 # Flags
2767 $found = false; # $text has been filled
2768 $nowiki = false; # wiki markup in $text should be escaped
2769 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2770 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2771 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2772 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2773
2774 # Title object, where $text came from
2775 $title = null;
2776
2777 # $part1 is the bit before the first |, and must contain only title characters.
2778 # Various prefixes will be stripped from it later.
2779 $titleWithSpaces = $frame->expand( $piece['title'] );
2780 $part1 = trim( $titleWithSpaces );
2781 $titleText = false;
2782
2783 # Original title text preserved for various purposes
2784 $originalTitle = $part1;
2785
2786 # $args is a list of argument nodes, starting from index 0, not including $part1
2787 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2788 wfProfileOut( __METHOD__.'-setup' );
2789
2790 # SUBST
2791 wfProfileIn( __METHOD__.'-modifiers' );
2792 if ( !$found ) {
2793 $mwSubst = MagicWord::get( 'subst' );
2794 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2795 # One of two possibilities is true:
2796 # 1) Found SUBST but not in the PST phase
2797 # 2) Didn't find SUBST and in the PST phase
2798 # In either case, return without further processing
2799 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2800 $isLocalObj = true;
2801 $found = true;
2802 }
2803 }
2804
2805 # Variables
2806 if ( !$found && $args->getLength() == 0 ) {
2807 $id = $this->mVariables->matchStartToEnd( $part1 );
2808 if ( $id !== false ) {
2809 $text = $this->getVariableValue( $id, $frame );
2810 if (MagicWord::getCacheTTL($id)>-1)
2811 $this->mOutput->mContainsOldMagic = true;
2812 $found = true;
2813 }
2814 }
2815
2816 # MSG, MSGNW and RAW
2817 if ( !$found ) {
2818 # Check for MSGNW:
2819 $mwMsgnw = MagicWord::get( 'msgnw' );
2820 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2821 $nowiki = true;
2822 } else {
2823 # Remove obsolete MSG:
2824 $mwMsg = MagicWord::get( 'msg' );
2825 $mwMsg->matchStartAndRemove( $part1 );
2826 }
2827
2828 # Check for RAW:
2829 $mwRaw = MagicWord::get( 'raw' );
2830 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2831 $forceRawInterwiki = true;
2832 }
2833 }
2834 wfProfileOut( __METHOD__.'-modifiers' );
2835
2836 # Parser functions
2837 if ( !$found ) {
2838 wfProfileIn( __METHOD__ . '-pfunc' );
2839
2840 $colonPos = strpos( $part1, ':' );
2841 if ( $colonPos !== false ) {
2842 # Case sensitive functions
2843 $function = substr( $part1, 0, $colonPos );
2844 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2845 $function = $this->mFunctionSynonyms[1][$function];
2846 } else {
2847 # Case insensitive functions
2848 $function = $wgContLang->lc( $function );
2849 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2850 $function = $this->mFunctionSynonyms[0][$function];
2851 } else {
2852 $function = false;
2853 }
2854 }
2855 if ( $function ) {
2856 list( $callback, $flags ) = $this->mFunctionHooks[$function];
2857 $initialArgs = array( &$this );
2858 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
2859 if ( $flags & SFH_OBJECT_ARGS ) {
2860 # Add a frame parameter, and pass the arguments as an array
2861 $allArgs = $initialArgs;
2862 $allArgs[] = $frame;
2863 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2864 $funcArgs[] = $args->item( $i );
2865 }
2866 $allArgs[] = $funcArgs;
2867 } else {
2868 # Convert arguments to plain text
2869 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2870 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2871 }
2872 $allArgs = array_merge( $initialArgs, $funcArgs );
2873 }
2874
2875 # Workaround for PHP bug 35229 and similar
2876 if ( !is_callable( $callback ) ) {
2877 wfProfileOut( __METHOD__ . '-pfunc' );
2878 wfProfileOut( __METHOD__ );
2879 throw new MWException( "Tag hook for $function is not callable\n" );
2880 }
2881 $result = call_user_func_array( $callback, $allArgs );
2882 $found = true;
2883 $noparse = true;
2884 $preprocessFlags = 0;
2885
2886 if ( is_array( $result ) ) {
2887 if ( isset( $result[0] ) ) {
2888 $text = $result[0];
2889 unset( $result[0] );
2890 }
2891
2892 // Extract flags into the local scope
2893 // This allows callers to set flags such as nowiki, found, etc.
2894 extract( $result );
2895 } else {
2896 $text = $result;
2897 }
2898 if ( !$noparse ) {
2899 $text = $this->preprocessToDom( $text, $preprocessFlags );
2900 $isChildObj = true;
2901 }
2902 }
2903 }
2904 wfProfileOut( __METHOD__ . '-pfunc' );
2905 }
2906
2907 # Finish mangling title and then check for loops.
2908 # Set $title to a Title object and $titleText to the PDBK
2909 if ( !$found ) {
2910 $ns = NS_TEMPLATE;
2911 # Split the title into page and subpage
2912 $subpage = '';
2913 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2914 if ($subpage !== '') {
2915 $ns = $this->mTitle->getNamespace();
2916 }
2917 $title = Title::newFromText( $part1, $ns );
2918 if ( $title ) {
2919 $titleText = $title->getPrefixedText();
2920 # Check for language variants if the template is not found
2921 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2922 $wgContLang->findVariantLink( $part1, $title, true );
2923 }
2924 # Do recursion depth check
2925 $limit = $this->mOptions->getMaxTemplateDepth();
2926 if ( $frame->depth >= $limit ) {
2927 $found = true;
2928 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2929 }
2930 }
2931 }
2932
2933 # Load from database
2934 if ( !$found && $title ) {
2935 wfProfileIn( __METHOD__ . '-loadtpl' );
2936 if ( !$title->isExternal() ) {
2937 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2938 $text = SpecialPage::capturePath( $title );
2939 if ( is_string( $text ) ) {
2940 $found = true;
2941 $isHTML = true;
2942 $this->disableCache();
2943 }
2944 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2945 $found = false; //access denied
2946 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
2947 } else {
2948 list( $text, $title ) = $this->getTemplateDom( $title );
2949 if ( $text !== false ) {
2950 $found = true;
2951 $isChildObj = true;
2952 }
2953 }
2954
2955 # If the title is valid but undisplayable, make a link to it
2956 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2957 $text = "[[:$titleText]]";
2958 $found = true;
2959 }
2960 } elseif ( $title->isTrans() ) {
2961 // Interwiki transclusion
2962 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2963 $text = $this->interwikiTransclude( $title, 'render' );
2964 $isHTML = true;
2965 } else {
2966 $text = $this->interwikiTransclude( $title, 'raw' );
2967 // Preprocess it like a template
2968 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
2969 $isChildObj = true;
2970 }
2971 $found = true;
2972 }
2973
2974 # Do infinite loop check
2975 # This has to be done after redirect resolution to avoid infinite loops via redirects
2976 if ( !$frame->loopCheck( $title ) ) {
2977 $found = true;
2978 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2979 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
2980 }
2981 wfProfileOut( __METHOD__ . '-loadtpl' );
2982 }
2983
2984 # If we haven't found text to substitute by now, we're done
2985 # Recover the source wikitext and return it
2986 if ( !$found ) {
2987 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2988 wfProfileOut( __METHOD__ );
2989 return array( 'object' => $text );
2990 }
2991
2992 # Expand DOM-style return values in a child frame
2993 if ( $isChildObj ) {
2994 # Clean up argument array
2995 $newFrame = $frame->newChild( $args, $title );
2996
2997 if ( $nowiki ) {
2998 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
2999 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3000 # Expansion is eligible for the empty-frame cache
3001 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3002 $text = $this->mTplExpandCache[$titleText];
3003 } else {
3004 $text = $newFrame->expand( $text );
3005 $this->mTplExpandCache[$titleText] = $text;
3006 }
3007 } else {
3008 # Uncached expansion
3009 $text = $newFrame->expand( $text );
3010 }
3011 }
3012 if ( $isLocalObj && $nowiki ) {
3013 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3014 $isLocalObj = false;
3015 }
3016
3017 # Replace raw HTML by a placeholder
3018 # Add a blank line preceding, to prevent it from mucking up
3019 # immediately preceding headings
3020 if ( $isHTML ) {
3021 $text = "\n\n" . $this->insertStripItem( $text );
3022 }
3023 # Escape nowiki-style return values
3024 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3025 $text = wfEscapeWikiText( $text );
3026 }
3027 # Bug 529: if the template begins with a table or block-level
3028 # element, it should be treated as beginning a new line.
3029 # This behaviour is somewhat controversial.
3030 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3031 $text = "\n" . $text;
3032 }
3033
3034 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3035 # Error, oversize inclusion
3036 $text = "[[$originalTitle]]" .
3037 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3038 $this->limitationWarn( 'post-expand-template-inclusion' );
3039 }
3040
3041 if ( $isLocalObj ) {
3042 $ret = array( 'object' => $text );
3043 } else {
3044 $ret = array( 'text' => $text );
3045 }
3046
3047 wfProfileOut( __METHOD__ );
3048 return $ret;
3049 }
3050
3051 /**
3052 * Get the semi-parsed DOM representation of a template with a given title,
3053 * and its redirect destination title. Cached.
3054 */
3055 function getTemplateDom( $title ) {
3056 $cacheTitle = $title;
3057 $titleText = $title->getPrefixedDBkey();
3058
3059 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3060 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3061 $title = Title::makeTitle( $ns, $dbk );
3062 $titleText = $title->getPrefixedDBkey();
3063 }
3064 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3065 return array( $this->mTplDomCache[$titleText], $title );
3066 }
3067
3068 // Cache miss, go to the database
3069 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3070
3071 if ( $text === false ) {
3072 $this->mTplDomCache[$titleText] = false;
3073 return array( false, $title );
3074 }
3075
3076 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3077 $this->mTplDomCache[ $titleText ] = $dom;
3078
3079 if (! $title->equals($cacheTitle)) {
3080 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3081 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3082 }
3083
3084 return array( $dom, $title );
3085 }
3086
3087 /**
3088 * Fetch the unparsed text of a template and register a reference to it.
3089 */
3090 function fetchTemplateAndTitle( $title ) {
3091 $templateCb = $this->mOptions->getTemplateCallback();
3092 $stuff = call_user_func( $templateCb, $title, $this );
3093 $text = $stuff['text'];
3094 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3095 if ( isset( $stuff['deps'] ) ) {
3096 foreach ( $stuff['deps'] as $dep ) {
3097 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3098 }
3099 }
3100 return array($text,$finalTitle);
3101 }
3102
3103 function fetchTemplate( $title ) {
3104 $rv = $this->fetchTemplateAndTitle($title);
3105 return $rv[0];
3106 }
3107
3108 /**
3109 * Static function to get a template
3110 * Can be overridden via ParserOptions::setTemplateCallback().
3111 */
3112 static function statelessFetchTemplate( $title, $parser=false ) {
3113 $text = $skip = false;
3114 $finalTitle = $title;
3115 $deps = array();
3116
3117 // Loop to fetch the article, with up to 1 redirect
3118 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3119 # Give extensions a chance to select the revision instead
3120 $id = false; // Assume current
3121 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3122
3123 if( $skip ) {
3124 $text = false;
3125 $deps[] = array(
3126 'title' => $title,
3127 'page_id' => $title->getArticleID(),
3128 'rev_id' => null );
3129 break;
3130 }
3131 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3132 $rev_id = $rev ? $rev->getId() : 0;
3133 // If there is no current revision, there is no page
3134 if( $id === false && !$rev ) {
3135 $linkCache = LinkCache::singleton();
3136 $linkCache->addBadLinkObj( $title );
3137 }
3138
3139 $deps[] = array(
3140 'title' => $title,
3141 'page_id' => $title->getArticleID(),
3142 'rev_id' => $rev_id );
3143
3144 if( $rev ) {
3145 $text = $rev->getText();
3146 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3147 global $wgContLang;
3148 $message = $wgContLang->lcfirst( $title->getText() );
3149 $text = wfMsgForContentNoTrans( $message );
3150 if( wfEmptyMsg( $message, $text ) ) {
3151 $text = false;
3152 break;
3153 }
3154 } else {
3155 break;
3156 }
3157 if ( $text === false ) {
3158 break;
3159 }
3160 // Redirect?
3161 $finalTitle = $title;
3162 $title = Title::newFromRedirect( $text );
3163 }
3164 return array(
3165 'text' => $text,
3166 'finalTitle' => $finalTitle,
3167 'deps' => $deps );
3168 }
3169
3170 /**
3171 * Transclude an interwiki link.
3172 */
3173 function interwikiTransclude( $title, $action ) {
3174 global $wgEnableScaryTranscluding;
3175
3176 if (!$wgEnableScaryTranscluding)
3177 return wfMsg('scarytranscludedisabled');
3178
3179 $url = $title->getFullUrl( "action=$action" );
3180
3181 if (strlen($url) > 255)
3182 return wfMsg('scarytranscludetoolong');
3183 return $this->fetchScaryTemplateMaybeFromCache($url);
3184 }
3185
3186 function fetchScaryTemplateMaybeFromCache($url) {
3187 global $wgTranscludeCacheExpiry;
3188 $dbr = wfGetDB(DB_SLAVE);
3189 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3190 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3191 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3192 if ($obj) {
3193 return $obj->tc_contents;
3194 }
3195
3196 $text = Http::get($url);
3197 if (!$text)
3198 return wfMsg('scarytranscludefailed', $url);
3199
3200 $dbw = wfGetDB(DB_MASTER);
3201 $dbw->replace('transcache', array('tc_url'), array(
3202 'tc_url' => $url,
3203 'tc_time' => $dbw->timestamp( time() ),
3204 'tc_contents' => $text));
3205 return $text;
3206 }
3207
3208
3209 /**
3210 * Triple brace replacement -- used for template arguments
3211 * @private
3212 */
3213 function argSubstitution( $piece, $frame ) {
3214 wfProfileIn( __METHOD__ );
3215
3216 $error = false;
3217 $parts = $piece['parts'];
3218 $nameWithSpaces = $frame->expand( $piece['title'] );
3219 $argName = trim( $nameWithSpaces );
3220 $object = false;
3221 $text = $frame->getArgument( $argName );
3222 if ( $text === false && $parts->getLength() > 0
3223 && (
3224 $this->ot['html']
3225 || $this->ot['pre']
3226 || ( $this->ot['wiki'] && $frame->isTemplate() )
3227 )
3228 ) {
3229 # No match in frame, use the supplied default
3230 $object = $parts->item( 0 )->getChildren();
3231 }
3232 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3233 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3234 $this->limitationWarn( 'post-expand-template-argument' );
3235 }
3236
3237 if ( $text === false && $object === false ) {
3238 # No match anywhere
3239 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3240 }
3241 if ( $error !== false ) {
3242 $text .= $error;
3243 }
3244 if ( $object !== false ) {
3245 $ret = array( 'object' => $object );
3246 } else {
3247 $ret = array( 'text' => $text );
3248 }
3249
3250 wfProfileOut( __METHOD__ );
3251 return $ret;
3252 }
3253
3254 /**
3255 * Return the text to be used for a given extension tag.
3256 * This is the ghost of strip().
3257 *
3258 * @param array $params Associative array of parameters:
3259 * name PPNode for the tag name
3260 * attr PPNode for unparsed text where tag attributes are thought to be
3261 * attributes Optional associative array of parsed attributes
3262 * inner Contents of extension element
3263 * noClose Original text did not have a close tag
3264 * @param PPFrame $frame
3265 */
3266 function extensionSubstitution( $params, $frame ) {
3267 global $wgRawHtml, $wgContLang;
3268
3269 $name = $frame->expand( $params['name'] );
3270 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3271 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3272
3273 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
3274
3275 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
3276 ( $this->ot['html'] || $this->ot['pre'] );
3277 if ( $this->ot['html'] || $isFunctionTag ) {
3278 $name = strtolower( $name );
3279 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3280 if ( isset( $params['attributes'] ) ) {
3281 $attributes = $attributes + $params['attributes'];
3282 }
3283 switch ( $name ) {
3284 case 'html':
3285 if( $wgRawHtml ) {
3286 $output = $content;
3287 break;
3288 } else {
3289 throw new MWException( '<html> extension tag encountered unexpectedly' );
3290 }
3291 case 'nowiki':
3292 $content = strtr($content, array('-{' => '-&#123;', '}-' => '&#125;-'));
3293 $output = Xml::escapeTagsOnly( $content );
3294 break;
3295 case 'gallery':
3296 $output = $this->renderImageGallery( $content, $attributes );
3297 break;
3298 case 'a':
3299 $output = $this->renderHyperlink( $content, $attributes, $frame );
3300 break;
3301 case 'math':
3302 if ( $this->mOptions->getUseTeX() ) {
3303 $output = $wgContLang->armourMath(
3304 MathRenderer::renderMath( $content, $attributes ) );
3305 break;
3306 }
3307 /* else let a tag hook handle it (bug 21222) */
3308 default:
3309 if( isset( $this->mTagHooks[$name] ) ) {
3310 # Workaround for PHP bug 35229 and similar
3311 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3312 throw new MWException( "Tag hook for $name is not callable\n" );
3313 }
3314 $output = call_user_func_array( $this->mTagHooks[$name],
3315 array( $content, $attributes, $this, $frame ) );
3316 } elseif( isset( $this->mFunctionTagHooks[$name] ) ) {
3317 list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
3318 if( !is_callable( $callback ) )
3319 throw new MWException( "Tag hook for $name is not callable\n" );
3320
3321 $output = call_user_func_array( $callback,
3322 array( &$this, $frame, $content, $attributes ) );
3323 } else {
3324 $output = '<span class="error">Invalid tag extension name: ' .
3325 htmlspecialchars( $name ) . '</span>';
3326 }
3327 }
3328 } else {
3329 if ( is_null( $attrText ) ) {
3330 $attrText = '';
3331 }
3332 if ( isset( $params['attributes'] ) ) {
3333 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3334 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3335 htmlspecialchars( $attrValue ) . '"';
3336 }
3337 }
3338 if ( $content === null ) {
3339 $output = "<$name$attrText/>";
3340 } else {
3341 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3342 $output = "<$name$attrText>$content$close";
3343 }
3344 }
3345
3346 if( $isFunctionTag ) {
3347 return $output;
3348 } elseif ( $name === 'html' || $name === 'nowiki' ) {
3349 $this->mStripState->nowiki->setPair( $marker, $output );
3350 } else {
3351 $this->mStripState->general->setPair( $marker, $output );
3352 }
3353 return $marker;
3354 }
3355
3356 /**
3357 * Increment an include size counter
3358 *
3359 * @param string $type The type of expansion
3360 * @param integer $size The size of the text
3361 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3362 */
3363 function incrementIncludeSize( $type, $size ) {
3364 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3365 return false;
3366 } else {
3367 $this->mIncludeSizes[$type] += $size;
3368 return true;
3369 }
3370 }
3371
3372 /**
3373 * Increment the expensive function count
3374 *
3375 * @return boolean False if the limit has been exceeded
3376 */
3377 function incrementExpensiveFunctionCount() {
3378 global $wgExpensiveParserFunctionLimit;
3379 $this->mExpensiveFunctionCount++;
3380 if($this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit) {
3381 return true;
3382 }
3383 return false;
3384 }
3385
3386 /**
3387 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3388 * Fills $this->mDoubleUnderscores, returns the modified text
3389 */
3390 function doDoubleUnderscore( $text ) {
3391 global $wgDisableLangConversion;
3392 wfProfileIn( __METHOD__ );
3393
3394 // The position of __TOC__ needs to be recorded
3395 $mw = MagicWord::get( 'toc' );
3396 if( $mw->match( $text ) ) {
3397 $this->mShowToc = true;
3398 $this->mForceTocPosition = true;
3399
3400 // Set a placeholder. At the end we'll fill it in with the TOC.
3401 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3402
3403 // Only keep the first one.
3404 $text = $mw->replace( '', $text );
3405 }
3406
3407 // Now match and remove the rest of them
3408 $mwa = MagicWord::getDoubleUnderscoreArray();
3409 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3410
3411 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3412 $this->mOutput->mNoGallery = true;
3413 }
3414 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3415 $this->mShowToc = false;
3416 }
3417 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3418 $this->mOutput->setProperty( 'hiddencat', 'y' );
3419 $this->addTrackingCategory( 'hidden-category-category' );
3420 }
3421 # (bug 8068) Allow control over whether robots index a page.
3422 #
3423 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3424 # is not desirable, the last one on the page should win.
3425 if( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3426 $this->mOutput->setIndexPolicy( 'noindex' );
3427 $this->addTrackingCategory( 'noindex-category' );
3428 }
3429 if( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ){
3430 $this->mOutput->setIndexPolicy( 'index' );
3431 $this->addTrackingCategory( 'index-category' );
3432 }
3433
3434 if ( !$wgDisableLangConversion ) {
3435 if( isset( $this->mDoubleUnderscores['notitleconvert'] ) ){
3436 $this->mDoTitleConvert = false;
3437 }
3438
3439 // Don't convert talk pages
3440 if( isset( $this->mDoubleUnderscores['nocontentconvert'] )
3441 && !$this->mTitle->isTalkPage() ){
3442 $this->mDoContentConvert = false;
3443 }
3444 }
3445
3446 wfProfileOut( __METHOD__ );
3447 return $text;
3448 }
3449
3450 /**
3451 * Add a tracking category, getting the title from a system message,
3452 * or print a debug message if the title is invalid.
3453 * @param $msg String message key
3454 * @return Bool whether the addition was successful
3455 */
3456 protected function addTrackingCategory( $msg ){
3457 $cat = wfMsgForContent( $msg );
3458
3459 # Allow tracking categories to be disabled by setting them to "-"
3460 if( $cat === '-' ) return false;
3461
3462 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
3463 if ( $containerCategory ) {
3464 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3465 return true;
3466 } else {
3467 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
3468 return false;
3469 }
3470 }
3471
3472 /**
3473 * This function accomplishes several tasks:
3474 * 1) Auto-number headings if that option is enabled
3475 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3476 * 3) Add a Table of contents on the top for users who have enabled the option
3477 * 4) Auto-anchor headings
3478 *
3479 * It loops through all headlines, collects the necessary data, then splits up the
3480 * string and re-inserts the newly formatted headlines.
3481 *
3482 * @param string $text
3483 * @param string $origText Original, untouched wikitext
3484 * @param boolean $isMain
3485 * @private
3486 */
3487 function formatHeadings( $text, $origText, $isMain=true ) {
3488 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3489
3490 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3491 $showEditLink = $this->mOptions->getEditSection();
3492
3493 // Do not call quickUserCan unless necessary
3494 if( $showEditLink && !$this->mTitle->quickUserCan( 'edit' ) ) {
3495 $showEditLink = 0;
3496 }
3497
3498 # Inhibit editsection links if requested in the page
3499 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) || $this->mOptions->getIsPrintable() ) {
3500 $showEditLink = 0;
3501 }
3502
3503 # Get all headlines for numbering them and adding funky stuff like [edit]
3504 # links - this is for later, but we need the number of headlines right now
3505 $matches = array();
3506 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3507
3508 # if there are fewer than 4 headlines in the article, do not show TOC
3509 # unless it's been explicitly enabled.
3510 $enoughToc = $this->mShowToc &&
3511 (($numMatches >= 4) || $this->mForceTocPosition);
3512
3513 # Allow user to stipulate that a page should have a "new section"
3514 # link added via __NEWSECTIONLINK__
3515 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3516 $this->mOutput->setNewSection( true );
3517 }
3518
3519 # Allow user to remove the "new section"
3520 # link via __NONEWSECTIONLINK__
3521 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
3522 $this->mOutput->hideNewSection( true );
3523 }
3524
3525 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3526 # override above conditions and always show TOC above first header
3527 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3528 $this->mShowToc = true;
3529 $enoughToc = true;
3530 }
3531
3532 # We need this to perform operations on the HTML
3533 $sk = $this->mOptions->getSkin();
3534
3535 # headline counter
3536 $headlineCount = 0;
3537 $numVisible = 0;
3538
3539 # Ugh .. the TOC should have neat indentation levels which can be
3540 # passed to the skin functions. These are determined here
3541 $toc = '';
3542 $full = '';
3543 $head = array();
3544 $sublevelCount = array();
3545 $levelCount = array();
3546 $toclevel = 0;
3547 $level = 0;
3548 $prevlevel = 0;
3549 $toclevel = 0;
3550 $prevtoclevel = 0;
3551 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3552 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3553 $oldType = $this->mOutputType;
3554 $this->setOutputType( self::OT_WIKI );
3555 $frame = $this->getPreprocessor()->newFrame();
3556 $root = $this->preprocessToDom( $origText );
3557 $node = $root->getFirstChild();
3558 $byteOffset = 0;
3559 $tocraw = array();
3560
3561 foreach( $matches[3] as $headline ) {
3562 $isTemplate = false;
3563 $titleText = false;
3564 $sectionIndex = false;
3565 $numbering = '';
3566 $markerMatches = array();
3567 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3568 $serial = $markerMatches[1];
3569 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3570 $isTemplate = ($titleText != $baseTitleText);
3571 $headline = preg_replace("/^$markerRegex/", "", $headline);
3572 }
3573
3574 if( $toclevel ) {
3575 $prevlevel = $level;
3576 $prevtoclevel = $toclevel;
3577 }
3578 $level = $matches[1][$headlineCount];
3579
3580 if ( $level > $prevlevel ) {
3581 # Increase TOC level
3582 $toclevel++;
3583 $sublevelCount[$toclevel] = 0;
3584 if( $toclevel<$wgMaxTocLevel ) {
3585 $prevtoclevel = $toclevel;
3586 $toc .= $sk->tocIndent();
3587 $numVisible++;
3588 }
3589 }
3590 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3591 # Decrease TOC level, find level to jump to
3592
3593 for ($i = $toclevel; $i > 0; $i--) {
3594 if ( $levelCount[$i] == $level ) {
3595 # Found last matching level
3596 $toclevel = $i;
3597 break;
3598 }
3599 elseif ( $levelCount[$i] < $level ) {
3600 # Found first matching level below current level
3601 $toclevel = $i + 1;
3602 break;
3603 }
3604 }
3605 if( $i == 0 ) $toclevel = 1;
3606 if( $toclevel<$wgMaxTocLevel ) {
3607 if($prevtoclevel < $wgMaxTocLevel) {
3608 # Unindent only if the previous toc level was shown :p
3609 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3610 $prevtoclevel = $toclevel;
3611 } else {
3612 $toc .= $sk->tocLineEnd();
3613 }
3614 }
3615 }
3616 else {
3617 # No change in level, end TOC line
3618 if( $toclevel<$wgMaxTocLevel ) {
3619 $toc .= $sk->tocLineEnd();
3620 }
3621 }
3622
3623 $levelCount[$toclevel] = $level;
3624
3625 # count number of headlines for each level
3626 @$sublevelCount[$toclevel]++;
3627 $dot = 0;
3628 for( $i = 1; $i <= $toclevel; $i++ ) {
3629 if( !empty( $sublevelCount[$i] ) ) {
3630 if( $dot ) {
3631 $numbering .= '.';
3632 }
3633 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3634 $dot = 1;
3635 }
3636 }
3637
3638 # The safe header is a version of the header text safe to use for links
3639 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3640 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3641
3642 # Remove link placeholders by the link text.
3643 # <!--LINK number-->
3644 # turns into
3645 # link text with suffix
3646 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3647
3648 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3649 $tocline = preg_replace(
3650 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3651 array( '', '<$1>'),
3652 $safeHeadline
3653 );
3654 $tocline = trim( $tocline );
3655
3656 # For the anchor, strip out HTML-y stuff period
3657 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3658 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3659 $safeHeadline = trim( $safeHeadline );
3660
3661 # Save headline for section edit hint before it's escaped
3662 $headlineHint = $safeHeadline;
3663
3664 if ( $wgEnforceHtmlIds ) {
3665 $legacyHeadline = false;
3666 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
3667 'noninitial' );
3668 } else {
3669 # For reverse compatibility, provide an id that's
3670 # HTML4-compatible, like we used to.
3671 #
3672 # It may be worth noting, academically, that it's possible for
3673 # the legacy anchor to conflict with a non-legacy headline
3674 # anchor on the page. In this case likely the "correct" thing
3675 # would be to either drop the legacy anchors or make sure
3676 # they're numbered first. However, this would require people
3677 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3678 # manually, so let's not bother worrying about it.
3679 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
3680 'noninitial' );
3681 $safeHeadline = Sanitizer::escapeId( $safeHeadline, 'xml' );
3682
3683 if ( $legacyHeadline == $safeHeadline ) {
3684 # No reason to have both (in fact, we can't)
3685 $legacyHeadline = false;
3686 } elseif ( $legacyHeadline != Sanitizer::escapeId(
3687 $legacyHeadline, 'xml' ) ) {
3688 # The legacy id is invalid XML. We used to allow this, but
3689 # there's no reason to do so anymore. Backward
3690 # compatibility will fail slightly in this case, but it's
3691 # no big deal.
3692 $legacyHeadline = false;
3693 }
3694 }
3695
3696 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3697 # Does this apply to Unicode characters? Because we aren't
3698 # handling those here.
3699 $arrayKey = strtolower( $safeHeadline );
3700 if ( $legacyHeadline === false ) {
3701 $legacyArrayKey = false;
3702 } else {
3703 $legacyArrayKey = strtolower( $legacyHeadline );
3704 }
3705
3706 # count how many in assoc. array so we can track dupes in anchors
3707 if ( isset( $refers[$arrayKey] ) ) {
3708 $refers[$arrayKey]++;
3709 } else {
3710 $refers[$arrayKey] = 1;
3711 }
3712 if ( isset( $refers[$legacyArrayKey] ) ) {
3713 $refers[$legacyArrayKey]++;
3714 } else {
3715 $refers[$legacyArrayKey] = 1;
3716 }
3717
3718 # Don't number the heading if it is the only one (looks silly)
3719 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3720 # the two are different if the line contains a link
3721 $headline=$numbering . ' ' . $headline;
3722 }
3723
3724 # Create the anchor for linking from the TOC to the section
3725 $anchor = $safeHeadline;
3726 $legacyAnchor = $legacyHeadline;
3727 if ( $refers[$arrayKey] > 1 ) {
3728 $anchor .= '_' . $refers[$arrayKey];
3729 }
3730 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3731 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3732 }
3733 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3734 $toc .= $sk->tocLine($anchor, $tocline,
3735 $numbering, $toclevel, ($isTemplate ? false : $sectionIndex));
3736 }
3737
3738 # Add the section to the section tree
3739 # Find the DOM node for this header
3740 while ( $node && !$isTemplate ) {
3741 if ( $node->getName() === 'h' ) {
3742 $bits = $node->splitHeading();
3743 if ( $bits['i'] == $sectionIndex )
3744 break;
3745 }
3746 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
3747 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
3748 $node = $node->getNextSibling();
3749 }
3750 $tocraw[] = array(
3751 'toclevel' => $toclevel,
3752 'level' => $level,
3753 'line' => $tocline,
3754 'number' => $numbering,
3755 'index' => ($isTemplate ? 'T-' : '' ) . $sectionIndex,
3756 'fromtitle' => $titleText,
3757 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
3758 'anchor' => $anchor,
3759 );
3760
3761 # give headline the correct <h#> tag
3762 if( $showEditLink && $sectionIndex !== false ) {
3763 if( $isTemplate ) {
3764 # Put a T flag in the section identifier, to indicate to extractSections()
3765 # that sections inside <includeonly> should be counted.
3766 $editlink = $sk->doEditSectionLink(Title::newFromText( $titleText ), "T-$sectionIndex");
3767 } else {
3768 $editlink = $sk->doEditSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3769 }
3770 } else {
3771 $editlink = '';
3772 }
3773 $head[$headlineCount] = $sk->makeHeadline( $level,
3774 $matches['attrib'][$headlineCount], $anchor, $headline,
3775 $editlink, $legacyAnchor );
3776
3777 $headlineCount++;
3778 }
3779
3780 $this->setOutputType( $oldType );
3781
3782 # Never ever show TOC if no headers
3783 if( $numVisible < 1 ) {
3784 $enoughToc = false;
3785 }
3786
3787 if( $enoughToc ) {
3788 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3789 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3790 }
3791 $toc = $sk->tocList( $toc );
3792 $this->mOutput->setTOCHTML( $toc );
3793 }
3794
3795 if ( $isMain ) {
3796 $this->mOutput->setSections( $tocraw );
3797 }
3798
3799 # split up and insert constructed headlines
3800
3801 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3802 $i = 0;
3803
3804 foreach( $blocks as $block ) {
3805 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3806 # This is the [edit] link that appears for the top block of text when
3807 # section editing is enabled
3808
3809 # Disabled because it broke block formatting
3810 # For example, a bullet point in the top line
3811 # $full .= $sk->editSectionLink(0);
3812 }
3813 $full .= $block;
3814 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3815 # Top anchor now in skin
3816 $full = $full.$toc;
3817 }
3818
3819 if( !empty( $head[$i] ) ) {
3820 $full .= $head[$i];
3821 }
3822 $i++;
3823 }
3824 if( $this->mForceTocPosition ) {
3825 return str_replace( '<!--MWTOC-->', $toc, $full );
3826 } else {
3827 return $full;
3828 }
3829 }
3830
3831 /**
3832 * Merge $tree2 into $tree1 by replacing the section with index
3833 * $section in $tree1 and its descendants with the sections in $tree2.
3834 * Note that in the returned section tree, only the 'index' and
3835 * 'byteoffset' fields are guaranteed to be correct.
3836 * @param $tree1 array Section tree from ParserOutput::getSectons()
3837 * @param $tree2 array Section tree
3838 * @param $section int Section index
3839 * @param $title Title Title both section trees come from
3840 * @param $len2 int Length of the original wikitext for $tree2
3841 * @return array Merged section tree
3842 */
3843 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3844 global $wgContLang;
3845 $newTree = array();
3846 $targetLevel = false;
3847 $merged = false;
3848 $lastLevel = 1;
3849 $nextIndex = 1;
3850 $numbering = array( 0 );
3851 $titletext = $title->getPrefixedDBkey();
3852 foreach ( $tree1 as $s ) {
3853 if ( $targetLevel !== false ) {
3854 if ( $s['level'] <= $targetLevel )
3855 // We've skipped enough
3856 $targetLevel = false;
3857 else
3858 continue;
3859 }
3860 if ( $s['index'] != $section ||
3861 $s['fromtitle'] != $titletext ) {
3862 self::incrementNumbering( $numbering,
3863 $s['toclevel'], $lastLevel );
3864
3865 // Rewrite index, byteoffset and number
3866 if ( $s['fromtitle'] == $titletext ) {
3867 $s['index'] = $nextIndex++;
3868 if ( $merged )
3869 $s['byteoffset'] += $len2;
3870 }
3871 $s['number'] = implode( '.', array_map(
3872 array( $wgContLang, 'formatnum' ),
3873 $numbering ) );
3874 $lastLevel = $s['toclevel'];
3875 $newTree[] = $s;
3876 } else {
3877 // We're at $section
3878 // Insert sections from $tree2 here
3879 foreach ( $tree2 as $s2 ) {
3880 // Rewrite the fields in $s2
3881 // before inserting it
3882 $s2['toclevel'] += $s['toclevel'] - 1;
3883 $s2['level'] += $s['level'] - 1;
3884 $s2['index'] = $nextIndex++;
3885 $s2['byteoffset'] += $s['byteoffset'];
3886
3887 self::incrementNumbering( $numbering,
3888 $s2['toclevel'], $lastLevel );
3889 $s2['number'] = implode( '.', array_map(
3890 array( $wgContLang, 'formatnum' ),
3891 $numbering ) );
3892 $lastLevel = $s2['toclevel'];
3893 $newTree[] = $s2;
3894 }
3895 // Skip all descendants of $section in $tree1
3896 $targetLevel = $s['level'];
3897 $merged = true;
3898 }
3899 }
3900 return $newTree;
3901 }
3902
3903 /**
3904 * Increment a section number. Helper function for mergeSectionTrees()
3905 * @param $number array Array representing a section number
3906 * @param $level int Current TOC level (depth)
3907 * @param $lastLevel int Level of previous TOC entry
3908 */
3909 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3910 if ( $level > $lastLevel )
3911 $number[$level - 1] = 1;
3912 else if ( $level < $lastLevel ) {
3913 foreach ( $number as $key => $unused )
3914 if ( $key >= $level )
3915 unset( $number[$key] );
3916 $number[$level - 1]++;
3917 } else
3918 $number[$level - 1]++;
3919 }
3920
3921 /**
3922 * Transform wiki markup when saving a page by doing \r\n -> \n
3923 * conversion, substitting signatures, {{subst:}} templates, etc.
3924 *
3925 * @param string $text the text to transform
3926 * @param Title &$title the Title object for the current article
3927 * @param User $user the User object describing the current user
3928 * @param ParserOptions $options parsing options
3929 * @param bool $clearState whether to clear the parser state first
3930 * @return string the altered wiki markup
3931 * @public
3932 */
3933 function preSaveTransform( $text, Title $title, $user, $options, $clearState = true ) {
3934 $this->mOptions = $options;
3935 $this->setTitle( $title );
3936 $this->setOutputType( self::OT_WIKI );
3937
3938 if ( $clearState ) {
3939 $this->clearState();
3940 }
3941
3942 $pairs = array(
3943 "\r\n" => "\n",
3944 );
3945 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3946 $text = $this->pstPass2( $text, $user );
3947 $text = $this->mStripState->unstripBoth( $text );
3948 return $text;
3949 }
3950
3951 /**
3952 * Pre-save transform helper function
3953 * @private
3954 */
3955 function pstPass2( $text, $user ) {
3956 global $wgContLang, $wgLocaltimezone;
3957
3958 /* Note: This is the timestamp saved as hardcoded wikitext to
3959 * the database, we use $wgContLang here in order to give
3960 * everyone the same signature and use the default one rather
3961 * than the one selected in each user's preferences.
3962 *
3963 * (see also bug 12815)
3964 */
3965 $ts = $this->mOptions->getTimestamp();
3966 if ( isset( $wgLocaltimezone ) ) {
3967 $tz = $wgLocaltimezone;
3968 } else {
3969 $tz = date_default_timezone_get();
3970 }
3971
3972 $unixts = wfTimestamp( TS_UNIX, $ts );
3973 $oldtz = date_default_timezone_get();
3974 date_default_timezone_set( $tz );
3975 $ts = date( 'YmdHis', $unixts );
3976 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
3977
3978 /* Allow translation of timezones trough wiki. date() can return
3979 * whatever crap the system uses, localised or not, so we cannot
3980 * ship premade translations.
3981 */
3982 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
3983 $value = wfMsgForContent( $key );
3984 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
3985
3986 date_default_timezone_set( $oldtz );
3987
3988 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
3989
3990 # Variable replacement
3991 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3992 $text = $this->replaceVariables( $text );
3993
3994 # Signatures
3995 $sigText = $this->getUserSig( $user );
3996 $text = strtr( $text, array(
3997 '~~~~~' => $d,
3998 '~~~~' => "$sigText $d",
3999 '~~~' => $sigText
4000 ) );
4001
4002 # Context links: [[|name]] and [[name (context)|]]
4003 #
4004 global $wgLegalTitleChars;
4005 $tc = "[$wgLegalTitleChars]";
4006 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4007
4008 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4009 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4010 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4011 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4012
4013 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4014 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4015 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4016 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4017
4018 $t = $this->mTitle->getText();
4019 $m = array();
4020 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4021 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4022 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4023 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4024 } else {
4025 # if there's no context, don't bother duplicating the title
4026 $text = preg_replace( $p2, '[[\\1]]', $text );
4027 }
4028
4029 # Trim trailing whitespace
4030 $text = rtrim( $text );
4031
4032 return $text;
4033 }
4034
4035 /**
4036 * Fetch the user's signature text, if any, and normalize to
4037 * validated, ready-to-insert wikitext.
4038 * If you have pre-fetched the nickname or the fancySig option, you can
4039 * specify them here to save a database query.
4040 *
4041 * @param User $user
4042 * @return string
4043 */
4044 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4045 global $wgMaxSigChars;
4046
4047 $username = $user->getName();
4048
4049 // If not given, retrieve from the user object.
4050 if ( $nickname === false )
4051 $nickname = $user->getOption( 'nickname' );
4052
4053 if ( is_null( $fancySig ) )
4054 $fancySig = $user->getBoolOption( 'fancysig' );
4055
4056 $nickname = $nickname == null ? $username : $nickname;
4057
4058 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4059 $nickname = $username;
4060 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4061 } elseif( $fancySig !== false ) {
4062 # Sig. might contain markup; validate this
4063 if( $this->validateSig( $nickname ) !== false ) {
4064 # Validated; clean up (if needed) and return it
4065 return $this->cleanSig( $nickname, true );
4066 } else {
4067 # Failed to validate; fall back to the default
4068 $nickname = $username;
4069 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
4070 }
4071 }
4072
4073 // Make sure nickname doesnt get a sig in a sig
4074 $nickname = $this->cleanSigInSig( $nickname );
4075
4076 # If we're still here, make it a link to the user page
4077 $userText = wfEscapeWikiText( $username );
4078 $nickText = wfEscapeWikiText( $nickname );
4079 if ( $user->isAnon() ) {
4080 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4081 } else {
4082 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4083 }
4084 }
4085
4086 /**
4087 * Check that the user's signature contains no bad XML
4088 *
4089 * @param string $text
4090 * @return mixed An expanded string, or false if invalid.
4091 */
4092 function validateSig( $text ) {
4093 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
4094 }
4095
4096 /**
4097 * Clean up signature text
4098 *
4099 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4100 * 2) Substitute all transclusions
4101 *
4102 * @param string $text
4103 * @param $parsing Whether we're cleaning (preferences save) or parsing
4104 * @return string Signature text
4105 */
4106 function cleanSig( $text, $parsing = false ) {
4107 if ( !$parsing ) {
4108 global $wgTitle;
4109 $this->clearState();
4110 $this->setTitle( $wgTitle );
4111 $this->mOptions = new ParserOptions;
4112 $this->setOutputType = self::OT_PREPROCESS;
4113 }
4114
4115 # Option to disable this feature
4116 if ( !$this->mOptions->getCleanSignatures() ) {
4117 return $text;
4118 }
4119
4120 # FIXME: regex doesn't respect extension tags or nowiki
4121 # => Move this logic to braceSubstitution()
4122 $substWord = MagicWord::get( 'subst' );
4123 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4124 $substText = '{{' . $substWord->getSynonym( 0 );
4125
4126 $text = preg_replace( $substRegex, $substText, $text );
4127 $text = $this->cleanSigInSig( $text );
4128 $dom = $this->preprocessToDom( $text );
4129 $frame = $this->getPreprocessor()->newFrame();
4130 $text = $frame->expand( $dom );
4131
4132 if ( !$parsing ) {
4133 $text = $this->mStripState->unstripBoth( $text );
4134 }
4135
4136 return $text;
4137 }
4138
4139 /**
4140 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4141 * @param string $text
4142 * @return string Signature text with /~{3,5}/ removed
4143 */
4144 function cleanSigInSig( $text ) {
4145 $text = preg_replace( '/~{3,5}/', '', $text );
4146 return $text;
4147 }
4148
4149 /**
4150 * Set up some variables which are usually set up in parse()
4151 * so that an external function can call some class members with confidence
4152 * @public
4153 */
4154 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4155 $this->setTitle( $title );
4156 $this->mOptions = $options;
4157 $this->setOutputType( $outputType );
4158 if ( $clearState ) {
4159 $this->clearState();
4160 }
4161 }
4162
4163 /**
4164 * Wrapper for preprocess()
4165 *
4166 * @param string $text the text to preprocess
4167 * @param ParserOptions $options options
4168 * @return string
4169 * @public
4170 */
4171 function transformMsg( $text, $options ) {
4172 global $wgTitle;
4173 static $executing = false;
4174
4175 # Guard against infinite recursion
4176 if ( $executing ) {
4177 return $text;
4178 }
4179 $executing = true;
4180
4181 wfProfileIn(__METHOD__);
4182 $text = $this->preprocess( $text, $wgTitle, $options );
4183
4184 $executing = false;
4185 wfProfileOut(__METHOD__);
4186 return $text;
4187 }
4188
4189 /**
4190 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4191 * The callback should have the following form:
4192 * function myParserHook( $text, $params, &$parser ) { ... }
4193 *
4194 * Transform and return $text. Use $parser for any required context, e.g. use
4195 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4196 *
4197 * @public
4198 *
4199 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4200 * @param mixed $callback The callback function (and object) to use for the tag
4201 *
4202 * @return The old value of the mTagHooks array associated with the hook
4203 */
4204 function setHook( $tag, $callback ) {
4205 $tag = strtolower( $tag );
4206 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4207 $this->mTagHooks[$tag] = $callback;
4208 if( !in_array( $tag, $this->mStripList ) ) {
4209 $this->mStripList[] = $tag;
4210 }
4211
4212 return $oldVal;
4213 }
4214
4215 function setTransparentTagHook( $tag, $callback ) {
4216 $tag = strtolower( $tag );
4217 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4218 $this->mTransparentTagHooks[$tag] = $callback;
4219
4220 return $oldVal;
4221 }
4222
4223 /**
4224 * Remove all tag hooks
4225 */
4226 function clearTagHooks() {
4227 $this->mTagHooks = array();
4228 $this->mStripList = $this->mDefaultStripList;
4229 }
4230
4231 /**
4232 * Create a function, e.g. {{sum:1|2|3}}
4233 * The callback function should have the form:
4234 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4235 *
4236 * Or with SFH_OBJECT_ARGS:
4237 * function myParserFunction( $parser, $frame, $args ) { ... }
4238 *
4239 * The callback may either return the text result of the function, or an array with the text
4240 * in element 0, and a number of flags in the other elements. The names of the flags are
4241 * specified in the keys. Valid flags are:
4242 * found The text returned is valid, stop processing the template. This
4243 * is on by default.
4244 * nowiki Wiki markup in the return value should be escaped
4245 * isHTML The returned text is HTML, armour it against wikitext transformation
4246 *
4247 * @public
4248 *
4249 * @param string $id The magic word ID
4250 * @param mixed $callback The callback function (and object) to use
4251 * @param integer $flags a combination of the following flags:
4252 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4253 *
4254 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4255 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4256 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4257 * the arguments, and to control the way they are expanded.
4258 *
4259 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4260 * arguments, for instance:
4261 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4262 *
4263 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4264 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4265 * working if/when this is changed.
4266 *
4267 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4268 * expansion.
4269 *
4270 * Please read the documentation in includes/parser/Preprocessor.php for more information
4271 * about the methods available in PPFrame and PPNode.
4272 *
4273 * @return The old callback function for this name, if any
4274 */
4275 function setFunctionHook( $id, $callback, $flags = 0 ) {
4276 global $wgContLang;
4277
4278 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4279 $this->mFunctionHooks[$id] = array( $callback, $flags );
4280
4281 # Add to function cache
4282 $mw = MagicWord::get( $id );
4283 if( !$mw )
4284 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4285
4286 $synonyms = $mw->getSynonyms();
4287 $sensitive = intval( $mw->isCaseSensitive() );
4288
4289 foreach ( $synonyms as $syn ) {
4290 # Case
4291 if ( !$sensitive ) {
4292 $syn = $wgContLang->lc( $syn );
4293 }
4294 # Add leading hash
4295 if ( !( $flags & SFH_NO_HASH ) ) {
4296 $syn = '#' . $syn;
4297 }
4298 # Remove trailing colon
4299 if ( substr( $syn, -1, 1 ) === ':' ) {
4300 $syn = substr( $syn, 0, -1 );
4301 }
4302 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4303 }
4304 return $oldVal;
4305 }
4306
4307 /**
4308 * Get all registered function hook identifiers
4309 *
4310 * @return array
4311 */
4312 function getFunctionHooks() {
4313 return array_keys( $this->mFunctionHooks );
4314 }
4315
4316 /**
4317 * Create a tag function, e.g. <test>some stuff</test>.
4318 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4319 * Unlike parser functions, their content is not preprocessed.
4320 */
4321 function setFunctionTagHook( $tag, $callback, $flags ) {
4322 $tag = strtolower( $tag );
4323 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4324 $this->mFunctionTagHooks[$tag] : null;
4325 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4326
4327 if( !in_array( $tag, $this->mStripList ) ) {
4328 $this->mStripList[] = $tag;
4329 }
4330
4331 return $old;
4332 }
4333
4334 /**
4335 * FIXME: update documentation. makeLinkObj() is deprecated.
4336 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4337 * Placeholders created in Skin::makeLinkObj()
4338 * Returns an array of link CSS classes, indexed by PDBK.
4339 */
4340 function replaceLinkHolders( &$text, $options = 0 ) {
4341 return $this->mLinkHolders->replace( $text );
4342 }
4343
4344 /**
4345 * Replace <!--LINK--> link placeholders with plain text of links
4346 * (not HTML-formatted).
4347 * @param string $text
4348 * @return string
4349 */
4350 function replaceLinkHoldersText( $text ) {
4351 return $this->mLinkHolders->replaceText( $text );
4352 }
4353
4354 /**
4355 * Tag hook handler for 'pre'.
4356 */
4357 function renderPreTag( $text, $attribs ) {
4358 // Backwards-compatibility hack
4359 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4360
4361 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4362 return Xml::openElement( 'pre', $attribs ) .
4363 Xml::escapeTagsOnly( $content ) .
4364 '</pre>';
4365 }
4366
4367 /**
4368 * Tag hook handler for 'a'. Renders a HTML &lt;a&gt; tag, allowing most attributes, filtering href against
4369 * allowed protocols and spam blacklist.
4370 **/
4371 function renderHyperlink( $text, $params, $frame = false ) {
4372 foreach ( $params as $name => $value ) {
4373 $params[ $name ] = $this->replaceVariables( $value, $frame );
4374 }
4375
4376 $whitelist = Sanitizer::attributeWhitelist( 'a' );
4377 $params = Sanitizer::validateAttributes( $params, $whitelist );
4378
4379 $content = $this->recursiveTagParse( trim( $text ), $frame );
4380
4381 if ( isset( $params[ 'href' ] ) ) {
4382 $href = $params[ 'href' ];
4383 $this->mOutput->addExternalLink( $href );
4384 unset( $params[ 'href' ] );
4385 } else {
4386 # Non-link <a> tag
4387 return Xml::openElement( 'a', $params ) . $content . Xml::closeElement( 'a' );
4388 }
4389
4390 $sk = $this->mOptions->getSkin();
4391 $html = $sk->makeExternalLink( $href, $content, false, '', $params );
4392
4393 return $html;
4394 }
4395
4396 /**
4397 * Renders an image gallery from a text with one line per image.
4398 * text labels may be given by using |-style alternative text. E.g.
4399 * Image:one.jpg|The number "1"
4400 * Image:tree.jpg|A tree
4401 * given as text will return the HTML of a gallery with two images,
4402 * labeled 'The number "1"' and
4403 * 'A tree'.
4404 */
4405 function renderImageGallery( $text, $params ) {
4406 $ig = new ImageGallery();
4407 $ig->setContextTitle( $this->mTitle );
4408 $ig->setShowBytes( false );
4409 $ig->setShowFilename( false );
4410 $ig->setParser( $this );
4411 $ig->setHideBadImages();
4412 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4413 $ig->useSkin( $this->mOptions->getSkin() );
4414 $ig->mRevisionId = $this->mRevisionId;
4415
4416 if( isset( $params['caption'] ) ) {
4417 $caption = $params['caption'];
4418 $caption = htmlspecialchars( $caption );
4419 $caption = $this->replaceInternalLinks( $caption );
4420 $ig->setCaptionHtml( $caption );
4421 }
4422 if( isset( $params['perrow'] ) ) {
4423 $ig->setPerRow( $params['perrow'] );
4424 }
4425 if( isset( $params['widths'] ) ) {
4426 $ig->setWidths( $params['widths'] );
4427 }
4428 if( isset( $params['heights'] ) ) {
4429 $ig->setHeights( $params['heights'] );
4430 }
4431
4432 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4433
4434 $lines = StringUtils::explode( "\n", $text );
4435 foreach ( $lines as $line ) {
4436 # match lines like these:
4437 # Image:someimage.jpg|This is some image
4438 $matches = array();
4439 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4440 # Skip empty lines
4441 if ( count( $matches ) == 0 ) {
4442 continue;
4443 }
4444
4445 if ( strpos( $matches[0], '%' ) !== false )
4446 $matches[1] = urldecode( $matches[1] );
4447 $tp = Title::newFromText( $matches[1]/*, NS_FILE*/ );
4448 $nt =& $tp;
4449 if( is_null( $nt ) ) {
4450 # Bogus title. Ignore these so we don't bomb out later.
4451 continue;
4452 }
4453 if ( isset( $matches[3] ) ) {
4454 $label = $matches[3];
4455 } else {
4456 $label = '';
4457 }
4458
4459 $html = $this->recursiveTagParse( trim( $label ) );
4460
4461 $ig->add( $nt, $html );
4462
4463 # Only add real images (bug #5586)
4464 if ( $nt->getNamespace() == NS_FILE ) {
4465 $this->mOutput->addImage( $nt->getDBkey() );
4466 }
4467 }
4468 return $ig->toHTML();
4469 }
4470
4471 function getImageParams( $handler ) {
4472 if ( $handler ) {
4473 $handlerClass = get_class( $handler );
4474 } else {
4475 $handlerClass = '';
4476 }
4477 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4478 // Initialise static lists
4479 static $internalParamNames = array(
4480 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4481 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4482 'bottom', 'text-bottom' ),
4483 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4484 'upright', 'border', 'link', 'alt' ),
4485 );
4486 static $internalParamMap;
4487 if ( !$internalParamMap ) {
4488 $internalParamMap = array();
4489 foreach ( $internalParamNames as $type => $names ) {
4490 foreach ( $names as $name ) {
4491 $magicName = str_replace( '-', '_', "img_$name" );
4492 $internalParamMap[$magicName] = array( $type, $name );
4493 }
4494 }
4495 }
4496
4497 // Add handler params
4498 $paramMap = $internalParamMap;
4499 if ( $handler ) {
4500 $handlerParamMap = $handler->getParamMap();
4501 foreach ( $handlerParamMap as $magic => $paramName ) {
4502 $paramMap[$magic] = array( 'handler', $paramName );
4503 }
4504 }
4505 $this->mImageParams[$handlerClass] = $paramMap;
4506 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4507 }
4508 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4509 }
4510
4511 /**
4512 * Parse image options text and use it to make an image
4513 * @param Title $title
4514 * @param string $options
4515 * @param LinkHolderArray $holders
4516 */
4517 function makeImage( $title, $options, $holders = false ) {
4518 # Check if the options text is of the form "options|alt text"
4519 # Options are:
4520 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4521 # * left no resizing, just left align. label is used for alt= only
4522 # * right same, but right aligned
4523 # * none same, but not aligned
4524 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4525 # * center center the image
4526 # * frame Keep original image size, no magnify-button.
4527 # * framed Same as "frame"
4528 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4529 # * upright reduce width for upright images, rounded to full __0 px
4530 # * border draw a 1px border around the image
4531 # * alt Text for HTML alt attribute (defaults to empty)
4532 # * link Set the target of the image link. Can be external, interwiki, or local
4533 # vertical-align values (no % or length right now):
4534 # * baseline
4535 # * sub
4536 # * super
4537 # * top
4538 # * text-top
4539 # * middle
4540 # * bottom
4541 # * text-bottom
4542
4543 $parts = StringUtils::explode( "|", $options );
4544 $sk = $this->mOptions->getSkin();
4545
4546 # Give extensions a chance to select the file revision for us
4547 $skip = $time = $descQuery = false;
4548 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4549
4550 if ( $skip ) {
4551 return $sk->link( $title );
4552 }
4553
4554 # Get the file
4555 $imagename = $title->getDBkey();
4556 $file = wfFindFile( $title, array( 'time' => $time ) );
4557 # Get parameter map
4558 $handler = $file ? $file->getHandler() : false;
4559
4560 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4561
4562 # Process the input parameters
4563 $caption = '';
4564 $params = array( 'frame' => array(), 'handler' => array(),
4565 'horizAlign' => array(), 'vertAlign' => array() );
4566 foreach( $parts as $part ) {
4567 $part = trim( $part );
4568 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4569 $validated = false;
4570 if( isset( $paramMap[$magicName] ) ) {
4571 list( $type, $paramName ) = $paramMap[$magicName];
4572
4573 // Special case; width and height come in one variable together
4574 if( $type === 'handler' && $paramName === 'width' ) {
4575 $m = array();
4576 # (bug 13500) In both cases (width/height and width only),
4577 # permit trailing "px" for backward compatibility.
4578 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4579 $width = intval( $m[1] );
4580 $height = intval( $m[2] );
4581 if ( $handler->validateParam( 'width', $width ) ) {
4582 $params[$type]['width'] = $width;
4583 $validated = true;
4584 }
4585 if ( $handler->validateParam( 'height', $height ) ) {
4586 $params[$type]['height'] = $height;
4587 $validated = true;
4588 }
4589 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4590 $width = intval( $value );
4591 if ( $handler->validateParam( 'width', $width ) ) {
4592 $params[$type]['width'] = $width;
4593 $validated = true;
4594 }
4595 } // else no validation -- bug 13436
4596 } else {
4597 if ( $type === 'handler' ) {
4598 # Validate handler parameter
4599 $validated = $handler->validateParam( $paramName, $value );
4600 } else {
4601 # Validate internal parameters
4602 switch( $paramName ) {
4603 case 'manualthumb':
4604 case 'alt':
4605 // @todo Fixme: possibly check validity here for
4606 // manualthumb? downstream behavior seems odd with
4607 // missing manual thumbs.
4608 $validated = true;
4609 $value = $this->stripAltText( $value, $holders );
4610 break;
4611 case 'link':
4612 $chars = self::EXT_LINK_URL_CLASS;
4613 $prots = $this->mUrlProtocols;
4614 if ( $value === '' ) {
4615 $paramName = 'no-link';
4616 $value = true;
4617 $validated = true;
4618 } elseif ( preg_match( "/^$prots/", $value ) ) {
4619 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4620 $paramName = 'link-url';
4621 $this->mOutput->addExternalLink( $value );
4622 $validated = true;
4623 }
4624 } else {
4625 $linkTitle = Title::newFromText( $value );
4626 if ( $linkTitle ) {
4627 $paramName = 'link-title';
4628 $value = $linkTitle;
4629 $this->mOutput->addLink( $linkTitle );
4630 $validated = true;
4631 }
4632 }
4633 break;
4634 default:
4635 // Most other things appear to be empty or numeric...
4636 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4637 }
4638 }
4639
4640 if ( $validated ) {
4641 $params[$type][$paramName] = $value;
4642 }
4643 }
4644 }
4645 if ( !$validated ) {
4646 $caption = $part;
4647 }
4648 }
4649
4650 # Process alignment parameters
4651 if ( $params['horizAlign'] ) {
4652 $params['frame']['align'] = key( $params['horizAlign'] );
4653 }
4654 if ( $params['vertAlign'] ) {
4655 $params['frame']['valign'] = key( $params['vertAlign'] );
4656 }
4657
4658 $params['frame']['caption'] = $caption;
4659
4660 # Will the image be presented in a frame, with the caption below?
4661 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4662 isset( $params['frame']['framed'] ) ||
4663 isset( $params['frame']['thumbnail'] ) ||
4664 isset( $params['frame']['manualthumb'] );
4665
4666 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4667 # came to also set the caption, ordinary text after the image -- which
4668 # makes no sense, because that just repeats the text multiple times in
4669 # screen readers. It *also* came to set the title attribute.
4670 #
4671 # Now that we have an alt attribute, we should not set the alt text to
4672 # equal the caption: that's worse than useless, it just repeats the
4673 # text. This is the framed/thumbnail case. If there's no caption, we
4674 # use the unnamed parameter for alt text as well, just for the time be-
4675 # ing, if the unnamed param is set and the alt param is not.
4676 #
4677 # For the future, we need to figure out if we want to tweak this more,
4678 # e.g., introducing a title= parameter for the title; ignoring the un-
4679 # named parameter entirely for images without a caption; adding an ex-
4680 # plicit caption= parameter and preserving the old magic unnamed para-
4681 # meter for BC; ...
4682 if ( $imageIsFramed ) { # Framed image
4683 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4684 # No caption or alt text, add the filename as the alt text so
4685 # that screen readers at least get some description of the image
4686 $params['frame']['alt'] = $title->getText();
4687 }
4688 # Do not set $params['frame']['title'] because tooltips don't make sense
4689 # for framed images
4690 } else { # Inline image
4691 if ( !isset( $params['frame']['alt'] ) ) {
4692 # No alt text, use the "caption" for the alt text
4693 if ( $caption !== '') {
4694 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4695 } else {
4696 # No caption, fall back to using the filename for the
4697 # alt text
4698 $params['frame']['alt'] = $title->getText();
4699 }
4700 }
4701 # Use the "caption" for the tooltip text
4702 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4703 }
4704
4705 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4706
4707 # Linker does the rest
4708 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4709
4710 # Give the handler a chance to modify the parser object
4711 if ( $handler ) {
4712 $handler->parserTransformHook( $this, $file );
4713 }
4714
4715 return $ret;
4716 }
4717
4718 protected function stripAltText( $caption, $holders ) {
4719 # Strip bad stuff out of the title (tooltip). We can't just use
4720 # replaceLinkHoldersText() here, because if this function is called
4721 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4722 if ( $holders ) {
4723 $tooltip = $holders->replaceText( $caption );
4724 } else {
4725 $tooltip = $this->replaceLinkHoldersText( $caption );
4726 }
4727
4728 # make sure there are no placeholders in thumbnail attributes
4729 # that are later expanded to html- so expand them now and
4730 # remove the tags
4731 $tooltip = $this->mStripState->unstripBoth( $tooltip );
4732 $tooltip = Sanitizer::stripAllTags( $tooltip );
4733
4734 return $tooltip;
4735 }
4736
4737 /**
4738 * Set a flag in the output object indicating that the content is dynamic and
4739 * shouldn't be cached.
4740 */
4741 function disableCache() {
4742 wfDebug( "Parser output marked as uncacheable.\n" );
4743 $this->mOutput->mCacheTime = -1;
4744 }
4745
4746 /**#@+
4747 * Callback from the Sanitizer for expanding items found in HTML attribute
4748 * values, so they can be safely tested and escaped.
4749 * @param string $text
4750 * @param PPFrame $frame
4751 * @return string
4752 * @private
4753 */
4754 function attributeStripCallback( &$text, $frame = false ) {
4755 $text = $this->replaceVariables( $text, $frame );
4756 $text = $this->mStripState->unstripBoth( $text );
4757 return $text;
4758 }
4759
4760 /**#@-*/
4761
4762 /**#@+
4763 * Accessor/mutator
4764 */
4765 function Title( $x = null ) { return wfSetVar( $this->mTitle, $x ); }
4766 function Options( $x = null ) { return wfSetVar( $this->mOptions, $x ); }
4767 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType, $x ); }
4768 /**#@-*/
4769
4770 /**#@+
4771 * Accessor
4772 */
4773 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4774 /**#@-*/
4775
4776
4777 /**
4778 * Break wikitext input into sections, and either pull or replace
4779 * some particular section's text.
4780 *
4781 * External callers should use the getSection and replaceSection methods.
4782 *
4783 * @param string $text Page wikitext
4784 * @param string $section A section identifier string of the form:
4785 * <flag1> - <flag2> - ... - <section number>
4786 *
4787 * Currently the only recognised flag is "T", which means the target section number
4788 * was derived during a template inclusion parse, in other words this is a template
4789 * section edit link. If no flags are given, it was an ordinary section edit link.
4790 * This flag is required to avoid a section numbering mismatch when a section is
4791 * enclosed by <includeonly> (bug 6563).
4792 *
4793 * The section number 0 pulls the text before the first heading; other numbers will
4794 * pull the given section along with its lower-level subsections. If the section is
4795 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4796 *
4797 * @param string $mode One of "get" or "replace"
4798 * @param string $newText Replacement text for section data.
4799 * @return string for "get", the extracted section text.
4800 * for "replace", the whole page with the section replaced.
4801 */
4802 private function extractSections( $text, $section, $mode, $newText='' ) {
4803 global $wgTitle;
4804 $this->clearState();
4805 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4806 $this->mOptions = new ParserOptions;
4807 $this->setOutputType( self::OT_WIKI );
4808 $outText = '';
4809 $frame = $this->getPreprocessor()->newFrame();
4810
4811 // Process section extraction flags
4812 $flags = 0;
4813 $sectionParts = explode( '-', $section );
4814 $sectionIndex = array_pop( $sectionParts );
4815 foreach ( $sectionParts as $part ) {
4816 if ( $part === 'T' ) {
4817 $flags |= self::PTD_FOR_INCLUSION;
4818 }
4819 }
4820 // Preprocess the text
4821 $root = $this->preprocessToDom( $text, $flags );
4822
4823 // <h> nodes indicate section breaks
4824 // They can only occur at the top level, so we can find them by iterating the root's children
4825 $node = $root->getFirstChild();
4826
4827 // Find the target section
4828 if ( $sectionIndex == 0 ) {
4829 // Section zero doesn't nest, level=big
4830 $targetLevel = 1000;
4831 } else {
4832 while ( $node ) {
4833 if ( $node->getName() === 'h' ) {
4834 $bits = $node->splitHeading();
4835 if ( $bits['i'] == $sectionIndex ) {
4836 $targetLevel = $bits['level'];
4837 break;
4838 }
4839 }
4840 if ( $mode === 'replace' ) {
4841 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4842 }
4843 $node = $node->getNextSibling();
4844 }
4845 }
4846
4847 if ( !$node ) {
4848 // Not found
4849 if ( $mode === 'get' ) {
4850 return $newText;
4851 } else {
4852 return $text;
4853 }
4854 }
4855
4856 // Find the end of the section, including nested sections
4857 do {
4858 if ( $node->getName() === 'h' ) {
4859 $bits = $node->splitHeading();
4860 $curLevel = $bits['level'];
4861 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4862 break;
4863 }
4864 }
4865 if ( $mode === 'get' ) {
4866 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4867 }
4868 $node = $node->getNextSibling();
4869 } while ( $node );
4870
4871 // Write out the remainder (in replace mode only)
4872 if ( $mode === 'replace' ) {
4873 // Output the replacement text
4874 // Add two newlines on -- trailing whitespace in $newText is conventionally
4875 // stripped by the editor, so we need both newlines to restore the paragraph gap
4876 // Only add trailing whitespace if there is newText
4877 if($newText != "") {
4878 $outText .= $newText . "\n\n";
4879 }
4880
4881 while ( $node ) {
4882 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4883 $node = $node->getNextSibling();
4884 }
4885 }
4886
4887 if ( is_string( $outText ) ) {
4888 // Re-insert stripped tags
4889 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4890 }
4891
4892 return $outText;
4893 }
4894
4895 /**
4896 * This function returns the text of a section, specified by a number ($section).
4897 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4898 * the first section before any such heading (section 0).
4899 *
4900 * If a section contains subsections, these are also returned.
4901 *
4902 * @param string $text text to look in
4903 * @param string $section section identifier
4904 * @param string $deftext default to return if section is not found
4905 * @return string text of the requested section
4906 */
4907 public function getSection( $text, $section, $deftext='' ) {
4908 return $this->extractSections( $text, $section, "get", $deftext );
4909 }
4910
4911 public function replaceSection( $oldtext, $section, $text ) {
4912 return $this->extractSections( $oldtext, $section, "replace", $text );
4913 }
4914
4915 /**
4916 * Get the timestamp associated with the current revision, adjusted for
4917 * the default server-local timestamp
4918 */
4919 function getRevisionTimestamp() {
4920 if ( is_null( $this->mRevisionTimestamp ) ) {
4921 wfProfileIn( __METHOD__ );
4922 global $wgContLang;
4923 $dbr = wfGetDB( DB_SLAVE );
4924 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4925 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4926
4927 // Normalize timestamp to internal MW format for timezone processing.
4928 // This has the added side-effect of replacing a null value with
4929 // the current time, which gives us more sensible behavior for
4930 // previews.
4931 $timestamp = wfTimestamp( TS_MW, $timestamp );
4932
4933 // The cryptic '' timezone parameter tells to use the site-default
4934 // timezone offset instead of the user settings.
4935 //
4936 // Since this value will be saved into the parser cache, served
4937 // to other users, and potentially even used inside links and such,
4938 // it needs to be consistent for all visitors.
4939 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4940
4941 wfProfileOut( __METHOD__ );
4942 }
4943 return $this->mRevisionTimestamp;
4944 }
4945
4946 /**
4947 * Get the name of the user that edited the last revision
4948 */
4949 function getRevisionUser() {
4950 // if this template is subst: the revision id will be blank,
4951 // so just use the current user's name
4952 if( $this->mRevisionId ) {
4953 $revision = Revision::newFromId( $this->mRevisionId );
4954 $revuser = $revision->getUserText();
4955 } else {
4956 global $wgUser;
4957 $revuser = $wgUser->getName();
4958 }
4959 return $revuser;
4960 }
4961
4962 /**
4963 * Mutator for $mDefaultSort
4964 *
4965 * @param $sort New value
4966 */
4967 public function setDefaultSort( $sort ) {
4968 $this->mDefaultSort = $sort;
4969 }
4970
4971 /**
4972 * Accessor for $mDefaultSort
4973 * Will use the title/prefixed title if none is set
4974 *
4975 * @return string
4976 */
4977 public function getDefaultSort() {
4978 global $wgCategoryPrefixedDefaultSortkey;
4979 if( $this->mDefaultSort !== false ) {
4980 return $this->mDefaultSort;
4981 } elseif ($this->mTitle->getNamespace() == NS_CATEGORY ||
4982 !$wgCategoryPrefixedDefaultSortkey) {
4983 return $this->mTitle->getText();
4984 } else {
4985 return $this->mTitle->getPrefixedText();
4986 }
4987 }
4988
4989 /**
4990 * Accessor for $mDefaultSort
4991 * Unlike getDefaultSort(), will return false if none is set
4992 *
4993 * @return string or false
4994 */
4995 public function getCustomDefaultSort() {
4996 return $this->mDefaultSort;
4997 }
4998
4999 /**
5000 * Try to guess the section anchor name based on a wikitext fragment
5001 * presumably extracted from a heading, for example "Header" from
5002 * "== Header ==".
5003 */
5004 public function guessSectionNameFromWikiText( $text ) {
5005 # Strip out wikitext links(they break the anchor)
5006 $text = $this->stripSectionName( $text );
5007 $headline = Sanitizer::decodeCharReferences( $text );
5008 # strip out HTML
5009 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
5010 $headline = trim( $headline );
5011 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5012 $replacearray = array(
5013 '%3A' => ':',
5014 '%' => '.'
5015 );
5016 return str_replace(
5017 array_keys( $replacearray ),
5018 array_values( $replacearray ),
5019 $sectionanchor );
5020 }
5021
5022 /**
5023 * Strips a text string of wikitext for use in a section anchor
5024 *
5025 * Accepts a text string and then removes all wikitext from the
5026 * string and leaves only the resultant text (i.e. the result of
5027 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5028 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5029 * to create valid section anchors by mimicing the output of the
5030 * parser when headings are parsed.
5031 *
5032 * @param $text string Text string to be stripped of wikitext
5033 * for use in a Section anchor
5034 * @return Filtered text string
5035 */
5036 public function stripSectionName( $text ) {
5037 # Strip internal link markup
5038 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5039 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5040
5041 # Strip external link markup (FIXME: Not Tolerant to blank link text
5042 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5043 # on how many empty links there are on the page - need to figure that out.
5044 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5045
5046 # Parse wikitext quotes (italics & bold)
5047 $text = $this->doQuotes($text);
5048
5049 # Strip HTML tags
5050 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5051 return $text;
5052 }
5053
5054 function srvus( $text ) {
5055 return $this->testSrvus( $text, $this->mOutputType );
5056 }
5057
5058 /**
5059 * strip/replaceVariables/unstrip for preprocessor regression testing
5060 */
5061 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
5062 $this->clearState();
5063 if ( ! ( $title instanceof Title ) ) {
5064 $title = Title::newFromText( $title );
5065 }
5066 $this->mTitle = $title;
5067 $this->mOptions = $options;
5068 $this->setOutputType( $outputType );
5069 $text = $this->replaceVariables( $text );
5070 $text = $this->mStripState->unstripBoth( $text );
5071 $text = Sanitizer::removeHTMLtags( $text );
5072 return $text;
5073 }
5074
5075 function testPst( $text, $title, $options ) {
5076 global $wgUser;
5077 if ( ! ( $title instanceof Title ) ) {
5078 $title = Title::newFromText( $title );
5079 }
5080 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5081 }
5082
5083 function testPreprocess( $text, $title, $options ) {
5084 if ( ! ( $title instanceof Title ) ) {
5085 $title = Title::newFromText( $title );
5086 }
5087 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5088 }
5089
5090 function markerSkipCallback( $s, $callback ) {
5091 $i = 0;
5092 $out = '';
5093 while ( $i < strlen( $s ) ) {
5094 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5095 if ( $markerStart === false ) {
5096 $out .= call_user_func( $callback, substr( $s, $i ) );
5097 break;
5098 } else {
5099 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5100 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5101 if ( $markerEnd === false ) {
5102 $out .= substr( $s, $markerStart );
5103 break;
5104 } else {
5105 $markerEnd += strlen( self::MARKER_SUFFIX );
5106 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5107 $i = $markerEnd;
5108 }
5109 }
5110 }
5111 return $out;
5112 }
5113
5114 function serialiseHalfParsedText( $text ) {
5115 $data = array();
5116 $data['text'] = $text;
5117
5118 // First, find all strip markers, and store their
5119 // data in an array.
5120 $stripState = new StripState;
5121 $pos = 0;
5122 while( ( $start_pos = strpos( $text, $this->mUniqPrefix, $pos ) ) && ( $end_pos = strpos( $text, self::MARKER_SUFFIX, $pos ) ) ) {
5123 $end_pos += strlen( self::MARKER_SUFFIX );
5124 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5125
5126 if ( !empty( $this->mStripState->general->data[$marker] ) ) {
5127 $replaceArray = $stripState->general;
5128 $stripText = $this->mStripState->general->data[$marker];
5129 } elseif ( !empty( $this->mStripState->nowiki->data[$marker] ) ) {
5130 $replaceArray = $stripState->nowiki;
5131 $stripText = $this->mStripState->nowiki->data[$marker];
5132 } else {
5133 throw new MWException( "Hanging strip marker: '$marker'." );
5134 }
5135
5136 $replaceArray->setPair( $marker, $stripText );
5137 $pos = $end_pos;
5138 }
5139 $data['stripstate'] = $stripState;
5140
5141 // Now, find all of our links, and store THEIR
5142 // data in an array! :)
5143 $links = array( 'internal' => array(), 'interwiki' => array() );
5144 $pos = 0;
5145
5146 // Internal links
5147 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5148 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos + strlen( '<!--LINK ' ) ), 2 );
5149
5150 $ns = trim($ns);
5151 if (empty( $links['internal'][$ns] )) {
5152 $links['internal'][$ns] = array();
5153 }
5154
5155 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5156 $links['internal'][$ns][] = $this->mLinkHolders->internals[$ns][$key];
5157 $pos = $start_pos + strlen( "<!--LINK $ns:$key-->" );
5158 }
5159
5160 $pos = 0;
5161
5162 // Interwiki links
5163 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5164 $data = substr( $text, $start_pos );
5165 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5166 $links['interwiki'][] = $this->mLinkHolders->interwiki[$key];
5167 $pos = $start_pos + strlen( "<!--IWLINK $key-->" );
5168 }
5169
5170 $data['linkholder'] = $links;
5171
5172 return $data;
5173 }
5174
5175 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5176 if (!$intPrefix)
5177 $intPrefix = $this->getRandomString();
5178
5179 // First, extract the strip state.
5180 $stripState = $data['stripstate'];
5181 $this->mStripState->general->merge( $stripState->general );
5182 $this->mStripState->nowiki->merge( $stripState->nowiki );
5183
5184 // Now, extract the text, and renumber links
5185 $text = $data['text'];
5186 $links = $data['linkholder'];
5187
5188 // Internal...
5189 foreach( $links['internal'] as $ns => $nsLinks ) {
5190 foreach( $nsLinks as $key => $entry ) {
5191 $newKey = $intPrefix . '-' . $key;
5192 $this->mLinkHolders->internals[$ns][$newKey] = $entry;
5193
5194 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5195 }
5196 }
5197
5198 // Interwiki...
5199 foreach( $links['interwiki'] as $key => $entry ) {
5200 $newKey = "$intPrefix-$key";
5201 $this->mLinkHolders->interwikis[$newKey] = $entry;
5202
5203 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5204 }
5205
5206 // Should be good to go.
5207 return $text;
5208 }
5209 }
5210
5211 /**
5212 * @todo document, briefly.
5213 * @ingroup Parser
5214 */
5215 class StripState {
5216 var $general, $nowiki;
5217
5218 function __construct() {
5219 $this->general = new ReplacementArray;
5220 $this->nowiki = new ReplacementArray;
5221 }
5222
5223 function unstripGeneral( $text ) {
5224 wfProfileIn( __METHOD__ );
5225 do {
5226 $oldText = $text;
5227 $text = $this->general->replace( $text );
5228 } while ( $text !== $oldText );
5229 wfProfileOut( __METHOD__ );
5230 return $text;
5231 }
5232
5233 function unstripNoWiki( $text ) {
5234 wfProfileIn( __METHOD__ );
5235 do {
5236 $oldText = $text;
5237 $text = $this->nowiki->replace( $text );
5238 } while ( $text !== $oldText );
5239 wfProfileOut( __METHOD__ );
5240 return $text;
5241 }
5242
5243 function unstripBoth( $text ) {
5244 wfProfileIn( __METHOD__ );
5245 do {
5246 $oldText = $text;
5247 $text = $this->general->replace( $text );
5248 $text = $this->nowiki->replace( $text );
5249 } while ( $text !== $oldText );
5250 wfProfileOut( __METHOD__ );
5251 return $text;
5252 }
5253 }
5254
5255 /**
5256 * @todo document, briefly.
5257 * @ingroup Parser
5258 */
5259 class OnlyIncludeReplacer {
5260 var $output = '';
5261
5262 function replace( $matches ) {
5263 if ( substr( $matches[1], -1 ) === "\n" ) {
5264 $this->output .= substr( $matches[1], 0, -1 );
5265 } else {
5266 $this->output .= $matches[1];
5267 }
5268 }
5269 }