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