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