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