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