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