Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / parser / Parser.php
blob2066580f6c2824ec197351951345067395db9531
1 <?php
2 /**
3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Parser
24 /**
25 * @defgroup Parser Parser
28 /**
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
36 * - Parser::parse()
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
51 * Globals used:
52 * object: $wgContLang
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
56 * @par Settings:
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
62 * $wgInterwikiMagic
63 * $wgMaxArticleSize
65 * @ingroup Parser
67 class Parser {
68 /**
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION = '1.6.4';
75 /**
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION = 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH = 1;
84 const SFH_OBJECT_ARGS = 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT = 0;
96 const COLON_STATE_TAG = 1;
97 const COLON_STATE_TAGSTART = 2;
98 const COLON_STATE_CLOSETAG = 3;
99 const COLON_STATE_TAGSLASH = 4;
100 const COLON_STATE_COMMENT = 5;
101 const COLON_STATE_COMMENTDASH = 6;
102 const COLON_STATE_COMMENTDASHDASH = 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION = 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML = 1; # like parse()
110 const OT_WIKI = 2; # like preSaveTransform()
111 const OT_PREPROCESS = 3; # like preprocess()
112 const OT_MSG = 3;
113 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX = "-QINU\x7f";
118 # Markers used for wrapping the table of contents
119 const TOC_START = '<mw:toc>';
120 const TOC_END = '</mw:toc>';
122 # Persistent
124 /** @var array */
125 public $mTagHooks = array();
127 /** @var array */
128 public $mTransparentTagHooks = array();
130 /** @var array */
131 public $mFunctionHooks = array();
133 /** @var array */
134 protected $mFunctionSynonyms = array( 0 => array(), 1 => array() );
136 /** @var array */
137 protected $mFunctionTagHooks = array();
139 /** @var array */
140 protected $mStripList = array();
143 * @var array
144 * @todo Unused?
146 private $mDefaultStripList = array();
148 /** @var array */
149 protected $mVarCache = array();
151 /** @var array */
152 protected $mImageParams = array();
154 /** @var array */
155 protected $mImageParamsMagicArray = array();
157 /** @var int */
158 public $mMarkerIndex = 0;
160 /** @var bool */
161 protected $mFirstCall = true;
163 # Initialised by initialiseVariables()
165 /** @var MagicWordArray */
166 public $mVariables;
168 /** @var MagicWordArray */
169 protected $mSubstWords;
171 # Initialised in constructor
173 /** @var array */
174 protected $mConf;
176 /** @var Parser */
177 public $mPreprocessor;
179 /** @var string */
180 protected $mExtLinkBracketedRegex;
182 /** @var string */
183 protected $mUrlProtocols;
185 # Cleared with clearState():
187 /** @var ParserOutput */
188 public $mOutput;
190 /** @var int */
191 protected $mAutonumber;
193 /** @var bool */
194 protected $mDTopen;
196 /** @var StripState */
197 public $mStripState;
200 * @var array
201 * @todo Unused?
203 private $mIncludeCount;
206 * @var bool
207 * @todo Unused?
209 private $mArgStack;
211 /** @var string */
212 protected $mLastSection;
214 /** @var bool */
215 protected $mInPre;
217 /** @var LinkHolderArray */
218 protected $mLinkHolders;
220 /** @var int */
221 protected $mLinkID;
223 /** @var array */
224 protected $mIncludeSizes;
226 /** @var int */
227 public $mPPNodeCount;
229 /** @var int */
230 public $mGeneratedPPNodeCount;
232 /** @var int */
233 public $mHighestExpansionDepth;
235 /** @var bool|string */
236 protected $mDefaultSort;
238 /** @var array Empty-frame expansion cache */
239 protected $mTplExpandCache;
241 /** @var array */
242 protected $mTplRedirCache;
244 /** @var array */
245 protected $mTplDomCache;
247 /** @var array */
248 public $mHeadings;
250 /** @var array */
251 protected $mDoubleUnderscores;
253 /** @var int Number of expensive parser function calls */
254 protected $mExpensiveFunctionCount;
256 /** @var bool */
257 protected $mShowToc;
259 /** @var bool */
260 protected $mForceTocPosition;
262 /** @var User User object; only used when doing pre-save transform */
263 protected $mUser;
265 # Temporary
266 # These are variables reset at least once per parse regardless of $clearState
268 /** @var ParserOptions */
269 public $mOptions;
271 /** @var Title Title context, used for self-link rendering and similar things */
272 public $mTitle;
274 /** @var array Shortcut alias, see setOutputType() */
275 public $ot;
277 /** @var string The timestamp of the specified revision ID */
278 public $mRevisionTimestamp;
280 /** @var string */
281 public $mUniqPrefix;
284 * @var boolean Recursive call protection.
285 * This variable should be treated as if it were private.
287 public $mInParse = false;
289 /** @var int Output type, one of the OT_xxx constants */
290 protected $mOutputType;
292 /** @var Revision The revision object of the specified revision ID */
293 protected $mRevisionObject;
295 /** @var int ID to display in {{REVISIONID}} tags */
296 protected $mRevisionId;
298 /** @var string User to display in {{REVISIONUSER}} tag */
299 protected $mRevisionUser;
301 /** @var int Size to display in {{REVISIONSIZE}} variable */
302 protected $mRevisionSize;
304 /** @var bool|int For {{PAGESIZE}} on current page. */
305 protected $mInputSize = false;
308 * @var array Array with the language name of each language link (i.e. the
309 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
310 * duplicate language links to the ParserOutput.
312 protected $mLangLinkLanguages;
315 * @var int The revision ID which was used to fetch the timestamp
316 * @todo Unused?
318 private $mRevIdForTs;
321 * @param array $conf
323 public function __construct( $conf = array() ) {
324 $this->mConf = $conf;
325 $this->mUrlProtocols = wfUrlProtocols();
326 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
327 self::EXT_LINK_URL_CLASS . '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
328 if ( isset( $conf['preprocessorClass'] ) ) {
329 $this->mPreprocessorClass = $conf['preprocessorClass'];
330 } elseif ( defined( 'HPHP_VERSION' ) ) {
331 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
332 $this->mPreprocessorClass = 'Preprocessor_Hash';
333 } elseif ( extension_loaded( 'domxml' ) ) {
334 # PECL extension that conflicts with the core DOM extension (bug 13770)
335 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
336 $this->mPreprocessorClass = 'Preprocessor_Hash';
337 } elseif ( extension_loaded( 'dom' ) ) {
338 $this->mPreprocessorClass = 'Preprocessor_DOM';
339 } else {
340 $this->mPreprocessorClass = 'Preprocessor_Hash';
342 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
346 * Reduce memory usage to reduce the impact of circular references
348 function __destruct() {
349 if ( isset( $this->mLinkHolders ) ) {
350 unset( $this->mLinkHolders );
352 foreach ( $this as $name => $value ) {
353 unset( $this->$name );
358 * Allow extensions to clean up when the parser is cloned
360 function __clone() {
361 $this->mInParse = false;
362 wfRunHooks( 'ParserCloned', array( $this ) );
366 * Do various kinds of initialisation on the first call of the parser
368 function firstCallInit() {
369 if ( !$this->mFirstCall ) {
370 return;
372 $this->mFirstCall = false;
374 wfProfileIn( __METHOD__ );
376 CoreParserFunctions::register( $this );
377 CoreTagHooks::register( $this );
378 $this->initialiseVariables();
380 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
381 wfProfileOut( __METHOD__ );
385 * Clear Parser state
387 * @private
389 function clearState() {
390 wfProfileIn( __METHOD__ );
391 if ( $this->mFirstCall ) {
392 $this->firstCallInit();
394 $this->mOutput = new ParserOutput;
395 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
396 $this->mAutonumber = 0;
397 $this->mLastSection = '';
398 $this->mDTopen = false;
399 $this->mIncludeCount = array();
400 $this->mArgStack = false;
401 $this->mInPre = false;
402 $this->mLinkHolders = new LinkHolderArray( $this );
403 $this->mLinkID = 0;
404 $this->mRevisionObject = $this->mRevisionTimestamp =
405 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null;
406 $this->mVarCache = array();
407 $this->mUser = null;
408 $this->mLangLinkLanguages = array();
411 * Prefix for temporary replacement strings for the multipass parser.
412 * \x07 should never appear in input as it's disallowed in XML.
413 * Using it at the front also gives us a little extra robustness
414 * since it shouldn't match when butted up against identifier-like
415 * string constructs.
417 * Must not consist of all title characters, or else it will change
418 * the behavior of <nowiki> in a link.
420 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
421 $this->mStripState = new StripState( $this->mUniqPrefix );
423 # Clear these on every parse, bug 4549
424 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
426 $this->mShowToc = true;
427 $this->mForceTocPosition = false;
428 $this->mIncludeSizes = array(
429 'post-expand' => 0,
430 'arg' => 0,
432 $this->mPPNodeCount = 0;
433 $this->mGeneratedPPNodeCount = 0;
434 $this->mHighestExpansionDepth = 0;
435 $this->mDefaultSort = false;
436 $this->mHeadings = array();
437 $this->mDoubleUnderscores = array();
438 $this->mExpensiveFunctionCount = 0;
440 # Fix cloning
441 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
442 $this->mPreprocessor = null;
445 wfRunHooks( 'ParserClearState', array( &$this ) );
446 wfProfileOut( __METHOD__ );
450 * Convert wikitext to HTML
451 * Do not call this function recursively.
453 * @param string $text text we want to parse
454 * @param Title $title
455 * @param ParserOptions $options
456 * @param bool $linestart
457 * @param bool $clearState
458 * @param int $revid Number to pass in {{REVISIONID}}
459 * @return ParserOutput A ParserOutput
461 public function parse( $text, Title $title, ParserOptions $options,
462 $linestart = true, $clearState = true, $revid = null
465 * First pass--just handle <nowiki> sections, pass the rest off
466 * to internalParse() which does all the real work.
469 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
470 $fname = __METHOD__ . '-' . wfGetCaller();
471 wfProfileIn( __METHOD__ );
472 wfProfileIn( $fname );
474 if ( $clearState ) {
475 $magicScopeVariable = $this->lock();
478 $this->startParse( $title, $options, self::OT_HTML, $clearState );
480 $this->mInputSize = strlen( $text );
481 if ( $this->mOptions->getEnableLimitReport() ) {
482 $this->mOutput->resetParseStartTime();
485 # Remove the strip marker tag prefix from the input, if present.
486 if ( $clearState ) {
487 $text = str_replace( $this->mUniqPrefix, '', $text );
490 $oldRevisionId = $this->mRevisionId;
491 $oldRevisionObject = $this->mRevisionObject;
492 $oldRevisionTimestamp = $this->mRevisionTimestamp;
493 $oldRevisionUser = $this->mRevisionUser;
494 $oldRevisionSize = $this->mRevisionSize;
495 if ( $revid !== null ) {
496 $this->mRevisionId = $revid;
497 $this->mRevisionObject = null;
498 $this->mRevisionTimestamp = null;
499 $this->mRevisionUser = null;
500 $this->mRevisionSize = null;
503 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
504 # No more strip!
505 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
506 $text = $this->internalParse( $text );
507 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) );
509 $text = $this->mStripState->unstripGeneral( $text );
511 # Clean up special characters, only run once, next-to-last before doBlockLevels
512 $fixtags = array(
513 # french spaces, last one Guillemet-left
514 # only if there is something before the space
515 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
516 # french spaces, Guillemet-right
517 '/(\\302\\253) /' => '\\1&#160;',
518 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
520 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
522 $text = $this->doBlockLevels( $text, $linestart );
524 $this->replaceLinkHolders( $text );
527 * The input doesn't get language converted if
528 * a) It's disabled
529 * b) Content isn't converted
530 * c) It's a conversion table
531 * d) it is an interface message (which is in the user language)
533 if ( !( $options->getDisableContentConversion()
534 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
536 if ( !$this->mOptions->getInterfaceMessage() ) {
537 # The position of the convert() call should not be changed. it
538 # assumes that the links are all replaced and the only thing left
539 # is the <nowiki> mark.
540 $text = $this->getConverterLanguage()->convert( $text );
545 * A converted title will be provided in the output object if title and
546 * content conversion are enabled, the article text does not contain
547 * a conversion-suppressing double-underscore tag, and no
548 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
549 * automatic link conversion.
551 if ( !( $options->getDisableTitleConversion()
552 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
553 || isset( $this->mDoubleUnderscores['notitleconvert'] )
554 || $this->mOutput->getDisplayTitle() !== false )
556 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
557 if ( $convruletitle ) {
558 $this->mOutput->setTitleText( $convruletitle );
559 } else {
560 $titleText = $this->getConverterLanguage()->convertTitle( $title );
561 $this->mOutput->setTitleText( $titleText );
565 $text = $this->mStripState->unstripNoWiki( $text );
567 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
569 $text = $this->replaceTransparentTags( $text );
570 $text = $this->mStripState->unstripGeneral( $text );
572 $text = Sanitizer::normalizeCharReferences( $text );
574 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
575 $text = MWTidy::tidy( $text );
576 } else {
577 # attempt to sanitize at least some nesting problems
578 # (bug #2702 and quite a few others)
579 $tidyregs = array(
580 # ''Something [http://www.cool.com cool''] -->
581 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
582 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
583 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
584 # fix up an anchor inside another anchor, only
585 # at least for a single single nested link (bug 3695)
586 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
587 '\\1\\2</a>\\3</a>\\1\\4</a>',
588 # fix div inside inline elements- doBlockLevels won't wrap a line which
589 # contains a div, so fix it up here; replace
590 # div with escaped text
591 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
592 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
593 # remove empty italic or bold tag pairs, some
594 # introduced by rules above
595 '/<([bi])><\/\\1>/' => '',
598 $text = preg_replace(
599 array_keys( $tidyregs ),
600 array_values( $tidyregs ),
601 $text );
604 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
605 $this->limitationWarn( 'expensive-parserfunction',
606 $this->mExpensiveFunctionCount,
607 $this->mOptions->getExpensiveParserFunctionLimit()
611 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
613 # Information on include size limits, for the benefit of users who try to skirt them
614 if ( $this->mOptions->getEnableLimitReport() ) {
615 $max = $this->mOptions->getMaxIncludeSize();
617 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' );
618 if ( $cpuTime !== null ) {
619 $this->mOutput->setLimitReportData( 'limitreport-cputime',
620 sprintf( "%.3f", $cpuTime )
624 $wallTime = $this->mOutput->getTimeSinceStart( 'wall' );
625 $this->mOutput->setLimitReportData( 'limitreport-walltime',
626 sprintf( "%.3f", $wallTime )
629 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes',
630 array( $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() )
632 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes',
633 array( $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() )
635 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize',
636 array( $this->mIncludeSizes['post-expand'], $max )
638 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize',
639 array( $this->mIncludeSizes['arg'], $max )
641 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth',
642 array( $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() )
644 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount',
645 array( $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() )
647 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput ) );
649 $limitReport = "NewPP limit report\n";
650 if ( $wgShowHostnames ) {
651 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
653 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
654 if ( wfRunHooks( 'ParserLimitReportFormat',
655 array( $key, &$value, &$limitReport, false, false )
656 ) ) {
657 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
658 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
659 ->inLanguage( 'en' )->useDatabase( false );
660 if ( !$valueMsg->exists() ) {
661 $valueMsg = new RawMessage( '$1' );
663 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
664 $valueMsg->params( $value );
665 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
669 // Since we're not really outputting HTML, decode the entities and
670 // then re-encode the things that need hiding inside HTML comments.
671 $limitReport = htmlspecialchars_decode( $limitReport );
672 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
674 // Sanitize for comment. Note '‐' in the replacement is U+2010,
675 // which looks much like the problematic '-'.
676 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&amp;' ), $limitReport );
677 $text .= "\n<!-- \n$limitReport-->\n";
679 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
680 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
681 $this->mTitle->getPrefixedDBkey() );
684 $this->mOutput->setText( $text );
686 $this->mRevisionId = $oldRevisionId;
687 $this->mRevisionObject = $oldRevisionObject;
688 $this->mRevisionTimestamp = $oldRevisionTimestamp;
689 $this->mRevisionUser = $oldRevisionUser;
690 $this->mRevisionSize = $oldRevisionSize;
691 $this->mInputSize = false;
692 wfProfileOut( $fname );
693 wfProfileOut( __METHOD__ );
695 return $this->mOutput;
699 * Recursive parser entry point that can be called from an extension tag
700 * hook.
702 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
704 * @param string $text Text extension wants to have parsed
705 * @param bool|PPFrame $frame The frame to use for expanding any template variables
707 * @return string
709 function recursiveTagParse( $text, $frame = false ) {
710 wfProfileIn( __METHOD__ );
711 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
712 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
713 $text = $this->internalParse( $text, false, $frame );
714 wfProfileOut( __METHOD__ );
715 return $text;
719 * Expand templates and variables in the text, producing valid, static wikitext.
720 * Also removes comments.
721 * @param string $text
722 * @param Title $title
723 * @param ParserOptions $options
724 * @param int|null $revid
725 * @return mixed|string
727 function preprocess( $text, Title $title = null, ParserOptions $options, $revid = null ) {
728 wfProfileIn( __METHOD__ );
729 $magicScopeVariable = $this->lock();
730 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
731 if ( $revid !== null ) {
732 $this->mRevisionId = $revid;
734 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
735 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
736 $text = $this->replaceVariables( $text );
737 $text = $this->mStripState->unstripBoth( $text );
738 wfProfileOut( __METHOD__ );
739 return $text;
743 * Recursive parser entry point that can be called from an extension tag
744 * hook.
746 * @param string $text Text to be expanded
747 * @param bool|PPFrame $frame The frame to use for expanding any template variables
748 * @return string
749 * @since 1.19
751 public function recursivePreprocess( $text, $frame = false ) {
752 wfProfileIn( __METHOD__ );
753 $text = $this->replaceVariables( $text, $frame );
754 $text = $this->mStripState->unstripBoth( $text );
755 wfProfileOut( __METHOD__ );
756 return $text;
760 * Process the wikitext for the "?preload=" feature. (bug 5210)
762 * "<noinclude>", "<includeonly>" etc. are parsed as for template
763 * transclusion, comments, templates, arguments, tags hooks and parser
764 * functions are untouched.
766 * @param string $text
767 * @param Title $title
768 * @param ParserOptions $options
769 * @param array $params
770 * @return string
772 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = array() ) {
773 $msg = new RawMessage( $text );
774 $text = $msg->params( $params )->plain();
776 # Parser (re)initialisation
777 $magicScopeVariable = $this->lock();
778 $this->startParse( $title, $options, self::OT_PLAIN, true );
780 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
781 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
782 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
783 $text = $this->mStripState->unstripBoth( $text );
784 return $text;
788 * Get a random string
790 * @return string
792 public static function getRandomString() {
793 return wfRandomString( 16 );
797 * Set the current user.
798 * Should only be used when doing pre-save transform.
800 * @param User|null $user User object or null (to reset)
802 function setUser( $user ) {
803 $this->mUser = $user;
807 * Accessor for mUniqPrefix.
809 * @return string
811 public function uniqPrefix() {
812 if ( !isset( $this->mUniqPrefix ) ) {
813 # @todo FIXME: This is probably *horribly wrong*
814 # LanguageConverter seems to want $wgParser's uniqPrefix, however
815 # if this is called for a parser cache hit, the parser may not
816 # have ever been initialized in the first place.
817 # Not really sure what the heck is supposed to be going on here.
818 return '';
819 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
821 return $this->mUniqPrefix;
825 * Set the context title
827 * @param Title $t
829 function setTitle( $t ) {
830 if ( !$t ) {
831 $t = Title::newFromText( 'NO TITLE' );
834 if ( $t->hasFragment() ) {
835 # Strip the fragment to avoid various odd effects
836 $this->mTitle = clone $t;
837 $this->mTitle->setFragment( '' );
838 } else {
839 $this->mTitle = $t;
844 * Accessor for the Title object
846 * @return Title
848 function getTitle() {
849 return $this->mTitle;
853 * Accessor/mutator for the Title object
855 * @param Title $x Title object or null to just get the current one
856 * @return Title
858 function Title( $x = null ) {
859 return wfSetVar( $this->mTitle, $x );
863 * Set the output type
865 * @param int $ot New value
867 function setOutputType( $ot ) {
868 $this->mOutputType = $ot;
869 # Shortcut alias
870 $this->ot = array(
871 'html' => $ot == self::OT_HTML,
872 'wiki' => $ot == self::OT_WIKI,
873 'pre' => $ot == self::OT_PREPROCESS,
874 'plain' => $ot == self::OT_PLAIN,
879 * Accessor/mutator for the output type
881 * @param int|null $x New value or null to just get the current one
882 * @return int
884 function OutputType( $x = null ) {
885 return wfSetVar( $this->mOutputType, $x );
889 * Get the ParserOutput object
891 * @return ParserOutput
893 function getOutput() {
894 return $this->mOutput;
898 * Get the ParserOptions object
900 * @return ParserOptions object
902 function getOptions() {
903 return $this->mOptions;
907 * Accessor/mutator for the ParserOptions object
909 * @param ParserOptions $x New value or null to just get the current one
910 * @return ParserOptions Current ParserOptions object
912 function Options( $x = null ) {
913 return wfSetVar( $this->mOptions, $x );
917 * @return int
919 function nextLinkID() {
920 return $this->mLinkID++;
924 * @param int $id
926 function setLinkID( $id ) {
927 $this->mLinkID = $id;
931 * Get a language object for use in parser functions such as {{FORMATNUM:}}
932 * @return Language
934 function getFunctionLang() {
935 return $this->getTargetLanguage();
939 * Get the target language for the content being parsed. This is usually the
940 * language that the content is in.
942 * @since 1.19
944 * @throws MWException
945 * @return Language|null
947 public function getTargetLanguage() {
948 $target = $this->mOptions->getTargetLanguage();
950 if ( $target !== null ) {
951 return $target;
952 } elseif ( $this->mOptions->getInterfaceMessage() ) {
953 return $this->mOptions->getUserLangObj();
954 } elseif ( is_null( $this->mTitle ) ) {
955 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
958 return $this->mTitle->getPageLanguage();
962 * Get the language object for language conversion
963 * @return Language|null
965 function getConverterLanguage() {
966 return $this->getTargetLanguage();
970 * Get a User object either from $this->mUser, if set, or from the
971 * ParserOptions object otherwise
973 * @return User
975 function getUser() {
976 if ( !is_null( $this->mUser ) ) {
977 return $this->mUser;
979 return $this->mOptions->getUser();
983 * Get a preprocessor object
985 * @return Preprocessor
987 function getPreprocessor() {
988 if ( !isset( $this->mPreprocessor ) ) {
989 $class = $this->mPreprocessorClass;
990 $this->mPreprocessor = new $class( $this );
992 return $this->mPreprocessor;
996 * Replaces all occurrences of HTML-style comments and the given tags
997 * in the text with a random marker and returns the next text. The output
998 * parameter $matches will be an associative array filled with data in
999 * the form:
1001 * @code
1002 * 'UNIQ-xxxxx' => array(
1003 * 'element',
1004 * 'tag content',
1005 * array( 'param' => 'x' ),
1006 * '<element param="x">tag content</element>' ) )
1007 * @endcode
1009 * @param array $elements List of element names. Comments are always extracted.
1010 * @param string $text Source text string.
1011 * @param array $matches Out parameter, Array: extracted tags
1012 * @param string $uniq_prefix
1013 * @return string Stripped text
1015 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
1016 static $n = 1;
1017 $stripped = '';
1018 $matches = array();
1020 $taglist = implode( '|', $elements );
1021 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
1023 while ( $text != '' ) {
1024 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
1025 $stripped .= $p[0];
1026 if ( count( $p ) < 5 ) {
1027 break;
1029 if ( count( $p ) > 5 ) {
1030 # comment
1031 $element = $p[4];
1032 $attributes = '';
1033 $close = '';
1034 $inside = $p[5];
1035 } else {
1036 # tag
1037 $element = $p[1];
1038 $attributes = $p[2];
1039 $close = $p[3];
1040 $inside = $p[4];
1043 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
1044 $stripped .= $marker;
1046 if ( $close === '/>' ) {
1047 # Empty element tag, <tag />
1048 $content = null;
1049 $text = $inside;
1050 $tail = null;
1051 } else {
1052 if ( $element === '!--' ) {
1053 $end = '/(-->)/';
1054 } else {
1055 $end = "/(<\\/$element\\s*>)/i";
1057 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
1058 $content = $q[0];
1059 if ( count( $q ) < 3 ) {
1060 # No end tag -- let it run out to the end of the text.
1061 $tail = '';
1062 $text = '';
1063 } else {
1064 $tail = $q[1];
1065 $text = $q[2];
1069 $matches[$marker] = array( $element,
1070 $content,
1071 Sanitizer::decodeTagAttributes( $attributes ),
1072 "<$element$attributes$close$content$tail" );
1074 return $stripped;
1078 * Get a list of strippable XML-like elements
1080 * @return array
1082 function getStripList() {
1083 return $this->mStripList;
1087 * Add an item to the strip state
1088 * Returns the unique tag which must be inserted into the stripped text
1089 * The tag will be replaced with the original text in unstrip()
1091 * @param string $text
1093 * @return string
1095 function insertStripItem( $text ) {
1096 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
1097 $this->mMarkerIndex++;
1098 $this->mStripState->addGeneral( $rnd, $text );
1099 return $rnd;
1103 * parse the wiki syntax used to render tables
1105 * @private
1106 * @param string $text
1107 * @return string
1109 function doTableStuff( $text ) {
1110 wfProfileIn( __METHOD__ );
1112 $lines = StringUtils::explode( "\n", $text );
1113 $out = '';
1114 $td_history = array(); # Is currently a td tag open?
1115 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1116 $tr_history = array(); # Is currently a tr tag open?
1117 $tr_attributes = array(); # history of tr attributes
1118 $has_opened_tr = array(); # Did this table open a <tr> element?
1119 $indent_level = 0; # indent level of the table
1121 foreach ( $lines as $outLine ) {
1122 $line = trim( $outLine );
1124 if ( $line === '' ) { # empty line, go to next line
1125 $out .= $outLine . "\n";
1126 continue;
1129 $first_character = $line[0];
1130 $matches = array();
1132 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1133 # First check if we are starting a new table
1134 $indent_level = strlen( $matches[1] );
1136 $attributes = $this->mStripState->unstripBoth( $matches[2] );
1137 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
1139 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1140 array_push( $td_history, false );
1141 array_push( $last_tag_history, '' );
1142 array_push( $tr_history, false );
1143 array_push( $tr_attributes, '' );
1144 array_push( $has_opened_tr, false );
1145 } elseif ( count( $td_history ) == 0 ) {
1146 # Don't do any of the following
1147 $out .= $outLine . "\n";
1148 continue;
1149 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1150 # We are ending a table
1151 $line = '</table>' . substr( $line, 2 );
1152 $last_tag = array_pop( $last_tag_history );
1154 if ( !array_pop( $has_opened_tr ) ) {
1155 $line = "<tr><td></td></tr>{$line}";
1158 if ( array_pop( $tr_history ) ) {
1159 $line = "</tr>{$line}";
1162 if ( array_pop( $td_history ) ) {
1163 $line = "</{$last_tag}>{$line}";
1165 array_pop( $tr_attributes );
1166 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1167 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1168 # Now we have a table row
1169 $line = preg_replace( '#^\|-+#', '', $line );
1171 # Whats after the tag is now only attributes
1172 $attributes = $this->mStripState->unstripBoth( $line );
1173 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
1174 array_pop( $tr_attributes );
1175 array_push( $tr_attributes, $attributes );
1177 $line = '';
1178 $last_tag = array_pop( $last_tag_history );
1179 array_pop( $has_opened_tr );
1180 array_push( $has_opened_tr, true );
1182 if ( array_pop( $tr_history ) ) {
1183 $line = '</tr>';
1186 if ( array_pop( $td_history ) ) {
1187 $line = "</{$last_tag}>{$line}";
1190 $outLine = $line;
1191 array_push( $tr_history, false );
1192 array_push( $td_history, false );
1193 array_push( $last_tag_history, '' );
1194 } elseif ( $first_character === '|'
1195 || $first_character === '!'
1196 || substr( $line, 0, 2 ) === '|+'
1198 # This might be cell elements, td, th or captions
1199 if ( substr( $line, 0, 2 ) === '|+' ) {
1200 $first_character = '+';
1201 $line = substr( $line, 1 );
1204 $line = substr( $line, 1 );
1206 if ( $first_character === '!' ) {
1207 $line = str_replace( '!!', '||', $line );
1210 # Split up multiple cells on the same line.
1211 # FIXME : This can result in improper nesting of tags processed
1212 # by earlier parser steps, but should avoid splitting up eg
1213 # attribute values containing literal "||".
1214 $cells = StringUtils::explodeMarkup( '||', $line );
1216 $outLine = '';
1218 # Loop through each table cell
1219 foreach ( $cells as $cell ) {
1220 $previous = '';
1221 if ( $first_character !== '+' ) {
1222 $tr_after = array_pop( $tr_attributes );
1223 if ( !array_pop( $tr_history ) ) {
1224 $previous = "<tr{$tr_after}>\n";
1226 array_push( $tr_history, true );
1227 array_push( $tr_attributes, '' );
1228 array_pop( $has_opened_tr );
1229 array_push( $has_opened_tr, true );
1232 $last_tag = array_pop( $last_tag_history );
1234 if ( array_pop( $td_history ) ) {
1235 $previous = "</{$last_tag}>\n{$previous}";
1238 if ( $first_character === '|' ) {
1239 $last_tag = 'td';
1240 } elseif ( $first_character === '!' ) {
1241 $last_tag = 'th';
1242 } elseif ( $first_character === '+' ) {
1243 $last_tag = 'caption';
1244 } else {
1245 $last_tag = '';
1248 array_push( $last_tag_history, $last_tag );
1250 # A cell could contain both parameters and data
1251 $cell_data = explode( '|', $cell, 2 );
1253 # Bug 553: Note that a '|' inside an invalid link should not
1254 # be mistaken as delimiting cell parameters
1255 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1256 $cell = "{$previous}<{$last_tag}>{$cell}";
1257 } elseif ( count( $cell_data ) == 1 ) {
1258 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1259 } else {
1260 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1261 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1262 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1265 $outLine .= $cell;
1266 array_push( $td_history, true );
1269 $out .= $outLine . "\n";
1272 # Closing open td, tr && table
1273 while ( count( $td_history ) > 0 ) {
1274 if ( array_pop( $td_history ) ) {
1275 $out .= "</td>\n";
1277 if ( array_pop( $tr_history ) ) {
1278 $out .= "</tr>\n";
1280 if ( !array_pop( $has_opened_tr ) ) {
1281 $out .= "<tr><td></td></tr>\n";
1284 $out .= "</table>\n";
1287 # Remove trailing line-ending (b/c)
1288 if ( substr( $out, -1 ) === "\n" ) {
1289 $out = substr( $out, 0, -1 );
1292 # special case: don't return empty table
1293 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1294 $out = '';
1297 wfProfileOut( __METHOD__ );
1299 return $out;
1303 * Helper function for parse() that transforms wiki markup into
1304 * HTML. Only called for $mOutputType == self::OT_HTML.
1306 * @private
1308 * @param string $text
1309 * @param bool $isMain
1310 * @param bool $frame
1312 * @return string
1314 function internalParse( $text, $isMain = true, $frame = false ) {
1315 wfProfileIn( __METHOD__ );
1317 $origText = $text;
1319 # Hook to suspend the parser in this state
1320 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
1321 wfProfileOut( __METHOD__ );
1322 return $text;
1325 # if $frame is provided, then use $frame for replacing any variables
1326 if ( $frame ) {
1327 # use frame depth to infer how include/noinclude tags should be handled
1328 # depth=0 means this is the top-level document; otherwise it's an included document
1329 if ( !$frame->depth ) {
1330 $flag = 0;
1331 } else {
1332 $flag = Parser::PTD_FOR_INCLUSION;
1334 $dom = $this->preprocessToDom( $text, $flag );
1335 $text = $frame->expand( $dom );
1336 } else {
1337 # if $frame is not provided, then use old-style replaceVariables
1338 $text = $this->replaceVariables( $text );
1341 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) );
1342 $text = Sanitizer::removeHTMLtags(
1343 $text,
1344 array( &$this, 'attributeStripCallback' ),
1345 false,
1346 array_keys( $this->mTransparentTagHooks )
1348 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
1350 # Tables need to come after variable replacement for things to work
1351 # properly; putting them before other transformations should keep
1352 # exciting things like link expansions from showing up in surprising
1353 # places.
1354 $text = $this->doTableStuff( $text );
1356 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1358 $text = $this->doDoubleUnderscore( $text );
1360 $text = $this->doHeadings( $text );
1361 $text = $this->replaceInternalLinks( $text );
1362 $text = $this->doAllQuotes( $text );
1363 $text = $this->replaceExternalLinks( $text );
1365 # replaceInternalLinks may sometimes leave behind
1366 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1367 $text = str_replace( $this->mUniqPrefix . 'NOPARSE', '', $text );
1369 $text = $this->doMagicLinks( $text );
1370 $text = $this->formatHeadings( $text, $origText, $isMain );
1372 wfProfileOut( __METHOD__ );
1373 return $text;
1377 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1378 * magic external links.
1380 * DML
1381 * @private
1383 * @param string $text
1385 * @return string
1387 function doMagicLinks( $text ) {
1388 wfProfileIn( __METHOD__ );
1389 $prots = wfUrlProtocolsWithoutProtRel();
1390 $urlChar = self::EXT_LINK_URL_CLASS;
1391 $text = preg_replace_callback(
1392 '!(?: # Start cases
1393 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1394 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1395 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1396 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1397 ISBN\s+(\b # m[5]: ISBN, capture number
1398 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1399 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1400 [0-9Xx] # check digit
1402 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1403 wfProfileOut( __METHOD__ );
1404 return $text;
1408 * @throws MWException
1409 * @param array $m
1410 * @return HTML|string
1412 function magicLinkCallback( $m ) {
1413 if ( isset( $m[1] ) && $m[1] !== '' ) {
1414 # Skip anchor
1415 return $m[0];
1416 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1417 # Skip HTML element
1418 return $m[0];
1419 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1420 # Free external link
1421 return $this->makeFreeExternalLink( $m[0] );
1422 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1423 # RFC or PMID
1424 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1425 $keyword = 'RFC';
1426 $urlmsg = 'rfcurl';
1427 $cssClass = 'mw-magiclink-rfc';
1428 $id = $m[4];
1429 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1430 $keyword = 'PMID';
1431 $urlmsg = 'pubmedurl';
1432 $cssClass = 'mw-magiclink-pmid';
1433 $id = $m[4];
1434 } else {
1435 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1436 substr( $m[0], 0, 20 ) . '"' );
1438 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1439 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1440 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1441 # ISBN
1442 $isbn = $m[5];
1443 $num = strtr( $isbn, array(
1444 '-' => '',
1445 ' ' => '',
1446 'x' => 'X',
1448 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1449 return '<a href="' .
1450 htmlspecialchars( $titleObj->getLocalURL() ) .
1451 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1452 } else {
1453 return $m[0];
1458 * Make a free external link, given a user-supplied URL
1460 * @param string $url
1462 * @return string HTML
1463 * @private
1465 function makeFreeExternalLink( $url ) {
1466 wfProfileIn( __METHOD__ );
1468 $trail = '';
1470 # The characters '<' and '>' (which were escaped by
1471 # removeHTMLtags()) should not be included in
1472 # URLs, per RFC 2396.
1473 $m2 = array();
1474 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1475 $trail = substr( $url, $m2[0][1] ) . $trail;
1476 $url = substr( $url, 0, $m2[0][1] );
1479 # Move trailing punctuation to $trail
1480 $sep = ',;\.:!?';
1481 # If there is no left bracket, then consider right brackets fair game too
1482 if ( strpos( $url, '(' ) === false ) {
1483 $sep .= ')';
1486 $numSepChars = strspn( strrev( $url ), $sep );
1487 if ( $numSepChars ) {
1488 $trail = substr( $url, -$numSepChars ) . $trail;
1489 $url = substr( $url, 0, -$numSepChars );
1492 $url = Sanitizer::cleanUrl( $url );
1494 # Is this an external image?
1495 $text = $this->maybeMakeExternalImage( $url );
1496 if ( $text === false ) {
1497 # Not an image, make a link
1498 $text = Linker::makeExternalLink( $url,
1499 $this->getConverterLanguage()->markNoConversion( $url, true ),
1500 true, 'free',
1501 $this->getExternalLinkAttribs( $url ) );
1502 # Register it in the output object...
1503 # Replace unnecessary URL escape codes with their equivalent characters
1504 $pasteurized = self::replaceUnusualEscapes( $url );
1505 $this->mOutput->addExternalLink( $pasteurized );
1507 wfProfileOut( __METHOD__ );
1508 return $text . $trail;
1512 * Parse headers and return html
1514 * @private
1516 * @param string $text
1518 * @return string
1520 function doHeadings( $text ) {
1521 wfProfileIn( __METHOD__ );
1522 for ( $i = 6; $i >= 1; --$i ) {
1523 $h = str_repeat( '=', $i );
1524 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1526 wfProfileOut( __METHOD__ );
1527 return $text;
1531 * Replace single quotes with HTML markup
1532 * @private
1534 * @param string $text
1536 * @return string the altered text
1538 function doAllQuotes( $text ) {
1539 wfProfileIn( __METHOD__ );
1540 $outtext = '';
1541 $lines = StringUtils::explode( "\n", $text );
1542 foreach ( $lines as $line ) {
1543 $outtext .= $this->doQuotes( $line ) . "\n";
1545 $outtext = substr( $outtext, 0, -1 );
1546 wfProfileOut( __METHOD__ );
1547 return $outtext;
1551 * Helper function for doAllQuotes()
1553 * @param string $text
1555 * @return string
1557 public function doQuotes( $text ) {
1558 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1559 $countarr = count( $arr );
1560 if ( $countarr == 1 ) {
1561 return $text;
1564 // First, do some preliminary work. This may shift some apostrophes from
1565 // being mark-up to being text. It also counts the number of occurrences
1566 // of bold and italics mark-ups.
1567 $numbold = 0;
1568 $numitalics = 0;
1569 for ( $i = 1; $i < $countarr; $i += 2 ) {
1570 $thislen = strlen( $arr[$i] );
1571 // If there are ever four apostrophes, assume the first is supposed to
1572 // be text, and the remaining three constitute mark-up for bold text.
1573 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1574 if ( $thislen == 4 ) {
1575 $arr[$i - 1] .= "'";
1576 $arr[$i] = "'''";
1577 $thislen = 3;
1578 } elseif ( $thislen > 5 ) {
1579 // If there are more than 5 apostrophes in a row, assume they're all
1580 // text except for the last 5.
1581 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1582 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1583 $arr[$i] = "'''''";
1584 $thislen = 5;
1586 // Count the number of occurrences of bold and italics mark-ups.
1587 if ( $thislen == 2 ) {
1588 $numitalics++;
1589 } elseif ( $thislen == 3 ) {
1590 $numbold++;
1591 } elseif ( $thislen == 5 ) {
1592 $numitalics++;
1593 $numbold++;
1597 // If there is an odd number of both bold and italics, it is likely
1598 // that one of the bold ones was meant to be an apostrophe followed
1599 // by italics. Which one we cannot know for certain, but it is more
1600 // likely to be one that has a single-letter word before it.
1601 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1602 $firstsingleletterword = -1;
1603 $firstmultiletterword = -1;
1604 $firstspace = -1;
1605 for ( $i = 1; $i < $countarr; $i += 2 ) {
1606 if ( strlen( $arr[$i] ) == 3 ) {
1607 $x1 = substr( $arr[$i - 1], -1 );
1608 $x2 = substr( $arr[$i - 1], -2, 1 );
1609 if ( $x1 === ' ' ) {
1610 if ( $firstspace == -1 ) {
1611 $firstspace = $i;
1613 } elseif ( $x2 === ' ' ) {
1614 if ( $firstsingleletterword == -1 ) {
1615 $firstsingleletterword = $i;
1616 // if $firstsingleletterword is set, we don't
1617 // look at the other options, so we can bail early.
1618 break;
1620 } else {
1621 if ( $firstmultiletterword == -1 ) {
1622 $firstmultiletterword = $i;
1628 // If there is a single-letter word, use it!
1629 if ( $firstsingleletterword > -1 ) {
1630 $arr[$firstsingleletterword] = "''";
1631 $arr[$firstsingleletterword - 1] .= "'";
1632 } elseif ( $firstmultiletterword > -1 ) {
1633 // If not, but there's a multi-letter word, use that one.
1634 $arr[$firstmultiletterword] = "''";
1635 $arr[$firstmultiletterword - 1] .= "'";
1636 } elseif ( $firstspace > -1 ) {
1637 // ... otherwise use the first one that has neither.
1638 // (notice that it is possible for all three to be -1 if, for example,
1639 // there is only one pentuple-apostrophe in the line)
1640 $arr[$firstspace] = "''";
1641 $arr[$firstspace - 1] .= "'";
1645 // Now let's actually convert our apostrophic mush to HTML!
1646 $output = '';
1647 $buffer = '';
1648 $state = '';
1649 $i = 0;
1650 foreach ( $arr as $r ) {
1651 if ( ( $i % 2 ) == 0 ) {
1652 if ( $state === 'both' ) {
1653 $buffer .= $r;
1654 } else {
1655 $output .= $r;
1657 } else {
1658 $thislen = strlen( $r );
1659 if ( $thislen == 2 ) {
1660 if ( $state === 'i' ) {
1661 $output .= '</i>';
1662 $state = '';
1663 } elseif ( $state === 'bi' ) {
1664 $output .= '</i>';
1665 $state = 'b';
1666 } elseif ( $state === 'ib' ) {
1667 $output .= '</b></i><b>';
1668 $state = 'b';
1669 } elseif ( $state === 'both' ) {
1670 $output .= '<b><i>' . $buffer . '</i>';
1671 $state = 'b';
1672 } else { // $state can be 'b' or ''
1673 $output .= '<i>';
1674 $state .= 'i';
1676 } elseif ( $thislen == 3 ) {
1677 if ( $state === 'b' ) {
1678 $output .= '</b>';
1679 $state = '';
1680 } elseif ( $state === 'bi' ) {
1681 $output .= '</i></b><i>';
1682 $state = 'i';
1683 } elseif ( $state === 'ib' ) {
1684 $output .= '</b>';
1685 $state = 'i';
1686 } elseif ( $state === 'both' ) {
1687 $output .= '<i><b>' . $buffer . '</b>';
1688 $state = 'i';
1689 } else { // $state can be 'i' or ''
1690 $output .= '<b>';
1691 $state .= 'b';
1693 } elseif ( $thislen == 5 ) {
1694 if ( $state === 'b' ) {
1695 $output .= '</b><i>';
1696 $state = 'i';
1697 } elseif ( $state === 'i' ) {
1698 $output .= '</i><b>';
1699 $state = 'b';
1700 } elseif ( $state === 'bi' ) {
1701 $output .= '</i></b>';
1702 $state = '';
1703 } elseif ( $state === 'ib' ) {
1704 $output .= '</b></i>';
1705 $state = '';
1706 } elseif ( $state === 'both' ) {
1707 $output .= '<i><b>' . $buffer . '</b></i>';
1708 $state = '';
1709 } else { // ($state == '')
1710 $buffer = '';
1711 $state = 'both';
1715 $i++;
1717 // Now close all remaining tags. Notice that the order is important.
1718 if ( $state === 'b' || $state === 'ib' ) {
1719 $output .= '</b>';
1721 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1722 $output .= '</i>';
1724 if ( $state === 'bi' ) {
1725 $output .= '</b>';
1727 // There might be lonely ''''', so make sure we have a buffer
1728 if ( $state === 'both' && $buffer ) {
1729 $output .= '<b><i>' . $buffer . '</i></b>';
1731 return $output;
1735 * Replace external links (REL)
1737 * Note: this is all very hackish and the order of execution matters a lot.
1738 * Make sure to run tests/parserTests.php if you change this code.
1740 * @private
1742 * @param string $text
1744 * @throws MWException
1745 * @return string
1747 function replaceExternalLinks( $text ) {
1748 wfProfileIn( __METHOD__ );
1750 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1751 if ( $bits === false ) {
1752 wfProfileOut( __METHOD__ );
1753 throw new MWException( "PCRE needs to be compiled with "
1754 . "--enable-unicode-properties in order for MediaWiki to function" );
1756 $s = array_shift( $bits );
1758 $i = 0;
1759 while ( $i < count( $bits ) ) {
1760 $url = $bits[$i++];
1761 $i++; // protocol
1762 $text = $bits[$i++];
1763 $trail = $bits[$i++];
1765 # The characters '<' and '>' (which were escaped by
1766 # removeHTMLtags()) should not be included in
1767 # URLs, per RFC 2396.
1768 $m2 = array();
1769 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1770 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1771 $url = substr( $url, 0, $m2[0][1] );
1774 # If the link text is an image URL, replace it with an <img> tag
1775 # This happened by accident in the original parser, but some people used it extensively
1776 $img = $this->maybeMakeExternalImage( $text );
1777 if ( $img !== false ) {
1778 $text = $img;
1781 $dtrail = '';
1783 # Set linktype for CSS - if URL==text, link is essentially free
1784 $linktype = ( $text === $url ) ? 'free' : 'text';
1786 # No link text, e.g. [http://domain.tld/some.link]
1787 if ( $text == '' ) {
1788 # Autonumber
1789 $langObj = $this->getTargetLanguage();
1790 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1791 $linktype = 'autonumber';
1792 } else {
1793 # Have link text, e.g. [http://domain.tld/some.link text]s
1794 # Check for trail
1795 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1798 $text = $this->getConverterLanguage()->markNoConversion( $text );
1800 $url = Sanitizer::cleanUrl( $url );
1802 # Use the encoded URL
1803 # This means that users can paste URLs directly into the text
1804 # Funny characters like ö aren't valid in URLs anyway
1805 # This was changed in August 2004
1806 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1807 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1809 # Register link in the output object.
1810 # Replace unnecessary URL escape codes with the referenced character
1811 # This prevents spammers from hiding links from the filters
1812 $pasteurized = self::replaceUnusualEscapes( $url );
1813 $this->mOutput->addExternalLink( $pasteurized );
1816 wfProfileOut( __METHOD__ );
1817 return $s;
1821 * Get the rel attribute for a particular external link.
1823 * @since 1.21
1824 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1825 * nofollow if appropriate
1826 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1827 * @return string|null Rel attribute for $url
1829 public static function getExternalLinkRel( $url = false, $title = null ) {
1830 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1831 $ns = $title ? $title->getNamespace() : false;
1832 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1833 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1835 return 'nofollow';
1837 return null;
1841 * Get an associative array of additional HTML attributes appropriate for a
1842 * particular external link. This currently may include rel => nofollow
1843 * (depending on configuration, namespace, and the URL's domain) and/or a
1844 * target attribute (depending on configuration).
1846 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1847 * nofollow if appropriate
1848 * @return array Associative array of HTML attributes
1850 function getExternalLinkAttribs( $url = false ) {
1851 $attribs = array();
1852 $attribs['rel'] = self::getExternalLinkRel( $url, $this->mTitle );
1854 if ( $this->mOptions->getExternalLinkTarget() ) {
1855 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1857 return $attribs;
1861 * Replace unusual URL escape codes with their equivalent characters
1863 * @param string $url
1864 * @return string
1866 * @todo This can merge genuinely required bits in the path or query string,
1867 * breaking legit URLs. A proper fix would treat the various parts of
1868 * the URL differently; as a workaround, just use the output for
1869 * statistical records, not for actual linking/output.
1871 static function replaceUnusualEscapes( $url ) {
1872 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1873 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1877 * Callback function used in replaceUnusualEscapes().
1878 * Replaces unusual URL escape codes with their equivalent character
1880 * @param array $matches
1882 * @return string
1884 private static function replaceUnusualEscapesCallback( $matches ) {
1885 $char = urldecode( $matches[0] );
1886 $ord = ord( $char );
1887 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1888 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1889 # No, shouldn't be escaped
1890 return $char;
1891 } else {
1892 # Yes, leave it escaped
1893 return $matches[0];
1898 * make an image if it's allowed, either through the global
1899 * option, through the exception, or through the on-wiki whitelist
1901 * @param string $url
1903 * @return string
1905 private function maybeMakeExternalImage( $url ) {
1906 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1907 $imagesexception = !empty( $imagesfrom );
1908 $text = false;
1909 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1910 if ( $imagesexception && is_array( $imagesfrom ) ) {
1911 $imagematch = false;
1912 foreach ( $imagesfrom as $match ) {
1913 if ( strpos( $url, $match ) === 0 ) {
1914 $imagematch = true;
1915 break;
1918 } elseif ( $imagesexception ) {
1919 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1920 } else {
1921 $imagematch = false;
1924 if ( $this->mOptions->getAllowExternalImages()
1925 || ( $imagesexception && $imagematch )
1927 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1928 # Image found
1929 $text = Linker::makeExternalImage( $url );
1932 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1933 && preg_match( self::EXT_IMAGE_REGEX, $url )
1935 $whitelist = explode(
1936 "\n",
1937 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1940 foreach ( $whitelist as $entry ) {
1941 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1942 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
1943 continue;
1945 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1946 # Image matches a whitelist entry
1947 $text = Linker::makeExternalImage( $url );
1948 break;
1952 return $text;
1956 * Process [[ ]] wikilinks
1958 * @param string $s
1960 * @return string Processed text
1962 * @private
1964 function replaceInternalLinks( $s ) {
1965 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1966 return $s;
1970 * Process [[ ]] wikilinks (RIL)
1971 * @param string $s
1972 * @throws MWException
1973 * @return LinkHolderArray
1975 * @private
1977 function replaceInternalLinks2( &$s ) {
1978 wfProfileIn( __METHOD__ );
1980 wfProfileIn( __METHOD__ . '-setup' );
1981 static $tc = false, $e1, $e1_img;
1982 # the % is needed to support urlencoded titles as well
1983 if ( !$tc ) {
1984 $tc = Title::legalChars() . '#%';
1985 # Match a link having the form [[namespace:link|alternate]]trail
1986 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1987 # Match cases where there is no "]]", which might still be images
1988 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1991 $holders = new LinkHolderArray( $this );
1993 # split the entire text string on occurrences of [[
1994 $a = StringUtils::explode( '[[', ' ' . $s );
1995 # get the first element (all text up to first [[), and remove the space we added
1996 $s = $a->current();
1997 $a->next();
1998 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1999 $s = substr( $s, 1 );
2001 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2002 $e2 = null;
2003 if ( $useLinkPrefixExtension ) {
2004 # Match the end of a line for a word that's not followed by whitespace,
2005 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2006 global $wgContLang;
2007 $charset = $wgContLang->linkPrefixCharset();
2008 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2011 if ( is_null( $this->mTitle ) ) {
2012 wfProfileOut( __METHOD__ . '-setup' );
2013 wfProfileOut( __METHOD__ );
2014 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2016 $nottalk = !$this->mTitle->isTalkPage();
2018 if ( $useLinkPrefixExtension ) {
2019 $m = array();
2020 if ( preg_match( $e2, $s, $m ) ) {
2021 $first_prefix = $m[2];
2022 } else {
2023 $first_prefix = false;
2025 } else {
2026 $prefix = '';
2029 $useSubpages = $this->areSubpagesAllowed();
2030 wfProfileOut( __METHOD__ . '-setup' );
2032 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2033 # Loop for each link
2034 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2035 // @codingStandardsIgnoreStart
2037 # Check for excessive memory usage
2038 if ( $holders->isBig() ) {
2039 # Too big
2040 # Do the existence check, replace the link holders and clear the array
2041 $holders->replace( $s );
2042 $holders->clear();
2045 if ( $useLinkPrefixExtension ) {
2046 wfProfileIn( __METHOD__ . '-prefixhandling' );
2047 if ( preg_match( $e2, $s, $m ) ) {
2048 $prefix = $m[2];
2049 $s = $m[1];
2050 } else {
2051 $prefix = '';
2053 # first link
2054 if ( $first_prefix ) {
2055 $prefix = $first_prefix;
2056 $first_prefix = false;
2058 wfProfileOut( __METHOD__ . '-prefixhandling' );
2061 $might_be_img = false;
2063 wfProfileIn( __METHOD__ . "-e1" );
2064 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2065 $text = $m[2];
2066 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2067 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2068 # the real problem is with the $e1 regex
2069 # See bug 1300.
2071 # Still some problems for cases where the ] is meant to be outside punctuation,
2072 # and no image is in sight. See bug 2095.
2074 if ( $text !== ''
2075 && substr( $m[3], 0, 1 ) === ']'
2076 && strpos( $text, '[' ) !== false
2078 $text .= ']'; # so that replaceExternalLinks($text) works later
2079 $m[3] = substr( $m[3], 1 );
2081 # fix up urlencoded title texts
2082 if ( strpos( $m[1], '%' ) !== false ) {
2083 # Should anchors '#' also be rejected?
2084 $m[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $m[1] ) );
2086 $trail = $m[3];
2087 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2088 # Invalid, but might be an image with a link in its caption
2089 $might_be_img = true;
2090 $text = $m[2];
2091 if ( strpos( $m[1], '%' ) !== false ) {
2092 $m[1] = rawurldecode( $m[1] );
2094 $trail = "";
2095 } else { # Invalid form; output directly
2096 $s .= $prefix . '[[' . $line;
2097 wfProfileOut( __METHOD__ . "-e1" );
2098 continue;
2100 wfProfileOut( __METHOD__ . "-e1" );
2101 wfProfileIn( __METHOD__ . "-misc" );
2103 # Don't allow internal links to pages containing
2104 # PROTO: where PROTO is a valid URL protocol; these
2105 # should be external links.
2106 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) {
2107 $s .= $prefix . '[[' . $line;
2108 wfProfileOut( __METHOD__ . "-misc" );
2109 continue;
2112 # Make subpage if necessary
2113 if ( $useSubpages ) {
2114 $link = $this->maybeDoSubpageLink( $m[1], $text );
2115 } else {
2116 $link = $m[1];
2119 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
2120 if ( !$noforce ) {
2121 # Strip off leading ':'
2122 $link = substr( $link, 1 );
2125 wfProfileOut( __METHOD__ . "-misc" );
2126 wfProfileIn( __METHOD__ . "-title" );
2127 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
2128 if ( $nt === null ) {
2129 $s .= $prefix . '[[' . $line;
2130 wfProfileOut( __METHOD__ . "-title" );
2131 continue;
2134 $ns = $nt->getNamespace();
2135 $iw = $nt->getInterwiki();
2136 wfProfileOut( __METHOD__ . "-title" );
2138 if ( $might_be_img ) { # if this is actually an invalid link
2139 wfProfileIn( __METHOD__ . "-might_be_img" );
2140 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2141 $found = false;
2142 while ( true ) {
2143 # look at the next 'line' to see if we can close it there
2144 $a->next();
2145 $next_line = $a->current();
2146 if ( $next_line === false || $next_line === null ) {
2147 break;
2149 $m = explode( ']]', $next_line, 3 );
2150 if ( count( $m ) == 3 ) {
2151 # the first ]] closes the inner link, the second the image
2152 $found = true;
2153 $text .= "[[{$m[0]}]]{$m[1]}";
2154 $trail = $m[2];
2155 break;
2156 } elseif ( count( $m ) == 2 ) {
2157 # if there's exactly one ]] that's fine, we'll keep looking
2158 $text .= "[[{$m[0]}]]{$m[1]}";
2159 } else {
2160 # if $next_line is invalid too, we need look no further
2161 $text .= '[[' . $next_line;
2162 break;
2165 if ( !$found ) {
2166 # we couldn't find the end of this imageLink, so output it raw
2167 # but don't ignore what might be perfectly normal links in the text we've examined
2168 $holders->merge( $this->replaceInternalLinks2( $text ) );
2169 $s .= "{$prefix}[[$link|$text";
2170 # note: no $trail, because without an end, there *is* no trail
2171 wfProfileOut( __METHOD__ . "-might_be_img" );
2172 continue;
2174 } else { # it's not an image, so output it raw
2175 $s .= "{$prefix}[[$link|$text";
2176 # note: no $trail, because without an end, there *is* no trail
2177 wfProfileOut( __METHOD__ . "-might_be_img" );
2178 continue;
2180 wfProfileOut( __METHOD__ . "-might_be_img" );
2183 $wasblank = ( $text == '' );
2184 if ( $wasblank ) {
2185 $text = $link;
2186 } else {
2187 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2188 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2189 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2190 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2191 $text = $this->doQuotes( $text );
2194 # Link not escaped by : , create the various objects
2195 if ( $noforce ) {
2196 # Interwikis
2197 wfProfileIn( __METHOD__ . "-interwiki" );
2198 if ( $iw && $this->mOptions->getInterwikiMagic()
2199 && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' )
2201 // XXX: the above check prevents links to sites with identifiers that are not language codes
2203 # Bug 24502: filter duplicates
2204 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2205 $this->mLangLinkLanguages[$iw] = true;
2206 $this->mOutput->addLanguageLink( $nt->getFullText() );
2209 $s = rtrim( $s . $prefix );
2210 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2211 wfProfileOut( __METHOD__ . "-interwiki" );
2212 continue;
2214 wfProfileOut( __METHOD__ . "-interwiki" );
2216 if ( $ns == NS_FILE ) {
2217 wfProfileIn( __METHOD__ . "-image" );
2218 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2219 if ( $wasblank ) {
2220 # if no parameters were passed, $text
2221 # becomes something like "File:Foo.png",
2222 # which we don't want to pass on to the
2223 # image generator
2224 $text = '';
2225 } else {
2226 # recursively parse links inside the image caption
2227 # actually, this will parse them in any other parameters, too,
2228 # but it might be hard to fix that, and it doesn't matter ATM
2229 $text = $this->replaceExternalLinks( $text );
2230 $holders->merge( $this->replaceInternalLinks2( $text ) );
2232 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2233 $s .= $prefix . $this->armorLinks(
2234 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2235 } else {
2236 $s .= $prefix . $trail;
2238 wfProfileOut( __METHOD__ . "-image" );
2239 continue;
2242 if ( $ns == NS_CATEGORY ) {
2243 wfProfileIn( __METHOD__ . "-category" );
2244 $s = rtrim( $s . "\n" ); # bug 87
2246 if ( $wasblank ) {
2247 $sortkey = $this->getDefaultSort();
2248 } else {
2249 $sortkey = $text;
2251 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2252 $sortkey = str_replace( "\n", '', $sortkey );
2253 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2254 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2257 * Strip the whitespace Category links produce, see bug 87
2259 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2261 wfProfileOut( __METHOD__ . "-category" );
2262 continue;
2266 # Self-link checking. For some languages, variants of the title are checked in
2267 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2268 # for linking to a different variant.
2269 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2270 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2271 continue;
2274 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2275 # @todo FIXME: Should do batch file existence checks, see comment below
2276 if ( $ns == NS_MEDIA ) {
2277 wfProfileIn( __METHOD__ . "-media" );
2278 # Give extensions a chance to select the file revision for us
2279 $options = array();
2280 $descQuery = false;
2281 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2282 array( $this, $nt, &$options, &$descQuery ) );
2283 # Fetch and register the file (file title may be different via hooks)
2284 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2285 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2286 $s .= $prefix . $this->armorLinks(
2287 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2288 wfProfileOut( __METHOD__ . "-media" );
2289 continue;
2292 wfProfileIn( __METHOD__ . "-always_known" );
2293 # Some titles, such as valid special pages or files in foreign repos, should
2294 # be shown as bluelinks even though they're not included in the page table
2296 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2297 # batch file existence checks for NS_FILE and NS_MEDIA
2298 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2299 $this->mOutput->addLink( $nt );
2300 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2301 } else {
2302 # Links will be added to the output link list after checking
2303 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2305 wfProfileOut( __METHOD__ . "-always_known" );
2307 wfProfileOut( __METHOD__ );
2308 return $holders;
2312 * Render a forced-blue link inline; protect against double expansion of
2313 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2314 * Since this little disaster has to split off the trail text to avoid
2315 * breaking URLs in the following text without breaking trails on the
2316 * wiki links, it's been made into a horrible function.
2318 * @param Title $nt
2319 * @param string $text
2320 * @param array|string $query
2321 * @param string $trail
2322 * @param string $prefix
2323 * @return string HTML-wikitext mix oh yuck
2325 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2326 list( $inside, $trail ) = Linker::splitTrail( $trail );
2328 if ( is_string( $query ) ) {
2329 $query = wfCgiToArray( $query );
2331 if ( $text == '' ) {
2332 $text = htmlspecialchars( $nt->getPrefixedText() );
2335 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2337 return $this->armorLinks( $link ) . $trail;
2341 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2342 * going to go through further parsing steps before inline URL expansion.
2344 * Not needed quite as much as it used to be since free links are a bit
2345 * more sensible these days. But bracketed links are still an issue.
2347 * @param string $text More-or-less HTML
2348 * @return string Less-or-more HTML with NOPARSE bits
2350 function armorLinks( $text ) {
2351 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2352 "{$this->mUniqPrefix}NOPARSE$1", $text );
2356 * Return true if subpage links should be expanded on this page.
2357 * @return bool
2359 function areSubpagesAllowed() {
2360 # Some namespaces don't allow subpages
2361 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2365 * Handle link to subpage if necessary
2367 * @param string $target The source of the link
2368 * @param string &$text The link text, modified as necessary
2369 * @return string The full name of the link
2370 * @private
2372 function maybeDoSubpageLink( $target, &$text ) {
2373 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2376 /**#@+
2377 * Used by doBlockLevels()
2378 * @private
2380 * @return string
2382 function closeParagraph() {
2383 $result = '';
2384 if ( $this->mLastSection != '' ) {
2385 $result = '</' . $this->mLastSection . ">\n";
2387 $this->mInPre = false;
2388 $this->mLastSection = '';
2389 return $result;
2393 * getCommon() returns the length of the longest common substring
2394 * of both arguments, starting at the beginning of both.
2395 * @private
2397 * @param string $st1
2398 * @param string $st2
2400 * @return int
2402 function getCommon( $st1, $st2 ) {
2403 $fl = strlen( $st1 );
2404 $shorter = strlen( $st2 );
2405 if ( $fl < $shorter ) {
2406 $shorter = $fl;
2409 for ( $i = 0; $i < $shorter; ++$i ) {
2410 if ( $st1[$i] != $st2[$i] ) {
2411 break;
2414 return $i;
2418 * These next three functions open, continue, and close the list
2419 * element appropriate to the prefix character passed into them.
2420 * @private
2422 * @param string $char
2424 * @return string
2426 function openList( $char ) {
2427 $result = $this->closeParagraph();
2429 if ( '*' === $char ) {
2430 $result .= "<ul>\n<li>";
2431 } elseif ( '#' === $char ) {
2432 $result .= "<ol>\n<li>";
2433 } elseif ( ':' === $char ) {
2434 $result .= "<dl>\n<dd>";
2435 } elseif ( ';' === $char ) {
2436 $result .= "<dl>\n<dt>";
2437 $this->mDTopen = true;
2438 } else {
2439 $result = '<!-- ERR 1 -->';
2442 return $result;
2446 * TODO: document
2447 * @param string $char
2448 * @private
2450 * @return string
2452 function nextItem( $char ) {
2453 if ( '*' === $char || '#' === $char ) {
2454 return "</li>\n<li>";
2455 } elseif ( ':' === $char || ';' === $char ) {
2456 $close = "</dd>\n";
2457 if ( $this->mDTopen ) {
2458 $close = "</dt>\n";
2460 if ( ';' === $char ) {
2461 $this->mDTopen = true;
2462 return $close . '<dt>';
2463 } else {
2464 $this->mDTopen = false;
2465 return $close . '<dd>';
2468 return '<!-- ERR 2 -->';
2472 * @todo Document
2473 * @param string $char
2474 * @private
2476 * @return string
2478 function closeList( $char ) {
2479 if ( '*' === $char ) {
2480 $text = "</li>\n</ul>";
2481 } elseif ( '#' === $char ) {
2482 $text = "</li>\n</ol>";
2483 } elseif ( ':' === $char ) {
2484 if ( $this->mDTopen ) {
2485 $this->mDTopen = false;
2486 $text = "</dt>\n</dl>";
2487 } else {
2488 $text = "</dd>\n</dl>";
2490 } else {
2491 return '<!-- ERR 3 -->';
2493 return $text . "\n";
2495 /**#@-*/
2498 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2500 * @param string $text
2501 * @param bool $linestart Whether or not this is at the start of a line.
2502 * @private
2503 * @return string The lists rendered as HTML
2505 function doBlockLevels( $text, $linestart ) {
2506 wfProfileIn( __METHOD__ );
2508 # Parsing through the text line by line. The main thing
2509 # happening here is handling of block-level elements p, pre,
2510 # and making lists from lines starting with * # : etc.
2512 $textLines = StringUtils::explode( "\n", $text );
2514 $lastPrefix = $output = '';
2515 $this->mDTopen = $inBlockElem = false;
2516 $prefixLength = 0;
2517 $paragraphStack = false;
2518 $inBlockquote = false;
2520 foreach ( $textLines as $oLine ) {
2521 # Fix up $linestart
2522 if ( !$linestart ) {
2523 $output .= $oLine;
2524 $linestart = true;
2525 continue;
2527 # * = ul
2528 # # = ol
2529 # ; = dt
2530 # : = dd
2532 $lastPrefixLength = strlen( $lastPrefix );
2533 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2534 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2535 # If not in a <pre> element, scan for and figure out what prefixes are there.
2536 if ( !$this->mInPre ) {
2537 # Multiple prefixes may abut each other for nested lists.
2538 $prefixLength = strspn( $oLine, '*#:;' );
2539 $prefix = substr( $oLine, 0, $prefixLength );
2541 # eh?
2542 # ; and : are both from definition-lists, so they're equivalent
2543 # for the purposes of determining whether or not we need to open/close
2544 # elements.
2545 $prefix2 = str_replace( ';', ':', $prefix );
2546 $t = substr( $oLine, $prefixLength );
2547 $this->mInPre = (bool)$preOpenMatch;
2548 } else {
2549 # Don't interpret any other prefixes in preformatted text
2550 $prefixLength = 0;
2551 $prefix = $prefix2 = '';
2552 $t = $oLine;
2555 # List generation
2556 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2557 # Same as the last item, so no need to deal with nesting or opening stuff
2558 $output .= $this->nextItem( substr( $prefix, -1 ) );
2559 $paragraphStack = false;
2561 if ( substr( $prefix, -1 ) === ';' ) {
2562 # The one nasty exception: definition lists work like this:
2563 # ; title : definition text
2564 # So we check for : in the remainder text to split up the
2565 # title and definition, without b0rking links.
2566 $term = $t2 = '';
2567 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2568 $t = $t2;
2569 $output .= $term . $this->nextItem( ':' );
2572 } elseif ( $prefixLength || $lastPrefixLength ) {
2573 # We need to open or close prefixes, or both.
2575 # Either open or close a level...
2576 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2577 $paragraphStack = false;
2579 # Close all the prefixes which aren't shared.
2580 while ( $commonPrefixLength < $lastPrefixLength ) {
2581 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2582 --$lastPrefixLength;
2585 # Continue the current prefix if appropriate.
2586 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2587 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2590 # Open prefixes where appropriate.
2591 while ( $prefixLength > $commonPrefixLength ) {
2592 $char = substr( $prefix, $commonPrefixLength, 1 );
2593 $output .= $this->openList( $char );
2595 if ( ';' === $char ) {
2596 # @todo FIXME: This is dupe of code above
2597 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2598 $t = $t2;
2599 $output .= $term . $this->nextItem( ':' );
2602 ++$commonPrefixLength;
2604 $lastPrefix = $prefix2;
2607 # If we have no prefixes, go to paragraph mode.
2608 if ( 0 == $prefixLength ) {
2609 wfProfileIn( __METHOD__ . "-paragraph" );
2610 # No prefix (not in list)--go to paragraph mode
2611 # XXX: use a stack for nestable elements like span, table and div
2612 $openmatch = preg_match(
2613 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2614 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2617 $closematch = preg_match(
2618 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2619 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2620 . $this->mUniqPrefix
2621 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2625 if ( $openmatch or $closematch ) {
2626 $paragraphStack = false;
2627 # @todo bug 5718: paragraph closed
2628 $output .= $this->closeParagraph();
2629 if ( $preOpenMatch and !$preCloseMatch ) {
2630 $this->mInPre = true;
2632 $bqOffset = 0;
2633 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset ) ) {
2634 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2635 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
2637 $inBlockElem = !$closematch;
2638 } elseif ( !$inBlockElem && !$this->mInPre ) {
2639 if ( ' ' == substr( $t, 0, 1 )
2640 && ( $this->mLastSection === 'pre' || trim( $t ) != '' )
2641 && !$inBlockquote
2643 # pre
2644 if ( $this->mLastSection !== 'pre' ) {
2645 $paragraphStack = false;
2646 $output .= $this->closeParagraph() . '<pre>';
2647 $this->mLastSection = 'pre';
2649 $t = substr( $t, 1 );
2650 } else {
2651 # paragraph
2652 if ( trim( $t ) === '' ) {
2653 if ( $paragraphStack ) {
2654 $output .= $paragraphStack . '<br />';
2655 $paragraphStack = false;
2656 $this->mLastSection = 'p';
2657 } else {
2658 if ( $this->mLastSection !== 'p' ) {
2659 $output .= $this->closeParagraph();
2660 $this->mLastSection = '';
2661 $paragraphStack = '<p>';
2662 } else {
2663 $paragraphStack = '</p><p>';
2666 } else {
2667 if ( $paragraphStack ) {
2668 $output .= $paragraphStack;
2669 $paragraphStack = false;
2670 $this->mLastSection = 'p';
2671 } elseif ( $this->mLastSection !== 'p' ) {
2672 $output .= $this->closeParagraph() . '<p>';
2673 $this->mLastSection = 'p';
2678 wfProfileOut( __METHOD__ . "-paragraph" );
2680 # somewhere above we forget to get out of pre block (bug 785)
2681 if ( $preCloseMatch && $this->mInPre ) {
2682 $this->mInPre = false;
2684 if ( $paragraphStack === false ) {
2685 $output .= $t . "\n";
2688 while ( $prefixLength ) {
2689 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2690 --$prefixLength;
2692 if ( $this->mLastSection != '' ) {
2693 $output .= '</' . $this->mLastSection . '>';
2694 $this->mLastSection = '';
2697 wfProfileOut( __METHOD__ );
2698 return $output;
2702 * Split up a string on ':', ignoring any occurrences inside tags
2703 * to prevent illegal overlapping.
2705 * @param string $str The string to split
2706 * @param string &$before Set to everything before the ':'
2707 * @param string &$after Set to everything after the ':'
2708 * @throws MWException
2709 * @return string The position of the ':', or false if none found
2711 function findColonNoLinks( $str, &$before, &$after ) {
2712 wfProfileIn( __METHOD__ );
2714 $pos = strpos( $str, ':' );
2715 if ( $pos === false ) {
2716 # Nothing to find!
2717 wfProfileOut( __METHOD__ );
2718 return false;
2721 $lt = strpos( $str, '<' );
2722 if ( $lt === false || $lt > $pos ) {
2723 # Easy; no tag nesting to worry about
2724 $before = substr( $str, 0, $pos );
2725 $after = substr( $str, $pos + 1 );
2726 wfProfileOut( __METHOD__ );
2727 return $pos;
2730 # Ugly state machine to walk through avoiding tags.
2731 $state = self::COLON_STATE_TEXT;
2732 $stack = 0;
2733 $len = strlen( $str );
2734 for ( $i = 0; $i < $len; $i++ ) {
2735 $c = $str[$i];
2737 switch ( $state ) {
2738 # (Using the number is a performance hack for common cases)
2739 case 0: # self::COLON_STATE_TEXT:
2740 switch ( $c ) {
2741 case "<":
2742 # Could be either a <start> tag or an </end> tag
2743 $state = self::COLON_STATE_TAGSTART;
2744 break;
2745 case ":":
2746 if ( $stack == 0 ) {
2747 # We found it!
2748 $before = substr( $str, 0, $i );
2749 $after = substr( $str, $i + 1 );
2750 wfProfileOut( __METHOD__ );
2751 return $i;
2753 # Embedded in a tag; don't break it.
2754 break;
2755 default:
2756 # Skip ahead looking for something interesting
2757 $colon = strpos( $str, ':', $i );
2758 if ( $colon === false ) {
2759 # Nothing else interesting
2760 wfProfileOut( __METHOD__ );
2761 return false;
2763 $lt = strpos( $str, '<', $i );
2764 if ( $stack === 0 ) {
2765 if ( $lt === false || $colon < $lt ) {
2766 # We found it!
2767 $before = substr( $str, 0, $colon );
2768 $after = substr( $str, $colon + 1 );
2769 wfProfileOut( __METHOD__ );
2770 return $i;
2773 if ( $lt === false ) {
2774 # Nothing else interesting to find; abort!
2775 # We're nested, but there's no close tags left. Abort!
2776 break 2;
2778 # Skip ahead to next tag start
2779 $i = $lt;
2780 $state = self::COLON_STATE_TAGSTART;
2782 break;
2783 case 1: # self::COLON_STATE_TAG:
2784 # In a <tag>
2785 switch ( $c ) {
2786 case ">":
2787 $stack++;
2788 $state = self::COLON_STATE_TEXT;
2789 break;
2790 case "/":
2791 # Slash may be followed by >?
2792 $state = self::COLON_STATE_TAGSLASH;
2793 break;
2794 default:
2795 # ignore
2797 break;
2798 case 2: # self::COLON_STATE_TAGSTART:
2799 switch ( $c ) {
2800 case "/":
2801 $state = self::COLON_STATE_CLOSETAG;
2802 break;
2803 case "!":
2804 $state = self::COLON_STATE_COMMENT;
2805 break;
2806 case ">":
2807 # Illegal early close? This shouldn't happen D:
2808 $state = self::COLON_STATE_TEXT;
2809 break;
2810 default:
2811 $state = self::COLON_STATE_TAG;
2813 break;
2814 case 3: # self::COLON_STATE_CLOSETAG:
2815 # In a </tag>
2816 if ( $c === ">" ) {
2817 $stack--;
2818 if ( $stack < 0 ) {
2819 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
2820 wfProfileOut( __METHOD__ );
2821 return false;
2823 $state = self::COLON_STATE_TEXT;
2825 break;
2826 case self::COLON_STATE_TAGSLASH:
2827 if ( $c === ">" ) {
2828 # Yes, a self-closed tag <blah/>
2829 $state = self::COLON_STATE_TEXT;
2830 } else {
2831 # Probably we're jumping the gun, and this is an attribute
2832 $state = self::COLON_STATE_TAG;
2834 break;
2835 case 5: # self::COLON_STATE_COMMENT:
2836 if ( $c === "-" ) {
2837 $state = self::COLON_STATE_COMMENTDASH;
2839 break;
2840 case self::COLON_STATE_COMMENTDASH:
2841 if ( $c === "-" ) {
2842 $state = self::COLON_STATE_COMMENTDASHDASH;
2843 } else {
2844 $state = self::COLON_STATE_COMMENT;
2846 break;
2847 case self::COLON_STATE_COMMENTDASHDASH:
2848 if ( $c === ">" ) {
2849 $state = self::COLON_STATE_TEXT;
2850 } else {
2851 $state = self::COLON_STATE_COMMENT;
2853 break;
2854 default:
2855 wfProfileOut( __METHOD__ );
2856 throw new MWException( "State machine error in " . __METHOD__ );
2859 if ( $stack > 0 ) {
2860 wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2861 wfProfileOut( __METHOD__ );
2862 return false;
2864 wfProfileOut( __METHOD__ );
2865 return false;
2869 * Return value of a magic variable (like PAGENAME)
2871 * @private
2873 * @param int $index
2874 * @param bool|PPFrame $frame
2876 * @throws MWException
2877 * @return string
2879 function getVariableValue( $index, $frame = false ) {
2880 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2881 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2883 if ( is_null( $this->mTitle ) ) {
2884 // If no title set, bad things are going to happen
2885 // later. Title should always be set since this
2886 // should only be called in the middle of a parse
2887 // operation (but the unit-tests do funky stuff)
2888 throw new MWException( __METHOD__ . ' Should only be '
2889 . ' called while parsing (no title set)' );
2893 * Some of these require message or data lookups and can be
2894 * expensive to check many times.
2896 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2897 if ( isset( $this->mVarCache[$index] ) ) {
2898 return $this->mVarCache[$index];
2902 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2903 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2905 $pageLang = $this->getFunctionLang();
2907 switch ( $index ) {
2908 case 'currentmonth':
2909 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) );
2910 break;
2911 case 'currentmonth1':
2912 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2913 break;
2914 case 'currentmonthname':
2915 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2916 break;
2917 case 'currentmonthnamegen':
2918 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2919 break;
2920 case 'currentmonthabbrev':
2921 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2922 break;
2923 case 'currentday':
2924 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) );
2925 break;
2926 case 'currentday2':
2927 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) );
2928 break;
2929 case 'localmonth':
2930 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) );
2931 break;
2932 case 'localmonth1':
2933 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2934 break;
2935 case 'localmonthname':
2936 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2937 break;
2938 case 'localmonthnamegen':
2939 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2940 break;
2941 case 'localmonthabbrev':
2942 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2943 break;
2944 case 'localday':
2945 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) );
2946 break;
2947 case 'localday2':
2948 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) );
2949 break;
2950 case 'pagename':
2951 $value = wfEscapeWikiText( $this->mTitle->getText() );
2952 break;
2953 case 'pagenamee':
2954 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2955 break;
2956 case 'fullpagename':
2957 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2958 break;
2959 case 'fullpagenamee':
2960 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2961 break;
2962 case 'subpagename':
2963 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2964 break;
2965 case 'subpagenamee':
2966 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2967 break;
2968 case 'rootpagename':
2969 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2970 break;
2971 case 'rootpagenamee':
2972 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2973 ' ',
2974 '_',
2975 $this->mTitle->getRootText()
2976 ) ) );
2977 break;
2978 case 'basepagename':
2979 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2980 break;
2981 case 'basepagenamee':
2982 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2983 ' ',
2984 '_',
2985 $this->mTitle->getBaseText()
2986 ) ) );
2987 break;
2988 case 'talkpagename':
2989 if ( $this->mTitle->canTalk() ) {
2990 $talkPage = $this->mTitle->getTalkPage();
2991 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2992 } else {
2993 $value = '';
2995 break;
2996 case 'talkpagenamee':
2997 if ( $this->mTitle->canTalk() ) {
2998 $talkPage = $this->mTitle->getTalkPage();
2999 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3000 } else {
3001 $value = '';
3003 break;
3004 case 'subjectpagename':
3005 $subjPage = $this->mTitle->getSubjectPage();
3006 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3007 break;
3008 case 'subjectpagenamee':
3009 $subjPage = $this->mTitle->getSubjectPage();
3010 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3011 break;
3012 case 'pageid': // requested in bug 23427
3013 $pageid = $this->getTitle()->getArticleID();
3014 if ( $pageid == 0 ) {
3015 # 0 means the page doesn't exist in the database,
3016 # which means the user is previewing a new page.
3017 # The vary-revision flag must be set, because the magic word
3018 # will have a different value once the page is saved.
3019 $this->mOutput->setFlag( 'vary-revision' );
3020 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3022 $value = $pageid ? $pageid : null;
3023 break;
3024 case 'revisionid':
3025 # Let the edit saving system know we should parse the page
3026 # *after* a revision ID has been assigned.
3027 $this->mOutput->setFlag( 'vary-revision' );
3028 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
3029 $value = $this->mRevisionId;
3030 break;
3031 case 'revisionday':
3032 # Let the edit saving system know we should parse the page
3033 # *after* a revision ID has been assigned. This is for null edits.
3034 $this->mOutput->setFlag( 'vary-revision' );
3035 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3036 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3037 break;
3038 case 'revisionday2':
3039 # Let the edit saving system know we should parse the page
3040 # *after* a revision ID has been assigned. This is for null edits.
3041 $this->mOutput->setFlag( 'vary-revision' );
3042 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3043 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3044 break;
3045 case 'revisionmonth':
3046 # Let the edit saving system know we should parse the page
3047 # *after* a revision ID has been assigned. This is for null edits.
3048 $this->mOutput->setFlag( 'vary-revision' );
3049 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3050 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3051 break;
3052 case 'revisionmonth1':
3053 # Let the edit saving system know we should parse the page
3054 # *after* a revision ID has been assigned. This is for null edits.
3055 $this->mOutput->setFlag( 'vary-revision' );
3056 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3057 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3058 break;
3059 case 'revisionyear':
3060 # Let the edit saving system know we should parse the page
3061 # *after* a revision ID has been assigned. This is for null edits.
3062 $this->mOutput->setFlag( 'vary-revision' );
3063 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3064 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3065 break;
3066 case 'revisiontimestamp':
3067 # Let the edit saving system know we should parse the page
3068 # *after* a revision ID has been assigned. This is for null edits.
3069 $this->mOutput->setFlag( 'vary-revision' );
3070 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3071 $value = $this->getRevisionTimestamp();
3072 break;
3073 case 'revisionuser':
3074 # Let the edit saving system know we should parse the page
3075 # *after* a revision ID has been assigned. This is for null edits.
3076 $this->mOutput->setFlag( 'vary-revision' );
3077 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3078 $value = $this->getRevisionUser();
3079 break;
3080 case 'revisionsize':
3081 # Let the edit saving system know we should parse the page
3082 # *after* a revision ID has been assigned. This is for null edits.
3083 $this->mOutput->setFlag( 'vary-revision' );
3084 wfDebug( __METHOD__ . ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3085 $value = $this->getRevisionSize();
3086 break;
3087 case 'namespace':
3088 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
3089 break;
3090 case 'namespacee':
3091 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
3092 break;
3093 case 'namespacenumber':
3094 $value = $this->mTitle->getNamespace();
3095 break;
3096 case 'talkspace':
3097 $value = $this->mTitle->canTalk()
3098 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
3099 : '';
3100 break;
3101 case 'talkspacee':
3102 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
3103 break;
3104 case 'subjectspace':
3105 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
3106 break;
3107 case 'subjectspacee':
3108 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
3109 break;
3110 case 'currentdayname':
3111 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
3112 break;
3113 case 'currentyear':
3114 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
3115 break;
3116 case 'currenttime':
3117 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
3118 break;
3119 case 'currenthour':
3120 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
3121 break;
3122 case 'currentweek':
3123 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3124 # int to remove the padding
3125 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
3126 break;
3127 case 'currentdow':
3128 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
3129 break;
3130 case 'localdayname':
3131 $value = $pageLang->getWeekdayName(
3132 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
3134 break;
3135 case 'localyear':
3136 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
3137 break;
3138 case 'localtime':
3139 $value = $pageLang->time(
3140 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
3141 false,
3142 false
3144 break;
3145 case 'localhour':
3146 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
3147 break;
3148 case 'localweek':
3149 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3150 # int to remove the padding
3151 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
3152 break;
3153 case 'localdow':
3154 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
3155 break;
3156 case 'numberofarticles':
3157 $value = $pageLang->formatNum( SiteStats::articles() );
3158 break;
3159 case 'numberoffiles':
3160 $value = $pageLang->formatNum( SiteStats::images() );
3161 break;
3162 case 'numberofusers':
3163 $value = $pageLang->formatNum( SiteStats::users() );
3164 break;
3165 case 'numberofactiveusers':
3166 $value = $pageLang->formatNum( SiteStats::activeUsers() );
3167 break;
3168 case 'numberofpages':
3169 $value = $pageLang->formatNum( SiteStats::pages() );
3170 break;
3171 case 'numberofadmins':
3172 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
3173 break;
3174 case 'numberofedits':
3175 $value = $pageLang->formatNum( SiteStats::edits() );
3176 break;
3177 case 'numberofviews':
3178 global $wgDisableCounters;
3179 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : '';
3180 break;
3181 case 'currenttimestamp':
3182 $value = wfTimestamp( TS_MW, $ts );
3183 break;
3184 case 'localtimestamp':
3185 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
3186 break;
3187 case 'currentversion':
3188 $value = SpecialVersion::getVersion();
3189 break;
3190 case 'articlepath':
3191 return $wgArticlePath;
3192 case 'sitename':
3193 return $wgSitename;
3194 case 'server':
3195 return $wgServer;
3196 case 'servername':
3197 return $wgServerName;
3198 case 'scriptpath':
3199 return $wgScriptPath;
3200 case 'stylepath':
3201 return $wgStylePath;
3202 case 'directionmark':
3203 return $pageLang->getDirMark();
3204 case 'contentlanguage':
3205 global $wgLanguageCode;
3206 return $wgLanguageCode;
3207 case 'cascadingsources':
3208 $value = CoreParserFunctions::cascadingsources( $this );
3209 break;
3210 default:
3211 $ret = null;
3212 wfRunHooks(
3213 'ParserGetVariableValueSwitch',
3214 array( &$this, &$this->mVarCache, &$index, &$ret, &$frame )
3217 return $ret;
3220 if ( $index ) {
3221 $this->mVarCache[$index] = $value;
3224 return $value;
3228 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3230 * @private
3232 function initialiseVariables() {
3233 wfProfileIn( __METHOD__ );
3234 $variableIDs = MagicWord::getVariableIDs();
3235 $substIDs = MagicWord::getSubstIDs();
3237 $this->mVariables = new MagicWordArray( $variableIDs );
3238 $this->mSubstWords = new MagicWordArray( $substIDs );
3239 wfProfileOut( __METHOD__ );
3243 * Preprocess some wikitext and return the document tree.
3244 * This is the ghost of replace_variables().
3246 * @param string $text The text to parse
3247 * @param int $flags Bitwise combination of:
3248 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3249 * included. Default is to assume a direct page view.
3251 * The generated DOM tree must depend only on the input text and the flags.
3252 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3254 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3255 * change in the DOM tree for a given text, must be passed through the section identifier
3256 * in the section edit link and thus back to extractSections().
3258 * The output of this function is currently only cached in process memory, but a persistent
3259 * cache may be implemented at a later date which takes further advantage of these strict
3260 * dependency requirements.
3262 * @return PPNode
3264 function preprocessToDom( $text, $flags = 0 ) {
3265 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3266 return $dom;
3270 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3272 * @param string $s
3274 * @return array
3276 public static function splitWhitespace( $s ) {
3277 $ltrimmed = ltrim( $s );
3278 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3279 $trimmed = rtrim( $ltrimmed );
3280 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3281 if ( $diff > 0 ) {
3282 $w2 = substr( $ltrimmed, -$diff );
3283 } else {
3284 $w2 = '';
3286 return array( $w1, $trimmed, $w2 );
3290 * Replace magic variables, templates, and template arguments
3291 * with the appropriate text. Templates are substituted recursively,
3292 * taking care to avoid infinite loops.
3294 * Note that the substitution depends on value of $mOutputType:
3295 * self::OT_WIKI: only {{subst:}} templates
3296 * self::OT_PREPROCESS: templates but not extension tags
3297 * self::OT_HTML: all templates and extension tags
3299 * @param string $text The text to transform
3300 * @param bool|PPFrame $frame Object describing the arguments passed to the
3301 * template. Arguments may also be provided as an associative array, as
3302 * was the usual case before MW1.12. Providing arguments this way may be
3303 * useful for extensions wishing to perform variable replacement
3304 * explicitly.
3305 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3306 * double-brace expansion.
3307 * @return string
3309 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3310 # Is there any text? Also, Prevent too big inclusions!
3311 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3312 return $text;
3314 wfProfileIn( __METHOD__ );
3316 if ( $frame === false ) {
3317 $frame = $this->getPreprocessor()->newFrame();
3318 } elseif ( !( $frame instanceof PPFrame ) ) {
3319 wfDebug( __METHOD__ . " called using plain parameters instead of "
3320 . "a PPFrame instance. Creating custom frame.\n" );
3321 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3324 $dom = $this->preprocessToDom( $text );
3325 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3326 $text = $frame->expand( $dom, $flags );
3328 wfProfileOut( __METHOD__ );
3329 return $text;
3333 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3335 * @param array $args
3337 * @return array
3339 static function createAssocArgs( $args ) {
3340 $assocArgs = array();
3341 $index = 1;
3342 foreach ( $args as $arg ) {
3343 $eqpos = strpos( $arg, '=' );
3344 if ( $eqpos === false ) {
3345 $assocArgs[$index++] = $arg;
3346 } else {
3347 $name = trim( substr( $arg, 0, $eqpos ) );
3348 $value = trim( substr( $arg, $eqpos + 1 ) );
3349 if ( $value === false ) {
3350 $value = '';
3352 if ( $name !== false ) {
3353 $assocArgs[$name] = $value;
3358 return $assocArgs;
3362 * Warn the user when a parser limitation is reached
3363 * Will warn at most once the user per limitation type
3365 * @param string $limitationType Should be one of:
3366 * 'expensive-parserfunction' (corresponding messages:
3367 * 'expensive-parserfunction-warning',
3368 * 'expensive-parserfunction-category')
3369 * 'post-expand-template-argument' (corresponding messages:
3370 * 'post-expand-template-argument-warning',
3371 * 'post-expand-template-argument-category')
3372 * 'post-expand-template-inclusion' (corresponding messages:
3373 * 'post-expand-template-inclusion-warning',
3374 * 'post-expand-template-inclusion-category')
3375 * 'node-count-exceeded' (corresponding messages:
3376 * 'node-count-exceeded-warning',
3377 * 'node-count-exceeded-category')
3378 * 'expansion-depth-exceeded' (corresponding messages:
3379 * 'expansion-depth-exceeded-warning',
3380 * 'expansion-depth-exceeded-category')
3381 * @param string|int|null $current Current value
3382 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3383 * exceeded, provide the values (optional)
3385 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3386 # does no harm if $current and $max are present but are unnecessary for the message
3387 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3388 ->inLanguage( $this->mOptions->getUserLangObj() )->text();
3389 $this->mOutput->addWarning( $warning );
3390 $this->addTrackingCategory( "$limitationType-category" );
3394 * Return the text of a template, after recursively
3395 * replacing any variables or templates within the template.
3397 * @param array $piece The parts of the template
3398 * $piece['title']: the title, i.e. the part before the |
3399 * $piece['parts']: the parameter array
3400 * $piece['lineStart']: whether the brace was at the start of a line
3401 * @param PPFrame $frame The current frame, contains template arguments
3402 * @throws Exception
3403 * @return string The text of the template
3405 public function braceSubstitution( $piece, $frame ) {
3406 wfProfileIn( __METHOD__ );
3407 wfProfileIn( __METHOD__ . '-setup' );
3409 // Flags
3411 // $text has been filled
3412 $found = false;
3413 // wiki markup in $text should be escaped
3414 $nowiki = false;
3415 // $text is HTML, armour it against wikitext transformation
3416 $isHTML = false;
3417 // Force interwiki transclusion to be done in raw mode not rendered
3418 $forceRawInterwiki = false;
3419 // $text is a DOM node needing expansion in a child frame
3420 $isChildObj = false;
3421 // $text is a DOM node needing expansion in the current frame
3422 $isLocalObj = false;
3424 # Title object, where $text came from
3425 $title = false;
3427 # $part1 is the bit before the first |, and must contain only title characters.
3428 # Various prefixes will be stripped from it later.
3429 $titleWithSpaces = $frame->expand( $piece['title'] );
3430 $part1 = trim( $titleWithSpaces );
3431 $titleText = false;
3433 # Original title text preserved for various purposes
3434 $originalTitle = $part1;
3436 # $args is a list of argument nodes, starting from index 0, not including $part1
3437 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3438 # below won't work b/c this $args isn't an object
3439 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3440 wfProfileOut( __METHOD__ . '-setup' );
3442 $titleProfileIn = null; // profile templates
3444 # SUBST
3445 wfProfileIn( __METHOD__ . '-modifiers' );
3446 if ( !$found ) {
3448 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3450 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3451 # Decide whether to expand template or keep wikitext as-is.
3452 if ( $this->ot['wiki'] ) {
3453 if ( $substMatch === false ) {
3454 $literal = true; # literal when in PST with no prefix
3455 } else {
3456 $literal = false; # expand when in PST with subst: or safesubst:
3458 } else {
3459 if ( $substMatch == 'subst' ) {
3460 $literal = true; # literal when not in PST with plain subst:
3461 } else {
3462 $literal = false; # expand when not in PST with safesubst: or no prefix
3465 if ( $literal ) {
3466 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3467 $isLocalObj = true;
3468 $found = true;
3472 # Variables
3473 if ( !$found && $args->getLength() == 0 ) {
3474 $id = $this->mVariables->matchStartToEnd( $part1 );
3475 if ( $id !== false ) {
3476 $text = $this->getVariableValue( $id, $frame );
3477 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3478 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3480 $found = true;
3484 # MSG, MSGNW and RAW
3485 if ( !$found ) {
3486 # Check for MSGNW:
3487 $mwMsgnw = MagicWord::get( 'msgnw' );
3488 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3489 $nowiki = true;
3490 } else {
3491 # Remove obsolete MSG:
3492 $mwMsg = MagicWord::get( 'msg' );
3493 $mwMsg->matchStartAndRemove( $part1 );
3496 # Check for RAW:
3497 $mwRaw = MagicWord::get( 'raw' );
3498 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3499 $forceRawInterwiki = true;
3502 wfProfileOut( __METHOD__ . '-modifiers' );
3504 # Parser functions
3505 if ( !$found ) {
3506 wfProfileIn( __METHOD__ . '-pfunc' );
3508 $colonPos = strpos( $part1, ':' );
3509 if ( $colonPos !== false ) {
3510 $func = substr( $part1, 0, $colonPos );
3511 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3512 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3513 $funcArgs[] = $args->item( $i );
3515 try {
3516 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3517 } catch ( Exception $ex ) {
3518 wfProfileOut( __METHOD__ . '-pfunc' );
3519 wfProfileOut( __METHOD__ );
3520 throw $ex;
3523 # The interface for parser functions allows for extracting
3524 # flags into the local scope. Extract any forwarded flags
3525 # here.
3526 extract( $result );
3528 wfProfileOut( __METHOD__ . '-pfunc' );
3531 # Finish mangling title and then check for loops.
3532 # Set $title to a Title object and $titleText to the PDBK
3533 if ( !$found ) {
3534 $ns = NS_TEMPLATE;
3535 # Split the title into page and subpage
3536 $subpage = '';
3537 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3538 if ( $part1 !== $relative ) {
3539 $part1 = $relative;
3540 $ns = $this->mTitle->getNamespace();
3542 $title = Title::newFromText( $part1, $ns );
3543 if ( $title ) {
3544 $titleText = $title->getPrefixedText();
3545 # Check for language variants if the template is not found
3546 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3547 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3549 # Do recursion depth check
3550 $limit = $this->mOptions->getMaxTemplateDepth();
3551 if ( $frame->depth >= $limit ) {
3552 $found = true;
3553 $text = '<span class="error">'
3554 . wfMessage( 'parser-template-recursion-depth-warning' )
3555 ->numParams( $limit )->inContentLanguage()->text()
3556 . '</span>';
3561 # Load from database
3562 if ( !$found && $title ) {
3563 if ( !Profiler::instance()->isPersistent() ) {
3564 # Too many unique items can kill profiling DBs/collectors
3565 $titleProfileIn = __METHOD__ . "-title-" . $title->getPrefixedDBkey();
3566 wfProfileIn( $titleProfileIn ); // template in
3568 wfProfileIn( __METHOD__ . '-loadtpl' );
3569 if ( !$title->isExternal() ) {
3570 if ( $title->isSpecialPage()
3571 && $this->mOptions->getAllowSpecialInclusion()
3572 && $this->ot['html']
3574 // Pass the template arguments as URL parameters.
3575 // "uselang" will have no effect since the Language object
3576 // is forced to the one defined in ParserOptions.
3577 $pageArgs = array();
3578 $argsLength = $args->getLength();
3579 for ( $i = 0; $i < $argsLength; $i++ ) {
3580 $bits = $args->item( $i )->splitArg();
3581 if ( strval( $bits['index'] ) === '' ) {
3582 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3583 $value = trim( $frame->expand( $bits['value'] ) );
3584 $pageArgs[$name] = $value;
3588 // Create a new context to execute the special page
3589 $context = new RequestContext;
3590 $context->setTitle( $title );
3591 $context->setRequest( new FauxRequest( $pageArgs ) );
3592 $context->setUser( $this->getUser() );
3593 $context->setLanguage( $this->mOptions->getUserLangObj() );
3594 $ret = SpecialPageFactory::capturePath( $title, $context );
3595 if ( $ret ) {
3596 $text = $context->getOutput()->getHTML();
3597 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3598 $found = true;
3599 $isHTML = true;
3600 $this->disableCache();
3602 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3603 $found = false; # access denied
3604 wfDebug( __METHOD__ . ": template inclusion denied for " .
3605 $title->getPrefixedDBkey() . "\n" );
3606 } else {
3607 list( $text, $title ) = $this->getTemplateDom( $title );
3608 if ( $text !== false ) {
3609 $found = true;
3610 $isChildObj = true;
3614 # If the title is valid but undisplayable, make a link to it
3615 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3616 $text = "[[:$titleText]]";
3617 $found = true;
3619 } elseif ( $title->isTrans() ) {
3620 # Interwiki transclusion
3621 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3622 $text = $this->interwikiTransclude( $title, 'render' );
3623 $isHTML = true;
3624 } else {
3625 $text = $this->interwikiTransclude( $title, 'raw' );
3626 # Preprocess it like a template
3627 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3628 $isChildObj = true;
3630 $found = true;
3633 # Do infinite loop check
3634 # This has to be done after redirect resolution to avoid infinite loops via redirects
3635 if ( !$frame->loopCheck( $title ) ) {
3636 $found = true;
3637 $text = '<span class="error">'
3638 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3639 . '</span>';
3640 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3642 wfProfileOut( __METHOD__ . '-loadtpl' );
3645 # If we haven't found text to substitute by now, we're done
3646 # Recover the source wikitext and return it
3647 if ( !$found ) {
3648 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3649 if ( $titleProfileIn ) {
3650 wfProfileOut( $titleProfileIn ); // template out
3652 wfProfileOut( __METHOD__ );
3653 return array( 'object' => $text );
3656 # Expand DOM-style return values in a child frame
3657 if ( $isChildObj ) {
3658 # Clean up argument array
3659 $newFrame = $frame->newChild( $args, $title );
3661 if ( $nowiki ) {
3662 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3663 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3664 # Expansion is eligible for the empty-frame cache
3665 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3666 $text = $this->mTplExpandCache[$titleText];
3667 } else {
3668 $text = $newFrame->expand( $text );
3669 $this->mTplExpandCache[$titleText] = $text;
3671 } else {
3672 # Uncached expansion
3673 $text = $newFrame->expand( $text );
3676 if ( $isLocalObj && $nowiki ) {
3677 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3678 $isLocalObj = false;
3681 if ( $titleProfileIn ) {
3682 wfProfileOut( $titleProfileIn ); // template out
3685 # Replace raw HTML by a placeholder
3686 if ( $isHTML ) {
3687 $text = $this->insertStripItem( $text );
3688 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3689 # Escape nowiki-style return values
3690 $text = wfEscapeWikiText( $text );
3691 } elseif ( is_string( $text )
3692 && !$piece['lineStart']
3693 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3695 # Bug 529: if the template begins with a table or block-level
3696 # element, it should be treated as beginning a new line.
3697 # This behavior is somewhat controversial.
3698 $text = "\n" . $text;
3701 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3702 # Error, oversize inclusion
3703 if ( $titleText !== false ) {
3704 # Make a working, properly escaped link if possible (bug 23588)
3705 $text = "[[:$titleText]]";
3706 } else {
3707 # This will probably not be a working link, but at least it may
3708 # provide some hint of where the problem is
3709 preg_replace( '/^:/', '', $originalTitle );
3710 $text = "[[:$originalTitle]]";
3712 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3713 . 'post-expand include size too large -->' );
3714 $this->limitationWarn( 'post-expand-template-inclusion' );
3717 if ( $isLocalObj ) {
3718 $ret = array( 'object' => $text );
3719 } else {
3720 $ret = array( 'text' => $text );
3723 wfProfileOut( __METHOD__ );
3724 return $ret;
3728 * Call a parser function and return an array with text and flags.
3730 * The returned array will always contain a boolean 'found', indicating
3731 * whether the parser function was found or not. It may also contain the
3732 * following:
3733 * text: string|object, resulting wikitext or PP DOM object
3734 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3735 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3736 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3737 * nowiki: bool, wiki markup in $text should be escaped
3739 * @since 1.21
3740 * @param PPFrame $frame The current frame, contains template arguments
3741 * @param string $function Function name
3742 * @param array $args Arguments to the function
3743 * @throws MWException
3744 * @return array
3746 public function callParserFunction( $frame, $function, array $args = array() ) {
3747 global $wgContLang;
3749 wfProfileIn( __METHOD__ );
3751 # Case sensitive functions
3752 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3753 $function = $this->mFunctionSynonyms[1][$function];
3754 } else {
3755 # Case insensitive functions
3756 $function = $wgContLang->lc( $function );
3757 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3758 $function = $this->mFunctionSynonyms[0][$function];
3759 } else {
3760 wfProfileOut( __METHOD__ );
3761 return array( 'found' => false );
3765 wfProfileIn( __METHOD__ . '-pfunc-' . $function );
3766 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3768 # Workaround for PHP bug 35229 and similar
3769 if ( !is_callable( $callback ) ) {
3770 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3771 wfProfileOut( __METHOD__ );
3772 throw new MWException( "Tag hook for $function is not callable\n" );
3775 $allArgs = array( &$this );
3776 if ( $flags & SFH_OBJECT_ARGS ) {
3777 # Convert arguments to PPNodes and collect for appending to $allArgs
3778 $funcArgs = array();
3779 foreach ( $args as $k => $v ) {
3780 if ( $v instanceof PPNode || $k === 0 ) {
3781 $funcArgs[] = $v;
3782 } else {
3783 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
3787 # Add a frame parameter, and pass the arguments as an array
3788 $allArgs[] = $frame;
3789 $allArgs[] = $funcArgs;
3790 } else {
3791 # Convert arguments to plain text and append to $allArgs
3792 foreach ( $args as $k => $v ) {
3793 if ( $v instanceof PPNode ) {
3794 $allArgs[] = trim( $frame->expand( $v ) );
3795 } elseif ( is_int( $k ) && $k >= 0 ) {
3796 $allArgs[] = trim( $v );
3797 } else {
3798 $allArgs[] = trim( "$k=$v" );
3803 $result = call_user_func_array( $callback, $allArgs );
3805 # The interface for function hooks allows them to return a wikitext
3806 # string or an array containing the string and any flags. This mungs
3807 # things around to match what this method should return.
3808 if ( !is_array( $result ) ) {
3809 $result = array(
3810 'found' => true,
3811 'text' => $result,
3813 } else {
3814 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3815 $result['text'] = $result[0];
3817 unset( $result[0] );
3818 $result += array(
3819 'found' => true,
3823 $noparse = true;
3824 $preprocessFlags = 0;
3825 if ( isset( $result['noparse'] ) ) {
3826 $noparse = $result['noparse'];
3828 if ( isset( $result['preprocessFlags'] ) ) {
3829 $preprocessFlags = $result['preprocessFlags'];
3832 if ( !$noparse ) {
3833 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3834 $result['isChildObj'] = true;
3836 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3837 wfProfileOut( __METHOD__ );
3839 return $result;
3843 * Get the semi-parsed DOM representation of a template with a given title,
3844 * and its redirect destination title. Cached.
3846 * @param Title $title
3848 * @return array
3850 function getTemplateDom( $title ) {
3851 $cacheTitle = $title;
3852 $titleText = $title->getPrefixedDBkey();
3854 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3855 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3856 $title = Title::makeTitle( $ns, $dbk );
3857 $titleText = $title->getPrefixedDBkey();
3859 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3860 return array( $this->mTplDomCache[$titleText], $title );
3863 # Cache miss, go to the database
3864 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3866 if ( $text === false ) {
3867 $this->mTplDomCache[$titleText] = false;
3868 return array( false, $title );
3871 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3872 $this->mTplDomCache[$titleText] = $dom;
3874 if ( !$title->equals( $cacheTitle ) ) {
3875 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3876 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3879 return array( $dom, $title );
3883 * Fetch the unparsed text of a template and register a reference to it.
3884 * @param Title $title
3885 * @return array ( string or false, Title )
3887 function fetchTemplateAndTitle( $title ) {
3888 // Defaults to Parser::statelessFetchTemplate()
3889 $templateCb = $this->mOptions->getTemplateCallback();
3890 $stuff = call_user_func( $templateCb, $title, $this );
3891 $text = $stuff['text'];
3892 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3893 if ( isset( $stuff['deps'] ) ) {
3894 foreach ( $stuff['deps'] as $dep ) {
3895 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3896 if ( $dep['title']->equals( $this->getTitle() ) ) {
3897 // If we transclude ourselves, the final result
3898 // will change based on the new version of the page
3899 $this->mOutput->setFlag( 'vary-revision' );
3903 return array( $text, $finalTitle );
3907 * Fetch the unparsed text of a template and register a reference to it.
3908 * @param Title $title
3909 * @return string|bool
3911 function fetchTemplate( $title ) {
3912 $rv = $this->fetchTemplateAndTitle( $title );
3913 return $rv[0];
3917 * Static function to get a template
3918 * Can be overridden via ParserOptions::setTemplateCallback().
3920 * @param Title $title
3921 * @param bool|Parser $parser
3923 * @return array
3925 static function statelessFetchTemplate( $title, $parser = false ) {
3926 $text = $skip = false;
3927 $finalTitle = $title;
3928 $deps = array();
3930 # Loop to fetch the article, with up to 1 redirect
3931 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3932 # Give extensions a chance to select the revision instead
3933 $id = false; # Assume current
3934 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3935 array( $parser, $title, &$skip, &$id ) );
3937 if ( $skip ) {
3938 $text = false;
3939 $deps[] = array(
3940 'title' => $title,
3941 'page_id' => $title->getArticleID(),
3942 'rev_id' => null
3944 break;
3946 # Get the revision
3947 $rev = $id
3948 ? Revision::newFromId( $id )
3949 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
3950 $rev_id = $rev ? $rev->getId() : 0;
3951 # If there is no current revision, there is no page
3952 if ( $id === false && !$rev ) {
3953 $linkCache = LinkCache::singleton();
3954 $linkCache->addBadLinkObj( $title );
3957 $deps[] = array(
3958 'title' => $title,
3959 'page_id' => $title->getArticleID(),
3960 'rev_id' => $rev_id );
3961 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3962 # We fetched a rev from a different title; register it too...
3963 $deps[] = array(
3964 'title' => $rev->getTitle(),
3965 'page_id' => $rev->getPage(),
3966 'rev_id' => $rev_id );
3969 if ( $rev ) {
3970 $content = $rev->getContent();
3971 $text = $content ? $content->getWikitextForTransclusion() : null;
3973 if ( $text === false || $text === null ) {
3974 $text = false;
3975 break;
3977 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3978 global $wgContLang;
3979 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3980 if ( !$message->exists() ) {
3981 $text = false;
3982 break;
3984 $content = $message->content();
3985 $text = $message->plain();
3986 } else {
3987 break;
3989 if ( !$content ) {
3990 break;
3992 # Redirect?
3993 $finalTitle = $title;
3994 $title = $content->getRedirectTarget();
3996 return array(
3997 'text' => $text,
3998 'finalTitle' => $finalTitle,
3999 'deps' => $deps );
4003 * Fetch a file and its title and register a reference to it.
4004 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4005 * @param Title $title
4006 * @param array $options Array of options to RepoGroup::findFile
4007 * @return File|bool
4009 function fetchFile( $title, $options = array() ) {
4010 $res = $this->fetchFileAndTitle( $title, $options );
4011 return $res[0];
4015 * Fetch a file and its title and register a reference to it.
4016 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4017 * @param Title $title
4018 * @param array $options Array of options to RepoGroup::findFile
4019 * @return array ( File or false, Title of file )
4021 function fetchFileAndTitle( $title, $options = array() ) {
4022 $file = $this->fetchFileNoRegister( $title, $options );
4024 $time = $file ? $file->getTimestamp() : false;
4025 $sha1 = $file ? $file->getSha1() : false;
4026 # Register the file as a dependency...
4027 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
4028 if ( $file && !$title->equals( $file->getTitle() ) ) {
4029 # Update fetched file title
4030 $title = $file->getTitle();
4031 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
4033 return array( $file, $title );
4037 * Helper function for fetchFileAndTitle.
4039 * Also useful if you need to fetch a file but not use it yet,
4040 * for example to get the file's handler.
4042 * @param Title $title
4043 * @param array $options Array of options to RepoGroup::findFile
4044 * @return File|bool
4046 protected function fetchFileNoRegister( $title, $options = array() ) {
4047 if ( isset( $options['broken'] ) ) {
4048 $file = false; // broken thumbnail forced by hook
4049 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4050 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
4051 } else { // get by (name,timestamp)
4052 $file = wfFindFile( $title, $options );
4054 return $file;
4058 * Transclude an interwiki link.
4060 * @param Title $title
4061 * @param string $action
4063 * @return string
4065 function interwikiTransclude( $title, $action ) {
4066 global $wgEnableScaryTranscluding;
4068 if ( !$wgEnableScaryTranscluding ) {
4069 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4072 $url = $title->getFullURL( array( 'action' => $action ) );
4074 if ( strlen( $url ) > 255 ) {
4075 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4077 return $this->fetchScaryTemplateMaybeFromCache( $url );
4081 * @param string $url
4082 * @return mixed|string
4084 function fetchScaryTemplateMaybeFromCache( $url ) {
4085 global $wgTranscludeCacheExpiry;
4086 $dbr = wfGetDB( DB_SLAVE );
4087 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4088 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4089 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4090 if ( $obj ) {
4091 return $obj->tc_contents;
4094 $req = MWHttpRequest::factory( $url );
4095 $status = $req->execute(); // Status object
4096 if ( $status->isOK() ) {
4097 $text = $req->getContent();
4098 } elseif ( $req->getStatus() != 200 ) {
4099 // Though we failed to fetch the content, this status is useless.
4100 return wfMessage( 'scarytranscludefailed-httpstatus' )
4101 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4102 } else {
4103 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4106 $dbw = wfGetDB( DB_MASTER );
4107 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4108 'tc_url' => $url,
4109 'tc_time' => $dbw->timestamp( time() ),
4110 'tc_contents' => $text
4111 ) );
4112 return $text;
4116 * Triple brace replacement -- used for template arguments
4117 * @private
4119 * @param array $piece
4120 * @param PPFrame $frame
4122 * @return array
4124 function argSubstitution( $piece, $frame ) {
4125 wfProfileIn( __METHOD__ );
4127 $error = false;
4128 $parts = $piece['parts'];
4129 $nameWithSpaces = $frame->expand( $piece['title'] );
4130 $argName = trim( $nameWithSpaces );
4131 $object = false;
4132 $text = $frame->getArgument( $argName );
4133 if ( $text === false && $parts->getLength() > 0
4134 && ( $this->ot['html']
4135 || $this->ot['pre']
4136 || ( $this->ot['wiki'] && $frame->isTemplate() )
4139 # No match in frame, use the supplied default
4140 $object = $parts->item( 0 )->getChildren();
4142 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4143 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4144 $this->limitationWarn( 'post-expand-template-argument' );
4147 if ( $text === false && $object === false ) {
4148 # No match anywhere
4149 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4151 if ( $error !== false ) {
4152 $text .= $error;
4154 if ( $object !== false ) {
4155 $ret = array( 'object' => $object );
4156 } else {
4157 $ret = array( 'text' => $text );
4160 wfProfileOut( __METHOD__ );
4161 return $ret;
4165 * Return the text to be used for a given extension tag.
4166 * This is the ghost of strip().
4168 * @param array $params Associative array of parameters:
4169 * name PPNode for the tag name
4170 * attr PPNode for unparsed text where tag attributes are thought to be
4171 * attributes Optional associative array of parsed attributes
4172 * inner Contents of extension element
4173 * noClose Original text did not have a close tag
4174 * @param PPFrame $frame
4176 * @throws MWException
4177 * @return string
4179 function extensionSubstitution( $params, $frame ) {
4180 $name = $frame->expand( $params['name'] );
4181 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
4182 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
4183 $marker = "{$this->mUniqPrefix}-$name-"
4184 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
4186 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
4187 ( $this->ot['html'] || $this->ot['pre'] );
4188 if ( $isFunctionTag ) {
4189 $markerType = 'none';
4190 } else {
4191 $markerType = 'general';
4193 if ( $this->ot['html'] || $isFunctionTag ) {
4194 $name = strtolower( $name );
4195 $attributes = Sanitizer::decodeTagAttributes( $attrText );
4196 if ( isset( $params['attributes'] ) ) {
4197 $attributes = $attributes + $params['attributes'];
4200 if ( isset( $this->mTagHooks[$name] ) ) {
4201 # Workaround for PHP bug 35229 and similar
4202 if ( !is_callable( $this->mTagHooks[$name] ) ) {
4203 throw new MWException( "Tag hook for $name is not callable\n" );
4205 $output = call_user_func_array( $this->mTagHooks[$name],
4206 array( $content, $attributes, $this, $frame ) );
4207 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
4208 list( $callback, ) = $this->mFunctionTagHooks[$name];
4209 if ( !is_callable( $callback ) ) {
4210 throw new MWException( "Tag hook for $name is not callable\n" );
4213 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4214 } else {
4215 $output = '<span class="error">Invalid tag extension name: ' .
4216 htmlspecialchars( $name ) . '</span>';
4219 if ( is_array( $output ) ) {
4220 # Extract flags to local scope (to override $markerType)
4221 $flags = $output;
4222 $output = $flags[0];
4223 unset( $flags[0] );
4224 extract( $flags );
4226 } else {
4227 if ( is_null( $attrText ) ) {
4228 $attrText = '';
4230 if ( isset( $params['attributes'] ) ) {
4231 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4232 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4233 htmlspecialchars( $attrValue ) . '"';
4236 if ( $content === null ) {
4237 $output = "<$name$attrText/>";
4238 } else {
4239 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4240 $output = "<$name$attrText>$content$close";
4244 if ( $markerType === 'none' ) {
4245 return $output;
4246 } elseif ( $markerType === 'nowiki' ) {
4247 $this->mStripState->addNoWiki( $marker, $output );
4248 } elseif ( $markerType === 'general' ) {
4249 $this->mStripState->addGeneral( $marker, $output );
4250 } else {
4251 throw new MWException( __METHOD__ . ': invalid marker type' );
4253 return $marker;
4257 * Increment an include size counter
4259 * @param string $type The type of expansion
4260 * @param int $size The size of the text
4261 * @return bool False if this inclusion would take it over the maximum, true otherwise
4263 function incrementIncludeSize( $type, $size ) {
4264 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4265 return false;
4266 } else {
4267 $this->mIncludeSizes[$type] += $size;
4268 return true;
4273 * Increment the expensive function count
4275 * @return bool False if the limit has been exceeded
4277 function incrementExpensiveFunctionCount() {
4278 $this->mExpensiveFunctionCount++;
4279 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4283 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4284 * Fills $this->mDoubleUnderscores, returns the modified text
4286 * @param string $text
4288 * @return string
4290 function doDoubleUnderscore( $text ) {
4291 wfProfileIn( __METHOD__ );
4293 # The position of __TOC__ needs to be recorded
4294 $mw = MagicWord::get( 'toc' );
4295 if ( $mw->match( $text ) ) {
4296 $this->mShowToc = true;
4297 $this->mForceTocPosition = true;
4299 # Set a placeholder. At the end we'll fill it in with the TOC.
4300 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4302 # Only keep the first one.
4303 $text = $mw->replace( '', $text );
4306 # Now match and remove the rest of them
4307 $mwa = MagicWord::getDoubleUnderscoreArray();
4308 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4310 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4311 $this->mOutput->mNoGallery = true;
4313 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4314 $this->mShowToc = false;
4316 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4317 && $this->mTitle->getNamespace() == NS_CATEGORY
4319 $this->addTrackingCategory( 'hidden-category-category' );
4321 # (bug 8068) Allow control over whether robots index a page.
4323 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4324 # is not desirable, the last one on the page should win.
4325 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4326 $this->mOutput->setIndexPolicy( 'noindex' );
4327 $this->addTrackingCategory( 'noindex-category' );
4329 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4330 $this->mOutput->setIndexPolicy( 'index' );
4331 $this->addTrackingCategory( 'index-category' );
4334 # Cache all double underscores in the database
4335 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4336 $this->mOutput->setProperty( $key, '' );
4339 wfProfileOut( __METHOD__ );
4340 return $text;
4344 * Add a tracking category, getting the title from a system message,
4345 * or print a debug message if the title is invalid.
4347 * Please add any message that you use with this function to
4348 * $wgTrackingCategories. That way they will be listed on
4349 * Special:TrackingCategories.
4351 * @param string $msg Message key
4352 * @return bool Whether the addition was successful
4354 public function addTrackingCategory( $msg ) {
4355 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
4356 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
4357 return false;
4359 // Important to parse with correct title (bug 31469)
4360 $cat = wfMessage( $msg )
4361 ->title( $this->getTitle() )
4362 ->inContentLanguage()
4363 ->text();
4365 # Allow tracking categories to be disabled by setting them to "-"
4366 if ( $cat === '-' ) {
4367 return false;
4370 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
4371 if ( $containerCategory ) {
4372 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4373 return true;
4374 } else {
4375 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
4376 return false;
4381 * This function accomplishes several tasks:
4382 * 1) Auto-number headings if that option is enabled
4383 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4384 * 3) Add a Table of contents on the top for users who have enabled the option
4385 * 4) Auto-anchor headings
4387 * It loops through all headlines, collects the necessary data, then splits up the
4388 * string and re-inserts the newly formatted headlines.
4390 * @param string $text
4391 * @param string $origText Original, untouched wikitext
4392 * @param bool $isMain
4393 * @return mixed|string
4394 * @private
4396 function formatHeadings( $text, $origText, $isMain = true ) {
4397 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4399 # Inhibit editsection links if requested in the page
4400 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4401 $maybeShowEditLink = $showEditLink = false;
4402 } else {
4403 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4404 $showEditLink = $this->mOptions->getEditSection();
4406 if ( $showEditLink ) {
4407 $this->mOutput->setEditSectionTokens( true );
4410 # Get all headlines for numbering them and adding funky stuff like [edit]
4411 # links - this is for later, but we need the number of headlines right now
4412 $matches = array();
4413 $numMatches = preg_match_all(
4414 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4415 $text,
4416 $matches
4419 # if there are fewer than 4 headlines in the article, do not show TOC
4420 # unless it's been explicitly enabled.
4421 $enoughToc = $this->mShowToc &&
4422 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4424 # Allow user to stipulate that a page should have a "new section"
4425 # link added via __NEWSECTIONLINK__
4426 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4427 $this->mOutput->setNewSection( true );
4430 # Allow user to remove the "new section"
4431 # link via __NONEWSECTIONLINK__
4432 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4433 $this->mOutput->hideNewSection( true );
4436 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4437 # override above conditions and always show TOC above first header
4438 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4439 $this->mShowToc = true;
4440 $enoughToc = true;
4443 # headline counter
4444 $headlineCount = 0;
4445 $numVisible = 0;
4447 # Ugh .. the TOC should have neat indentation levels which can be
4448 # passed to the skin functions. These are determined here
4449 $toc = '';
4450 $full = '';
4451 $head = array();
4452 $sublevelCount = array();
4453 $levelCount = array();
4454 $level = 0;
4455 $prevlevel = 0;
4456 $toclevel = 0;
4457 $prevtoclevel = 0;
4458 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4459 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4460 $oldType = $this->mOutputType;
4461 $this->setOutputType( self::OT_WIKI );
4462 $frame = $this->getPreprocessor()->newFrame();
4463 $root = $this->preprocessToDom( $origText );
4464 $node = $root->getFirstChild();
4465 $byteOffset = 0;
4466 $tocraw = array();
4467 $refers = array();
4469 foreach ( $matches[3] as $headline ) {
4470 $isTemplate = false;
4471 $titleText = false;
4472 $sectionIndex = false;
4473 $numbering = '';
4474 $markerMatches = array();
4475 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4476 $serial = $markerMatches[1];
4477 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4478 $isTemplate = ( $titleText != $baseTitleText );
4479 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4482 if ( $toclevel ) {
4483 $prevlevel = $level;
4485 $level = $matches[1][$headlineCount];
4487 if ( $level > $prevlevel ) {
4488 # Increase TOC level
4489 $toclevel++;
4490 $sublevelCount[$toclevel] = 0;
4491 if ( $toclevel < $wgMaxTocLevel ) {
4492 $prevtoclevel = $toclevel;
4493 $toc .= Linker::tocIndent();
4494 $numVisible++;
4496 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4497 # Decrease TOC level, find level to jump to
4499 for ( $i = $toclevel; $i > 0; $i-- ) {
4500 if ( $levelCount[$i] == $level ) {
4501 # Found last matching level
4502 $toclevel = $i;
4503 break;
4504 } elseif ( $levelCount[$i] < $level ) {
4505 # Found first matching level below current level
4506 $toclevel = $i + 1;
4507 break;
4510 if ( $i == 0 ) {
4511 $toclevel = 1;
4513 if ( $toclevel < $wgMaxTocLevel ) {
4514 if ( $prevtoclevel < $wgMaxTocLevel ) {
4515 # Unindent only if the previous toc level was shown :p
4516 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4517 $prevtoclevel = $toclevel;
4518 } else {
4519 $toc .= Linker::tocLineEnd();
4522 } else {
4523 # No change in level, end TOC line
4524 if ( $toclevel < $wgMaxTocLevel ) {
4525 $toc .= Linker::tocLineEnd();
4529 $levelCount[$toclevel] = $level;
4531 # count number of headlines for each level
4532 $sublevelCount[$toclevel]++;
4533 $dot = 0;
4534 for ( $i = 1; $i <= $toclevel; $i++ ) {
4535 if ( !empty( $sublevelCount[$i] ) ) {
4536 if ( $dot ) {
4537 $numbering .= '.';
4539 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4540 $dot = 1;
4544 # The safe header is a version of the header text safe to use for links
4546 # Remove link placeholders by the link text.
4547 # <!--LINK number-->
4548 # turns into
4549 # link text with suffix
4550 # Do this before unstrip since link text can contain strip markers
4551 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4553 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4554 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4556 # Strip out HTML (first regex removes any tag not allowed)
4557 # Allowed tags are:
4558 # * <sup> and <sub> (bug 8393)
4559 # * <i> (bug 26375)
4560 # * <b> (r105284)
4561 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4563 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4564 # to allow setting directionality in toc items.
4565 $tocline = preg_replace(
4566 array(
4567 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4568 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4570 array( '', '<$1>' ),
4571 $safeHeadline
4573 $tocline = trim( $tocline );
4575 # For the anchor, strip out HTML-y stuff period
4576 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4577 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4579 # Save headline for section edit hint before it's escaped
4580 $headlineHint = $safeHeadline;
4582 if ( $wgExperimentalHtmlIds ) {
4583 # For reverse compatibility, provide an id that's
4584 # HTML4-compatible, like we used to.
4586 # It may be worth noting, academically, that it's possible for
4587 # the legacy anchor to conflict with a non-legacy headline
4588 # anchor on the page. In this case likely the "correct" thing
4589 # would be to either drop the legacy anchors or make sure
4590 # they're numbered first. However, this would require people
4591 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4592 # manually, so let's not bother worrying about it.
4593 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4594 array( 'noninitial', 'legacy' ) );
4595 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4597 if ( $legacyHeadline == $safeHeadline ) {
4598 # No reason to have both (in fact, we can't)
4599 $legacyHeadline = false;
4601 } else {
4602 $legacyHeadline = false;
4603 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4604 'noninitial' );
4607 # HTML names must be case-insensitively unique (bug 10721).
4608 # This does not apply to Unicode characters per
4609 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4610 # @todo FIXME: We may be changing them depending on the current locale.
4611 $arrayKey = strtolower( $safeHeadline );
4612 if ( $legacyHeadline === false ) {
4613 $legacyArrayKey = false;
4614 } else {
4615 $legacyArrayKey = strtolower( $legacyHeadline );
4618 # count how many in assoc. array so we can track dupes in anchors
4619 if ( isset( $refers[$arrayKey] ) ) {
4620 $refers[$arrayKey]++;
4621 } else {
4622 $refers[$arrayKey] = 1;
4624 if ( isset( $refers[$legacyArrayKey] ) ) {
4625 $refers[$legacyArrayKey]++;
4626 } else {
4627 $refers[$legacyArrayKey] = 1;
4630 # Don't number the heading if it is the only one (looks silly)
4631 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4632 # the two are different if the line contains a link
4633 $headline = Html::element(
4634 'span',
4635 array( 'class' => 'mw-headline-number' ),
4636 $numbering
4637 ) . ' ' . $headline;
4640 # Create the anchor for linking from the TOC to the section
4641 $anchor = $safeHeadline;
4642 $legacyAnchor = $legacyHeadline;
4643 if ( $refers[$arrayKey] > 1 ) {
4644 $anchor .= '_' . $refers[$arrayKey];
4646 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4647 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4649 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4650 $toc .= Linker::tocLine( $anchor, $tocline,
4651 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4654 # Add the section to the section tree
4655 # Find the DOM node for this header
4656 $noOffset = ( $isTemplate || $sectionIndex === false );
4657 while ( $node && !$noOffset ) {
4658 if ( $node->getName() === 'h' ) {
4659 $bits = $node->splitHeading();
4660 if ( $bits['i'] == $sectionIndex ) {
4661 break;
4664 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4665 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4666 $node = $node->getNextSibling();
4668 $tocraw[] = array(
4669 'toclevel' => $toclevel,
4670 'level' => $level,
4671 'line' => $tocline,
4672 'number' => $numbering,
4673 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4674 'fromtitle' => $titleText,
4675 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4676 'anchor' => $anchor,
4679 # give headline the correct <h#> tag
4680 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4681 // Output edit section links as markers with styles that can be customized by skins
4682 if ( $isTemplate ) {
4683 # Put a T flag in the section identifier, to indicate to extractSections()
4684 # that sections inside <includeonly> should be counted.
4685 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4686 } else {
4687 $editlinkArgs = array(
4688 $this->mTitle->getPrefixedText(),
4689 $sectionIndex,
4690 $headlineHint
4693 // We use a bit of pesudo-xml for editsection markers. The
4694 // language converter is run later on. Using a UNIQ style marker
4695 // leads to the converter screwing up the tokens when it
4696 // converts stuff. And trying to insert strip tags fails too. At
4697 // this point all real inputted tags have already been escaped,
4698 // so we don't have to worry about a user trying to input one of
4699 // these markers directly. We use a page and section attribute
4700 // to stop the language converter from converting these
4701 // important bits of data, but put the headline hint inside a
4702 // content block because the language converter is supposed to
4703 // be able to convert that piece of data.
4704 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4705 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4706 if ( isset( $editlinkArgs[2] ) ) {
4707 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4708 } else {
4709 $editlink .= '/>';
4711 } else {
4712 $editlink = '';
4714 $head[$headlineCount] = Linker::makeHeadline( $level,
4715 $matches['attrib'][$headlineCount], $anchor, $headline,
4716 $editlink, $legacyAnchor );
4718 $headlineCount++;
4721 $this->setOutputType( $oldType );
4723 # Never ever show TOC if no headers
4724 if ( $numVisible < 1 ) {
4725 $enoughToc = false;
4728 if ( $enoughToc ) {
4729 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4730 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4732 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4733 $this->mOutput->setTOCHTML( $toc );
4734 $toc = self::TOC_START . $toc . self::TOC_END;
4735 $this->mOutput->addModules( 'mediawiki.toc' );
4738 if ( $isMain ) {
4739 $this->mOutput->setSections( $tocraw );
4742 # split up and insert constructed headlines
4743 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4744 $i = 0;
4746 // build an array of document sections
4747 $sections = array();
4748 foreach ( $blocks as $block ) {
4749 // $head is zero-based, sections aren't.
4750 if ( empty( $head[$i - 1] ) ) {
4751 $sections[$i] = $block;
4752 } else {
4753 $sections[$i] = $head[$i - 1] . $block;
4757 * Send a hook, one per section.
4758 * The idea here is to be able to make section-level DIVs, but to do so in a
4759 * lower-impact, more correct way than r50769
4761 * $this : caller
4762 * $section : the section number
4763 * &$sectionContent : ref to the content of the section
4764 * $showEditLinks : boolean describing whether this section has an edit link
4766 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4768 $i++;
4771 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4772 // append the TOC at the beginning
4773 // Top anchor now in skin
4774 $sections[0] = $sections[0] . $toc . "\n";
4777 $full .= join( '', $sections );
4779 if ( $this->mForceTocPosition ) {
4780 return str_replace( '<!--MWTOC-->', $toc, $full );
4781 } else {
4782 return $full;
4787 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4788 * conversion, substitting signatures, {{subst:}} templates, etc.
4790 * @param string $text The text to transform
4791 * @param Title $title The Title object for the current article
4792 * @param User $user The User object describing the current user
4793 * @param ParserOptions $options Parsing options
4794 * @param bool $clearState Whether to clear the parser state first
4795 * @return string The altered wiki markup
4797 public function preSaveTransform( $text, Title $title, User $user,
4798 ParserOptions $options, $clearState = true
4800 if ( $clearState ) {
4801 $magicScopeVariable = $this->lock();
4803 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4804 $this->setUser( $user );
4806 $pairs = array(
4807 "\r\n" => "\n",
4809 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4810 if ( $options->getPreSaveTransform() ) {
4811 $text = $this->pstPass2( $text, $user );
4813 $text = $this->mStripState->unstripBoth( $text );
4815 $this->setUser( null ); #Reset
4817 return $text;
4821 * Pre-save transform helper function
4823 * @param string $text
4824 * @param User $user
4826 * @return string
4828 private function pstPass2( $text, $user ) {
4829 global $wgContLang;
4831 # Note: This is the timestamp saved as hardcoded wikitext to
4832 # the database, we use $wgContLang here in order to give
4833 # everyone the same signature and use the default one rather
4834 # than the one selected in each user's preferences.
4835 # (see also bug 12815)
4836 $ts = $this->mOptions->getTimestamp();
4837 $timestamp = MWTimestamp::getLocalInstance( $ts );
4838 $ts = $timestamp->format( 'YmdHis' );
4839 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4841 # Allow translation of timezones through wiki. format() can return
4842 # whatever crap the system uses, localised or not, so we cannot
4843 # ship premade translations.
4844 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4845 $msg = wfMessage( $key )->inContentLanguage();
4846 if ( $msg->exists() ) {
4847 $tzMsg = $msg->text();
4850 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4852 # Variable replacement
4853 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4854 $text = $this->replaceVariables( $text );
4856 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4857 # which may corrupt this parser instance via its wfMessage()->text() call-
4859 # Signatures
4860 $sigText = $this->getUserSig( $user );
4861 $text = strtr( $text, array(
4862 '~~~~~' => $d,
4863 '~~~~' => "$sigText $d",
4864 '~~~' => $sigText
4865 ) );
4867 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4868 $tc = '[' . Title::legalChars() . ']';
4869 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4871 // [[ns:page (context)|]]
4872 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4873 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4874 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4875 // [[ns:page (context), context|]] (using either single or double-width comma)
4876 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4877 // [[|page]] (reverse pipe trick: add context from page title)
4878 $p2 = "/\[\[\\|($tc+)]]/";
4880 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4881 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4882 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4883 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4885 $t = $this->mTitle->getText();
4886 $m = array();
4887 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4888 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4889 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4890 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4891 } else {
4892 # if there's no context, don't bother duplicating the title
4893 $text = preg_replace( $p2, '[[\\1]]', $text );
4896 # Trim trailing whitespace
4897 $text = rtrim( $text );
4899 return $text;
4903 * Fetch the user's signature text, if any, and normalize to
4904 * validated, ready-to-insert wikitext.
4905 * If you have pre-fetched the nickname or the fancySig option, you can
4906 * specify them here to save a database query.
4907 * Do not reuse this parser instance after calling getUserSig(),
4908 * as it may have changed if it's the $wgParser.
4910 * @param User $user
4911 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4912 * @param bool|null $fancySig whether the nicknname is the complete signature
4913 * or null to use default value
4914 * @return string
4916 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4917 global $wgMaxSigChars;
4919 $username = $user->getName();
4921 # If not given, retrieve from the user object.
4922 if ( $nickname === false ) {
4923 $nickname = $user->getOption( 'nickname' );
4926 if ( is_null( $fancySig ) ) {
4927 $fancySig = $user->getBoolOption( 'fancysig' );
4930 $nickname = $nickname == null ? $username : $nickname;
4932 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4933 $nickname = $username;
4934 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4935 } elseif ( $fancySig !== false ) {
4936 # Sig. might contain markup; validate this
4937 if ( $this->validateSig( $nickname ) !== false ) {
4938 # Validated; clean up (if needed) and return it
4939 return $this->cleanSig( $nickname, true );
4940 } else {
4941 # Failed to validate; fall back to the default
4942 $nickname = $username;
4943 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4947 # Make sure nickname doesnt get a sig in a sig
4948 $nickname = self::cleanSigInSig( $nickname );
4950 # If we're still here, make it a link to the user page
4951 $userText = wfEscapeWikiText( $username );
4952 $nickText = wfEscapeWikiText( $nickname );
4953 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4955 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4956 ->title( $this->getTitle() )->text();
4960 * Check that the user's signature contains no bad XML
4962 * @param string $text
4963 * @return string|bool An expanded string, or false if invalid.
4965 function validateSig( $text ) {
4966 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4970 * Clean up signature text
4972 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4973 * 2) Substitute all transclusions
4975 * @param string $text
4976 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4977 * @return string Signature text
4979 public function cleanSig( $text, $parsing = false ) {
4980 if ( !$parsing ) {
4981 global $wgTitle;
4982 $magicScopeVariable = $this->lock();
4983 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4986 # Option to disable this feature
4987 if ( !$this->mOptions->getCleanSignatures() ) {
4988 return $text;
4991 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4992 # => Move this logic to braceSubstitution()
4993 $substWord = MagicWord::get( 'subst' );
4994 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4995 $substText = '{{' . $substWord->getSynonym( 0 );
4997 $text = preg_replace( $substRegex, $substText, $text );
4998 $text = self::cleanSigInSig( $text );
4999 $dom = $this->preprocessToDom( $text );
5000 $frame = $this->getPreprocessor()->newFrame();
5001 $text = $frame->expand( $dom );
5003 if ( !$parsing ) {
5004 $text = $this->mStripState->unstripBoth( $text );
5007 return $text;
5011 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5013 * @param string $text
5014 * @return string Signature text with /~{3,5}/ removed
5016 public static function cleanSigInSig( $text ) {
5017 $text = preg_replace( '/~{3,5}/', '', $text );
5018 return $text;
5022 * Set up some variables which are usually set up in parse()
5023 * so that an external function can call some class members with confidence
5025 * @param Title|null $title
5026 * @param ParserOptions $options
5027 * @param int $outputType
5028 * @param bool $clearState
5030 public function startExternalParse( Title $title = null, ParserOptions $options,
5031 $outputType, $clearState = true
5033 $this->startParse( $title, $options, $outputType, $clearState );
5037 * @param Title|null $title
5038 * @param ParserOptions $options
5039 * @param int $outputType
5040 * @param bool $clearState
5042 private function startParse( Title $title = null, ParserOptions $options,
5043 $outputType, $clearState = true
5045 $this->setTitle( $title );
5046 $this->mOptions = $options;
5047 $this->setOutputType( $outputType );
5048 if ( $clearState ) {
5049 $this->clearState();
5054 * Wrapper for preprocess()
5056 * @param string $text The text to preprocess
5057 * @param ParserOptions $options Options
5058 * @param Title|null $title Title object or null to use $wgTitle
5059 * @return string
5061 public function transformMsg( $text, $options, $title = null ) {
5062 static $executing = false;
5064 # Guard against infinite recursion
5065 if ( $executing ) {
5066 return $text;
5068 $executing = true;
5070 wfProfileIn( __METHOD__ );
5071 if ( !$title ) {
5072 global $wgTitle;
5073 $title = $wgTitle;
5076 $text = $this->preprocess( $text, $title, $options );
5078 $executing = false;
5079 wfProfileOut( __METHOD__ );
5080 return $text;
5084 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5085 * The callback should have the following form:
5086 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5088 * Transform and return $text. Use $parser for any required context, e.g. use
5089 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5091 * Hooks may return extended information by returning an array, of which the
5092 * first numbered element (index 0) must be the return string, and all other
5093 * entries are extracted into local variables within an internal function
5094 * in the Parser class.
5096 * This interface (introduced r61913) appears to be undocumented, but
5097 * 'markerName' is used by some core tag hooks to override which strip
5098 * array their results are placed in. **Use great caution if attempting
5099 * this interface, as it is not documented and injudicious use could smash
5100 * private variables.**
5102 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5103 * @param mixed $callback The callback function (and object) to use for the tag
5104 * @throws MWException
5105 * @return mixed|null The old value of the mTagHooks array associated with the hook
5107 public function setHook( $tag, $callback ) {
5108 $tag = strtolower( $tag );
5109 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5110 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5112 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
5113 $this->mTagHooks[$tag] = $callback;
5114 if ( !in_array( $tag, $this->mStripList ) ) {
5115 $this->mStripList[] = $tag;
5118 return $oldVal;
5122 * As setHook(), but letting the contents be parsed.
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.
5127 * This is probably obsoleted by things dealing with parser frames?
5128 * The only extension currently using it is geoserver.
5130 * @since 1.10
5131 * @todo better document or deprecate this
5133 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5134 * @param mixed $callback The callback function (and object) to use for the tag
5135 * @throws MWException
5136 * @return mixed|null The old value of the mTagHooks array associated with the hook
5138 function setTransparentTagHook( $tag, $callback ) {
5139 $tag = strtolower( $tag );
5140 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5141 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5143 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
5144 $this->mTransparentTagHooks[$tag] = $callback;
5146 return $oldVal;
5150 * Remove all tag hooks
5152 function clearTagHooks() {
5153 $this->mTagHooks = array();
5154 $this->mFunctionTagHooks = array();
5155 $this->mStripList = $this->mDefaultStripList;
5159 * Create a function, e.g. {{sum:1|2|3}}
5160 * The callback function should have the form:
5161 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5163 * Or with SFH_OBJECT_ARGS:
5164 * function myParserFunction( $parser, $frame, $args ) { ... }
5166 * The callback may either return the text result of the function, or an array with the text
5167 * in element 0, and a number of flags in the other elements. The names of the flags are
5168 * specified in the keys. Valid flags are:
5169 * found The text returned is valid, stop processing the template. This
5170 * is on by default.
5171 * nowiki Wiki markup in the return value should be escaped
5172 * isHTML The returned text is HTML, armour it against wikitext transformation
5174 * @param string $id The magic word ID
5175 * @param mixed $callback The callback function (and object) to use
5176 * @param int $flags A combination of the following flags:
5177 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5179 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5180 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5181 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5182 * the arguments, and to control the way they are expanded.
5184 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5185 * arguments, for instance:
5186 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5188 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5189 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5190 * working if/when this is changed.
5192 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5193 * expansion.
5195 * Please read the documentation in includes/parser/Preprocessor.php for more information
5196 * about the methods available in PPFrame and PPNode.
5198 * @throws MWException
5199 * @return string|callable The old callback function for this name, if any
5201 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5202 global $wgContLang;
5204 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
5205 $this->mFunctionHooks[$id] = array( $callback, $flags );
5207 # Add to function cache
5208 $mw = MagicWord::get( $id );
5209 if ( !$mw ) {
5210 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
5213 $synonyms = $mw->getSynonyms();
5214 $sensitive = intval( $mw->isCaseSensitive() );
5216 foreach ( $synonyms as $syn ) {
5217 # Case
5218 if ( !$sensitive ) {
5219 $syn = $wgContLang->lc( $syn );
5221 # Add leading hash
5222 if ( !( $flags & SFH_NO_HASH ) ) {
5223 $syn = '#' . $syn;
5225 # Remove trailing colon
5226 if ( substr( $syn, -1, 1 ) === ':' ) {
5227 $syn = substr( $syn, 0, -1 );
5229 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
5231 return $oldVal;
5235 * Get all registered function hook identifiers
5237 * @return array
5239 function getFunctionHooks() {
5240 return array_keys( $this->mFunctionHooks );
5244 * Create a tag function, e.g. "<test>some stuff</test>".
5245 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5246 * Unlike parser functions, their content is not preprocessed.
5247 * @param string $tag
5248 * @param callable $callback
5249 * @param int $flags
5250 * @throws MWException
5251 * @return null
5253 function setFunctionTagHook( $tag, $callback, $flags ) {
5254 $tag = strtolower( $tag );
5255 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5256 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5258 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
5259 $this->mFunctionTagHooks[$tag] : null;
5260 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
5262 if ( !in_array( $tag, $this->mStripList ) ) {
5263 $this->mStripList[] = $tag;
5266 return $old;
5270 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5271 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5272 * Placeholders created in Skin::makeLinkObj()
5274 * @param string $text
5275 * @param int $options
5277 * @return array Array of link CSS classes, indexed by PDBK.
5279 function replaceLinkHolders( &$text, $options = 0 ) {
5280 return $this->mLinkHolders->replace( $text );
5284 * Replace "<!--LINK-->" link placeholders with plain text of links
5285 * (not HTML-formatted).
5287 * @param string $text
5288 * @return string
5290 function replaceLinkHoldersText( $text ) {
5291 return $this->mLinkHolders->replaceText( $text );
5295 * Renders an image gallery from a text with one line per image.
5296 * text labels may be given by using |-style alternative text. E.g.
5297 * Image:one.jpg|The number "1"
5298 * Image:tree.jpg|A tree
5299 * given as text will return the HTML of a gallery with two images,
5300 * labeled 'The number "1"' and
5301 * 'A tree'.
5303 * @param string $text
5304 * @param array $params
5305 * @return string HTML
5307 function renderImageGallery( $text, $params ) {
5308 wfProfileIn( __METHOD__ );
5310 $mode = false;
5311 if ( isset( $params['mode'] ) ) {
5312 $mode = $params['mode'];
5315 try {
5316 $ig = ImageGalleryBase::factory( $mode );
5317 } catch ( MWException $e ) {
5318 // If invalid type set, fallback to default.
5319 $ig = ImageGalleryBase::factory( false );
5322 $ig->setContextTitle( $this->mTitle );
5323 $ig->setShowBytes( false );
5324 $ig->setShowFilename( false );
5325 $ig->setParser( $this );
5326 $ig->setHideBadImages();
5327 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
5329 if ( isset( $params['showfilename'] ) ) {
5330 $ig->setShowFilename( true );
5331 } else {
5332 $ig->setShowFilename( false );
5334 if ( isset( $params['caption'] ) ) {
5335 $caption = $params['caption'];
5336 $caption = htmlspecialchars( $caption );
5337 $caption = $this->replaceInternalLinks( $caption );
5338 $ig->setCaptionHtml( $caption );
5340 if ( isset( $params['perrow'] ) ) {
5341 $ig->setPerRow( $params['perrow'] );
5343 if ( isset( $params['widths'] ) ) {
5344 $ig->setWidths( $params['widths'] );
5346 if ( isset( $params['heights'] ) ) {
5347 $ig->setHeights( $params['heights'] );
5349 $ig->setAdditionalOptions( $params );
5351 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5353 $lines = StringUtils::explode( "\n", $text );
5354 foreach ( $lines as $line ) {
5355 # match lines like these:
5356 # Image:someimage.jpg|This is some image
5357 $matches = array();
5358 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5359 # Skip empty lines
5360 if ( count( $matches ) == 0 ) {
5361 continue;
5364 if ( strpos( $matches[0], '%' ) !== false ) {
5365 $matches[1] = rawurldecode( $matches[1] );
5367 $title = Title::newFromText( $matches[1], NS_FILE );
5368 if ( is_null( $title ) ) {
5369 # Bogus title. Ignore these so we don't bomb out later.
5370 continue;
5373 # We need to get what handler the file uses, to figure out parameters.
5374 # Note, a hook can overide the file name, and chose an entirely different
5375 # file (which potentially could be of a different type and have different handler).
5376 $options = array();
5377 $descQuery = false;
5378 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5379 array( $this, $title, &$options, &$descQuery ) );
5380 # Don't register it now, as ImageGallery does that later.
5381 $file = $this->fetchFileNoRegister( $title, $options );
5382 $handler = $file ? $file->getHandler() : false;
5384 wfProfileIn( __METHOD__ . '-getMagicWord' );
5385 $paramMap = array(
5386 'img_alt' => 'gallery-internal-alt',
5387 'img_link' => 'gallery-internal-link',
5389 if ( $handler ) {
5390 $paramMap = $paramMap + $handler->getParamMap();
5391 // We don't want people to specify per-image widths.
5392 // Additionally the width parameter would need special casing anyhow.
5393 unset( $paramMap['img_width'] );
5396 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5397 wfProfileOut( __METHOD__ . '-getMagicWord' );
5399 $label = '';
5400 $alt = '';
5401 $link = '';
5402 $handlerOptions = array();
5403 if ( isset( $matches[3] ) ) {
5404 // look for an |alt= definition while trying not to break existing
5405 // captions with multiple pipes (|) in it, until a more sensible grammar
5406 // is defined for images in galleries
5408 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5409 // splitting on '|' is a bit odd, and different from makeImage.
5410 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5411 $parameterMatches = StringUtils::explode( '|', $matches[3] );
5413 foreach ( $parameterMatches as $parameterMatch ) {
5414 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5415 if ( $magicName ) {
5416 $paramName = $paramMap[$magicName];
5418 switch ( $paramName ) {
5419 case 'gallery-internal-alt':
5420 $alt = $this->stripAltText( $match, false );
5421 break;
5422 case 'gallery-internal-link':
5423 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5424 $chars = self::EXT_LINK_URL_CLASS;
5425 $prots = $this->mUrlProtocols;
5426 //check to see if link matches an absolute url, if not then it must be a wiki link.
5427 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5428 $link = $linkValue;
5429 } else {
5430 $localLinkTitle = Title::newFromText( $linkValue );
5431 if ( $localLinkTitle !== null ) {
5432 $link = $localLinkTitle->getLocalURL();
5435 break;
5436 default:
5437 // Must be a handler specific parameter.
5438 if ( $handler->validateParam( $paramName, $match ) ) {
5439 $handlerOptions[$paramName] = $match;
5440 } else {
5441 // Guess not. Append it to the caption.
5442 wfDebug( "$parameterMatch failed parameter validation\n" );
5443 $label .= '|' . $parameterMatch;
5447 } else {
5448 // concatenate all other pipes
5449 $label .= '|' . $parameterMatch;
5452 // remove the first pipe
5453 $label = substr( $label, 1 );
5456 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5458 $html = $ig->toHTML();
5459 wfProfileOut( __METHOD__ );
5460 return $html;
5464 * @param string $handler
5465 * @return array
5467 function getImageParams( $handler ) {
5468 if ( $handler ) {
5469 $handlerClass = get_class( $handler );
5470 } else {
5471 $handlerClass = '';
5473 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5474 # Initialise static lists
5475 static $internalParamNames = array(
5476 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5477 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5478 'bottom', 'text-bottom' ),
5479 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5480 'upright', 'border', 'link', 'alt', 'class' ),
5482 static $internalParamMap;
5483 if ( !$internalParamMap ) {
5484 $internalParamMap = array();
5485 foreach ( $internalParamNames as $type => $names ) {
5486 foreach ( $names as $name ) {
5487 $magicName = str_replace( '-', '_', "img_$name" );
5488 $internalParamMap[$magicName] = array( $type, $name );
5493 # Add handler params
5494 $paramMap = $internalParamMap;
5495 if ( $handler ) {
5496 $handlerParamMap = $handler->getParamMap();
5497 foreach ( $handlerParamMap as $magic => $paramName ) {
5498 $paramMap[$magic] = array( 'handler', $paramName );
5501 $this->mImageParams[$handlerClass] = $paramMap;
5502 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5504 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5508 * Parse image options text and use it to make an image
5510 * @param Title $title
5511 * @param string $options
5512 * @param LinkHolderArray|bool $holders
5513 * @return string HTML
5515 function makeImage( $title, $options, $holders = false ) {
5516 # Check if the options text is of the form "options|alt text"
5517 # Options are:
5518 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5519 # * left no resizing, just left align. label is used for alt= only
5520 # * right same, but right aligned
5521 # * none same, but not aligned
5522 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5523 # * center center the image
5524 # * frame Keep original image size, no magnify-button.
5525 # * framed Same as "frame"
5526 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5527 # * upright reduce width for upright images, rounded to full __0 px
5528 # * border draw a 1px border around the image
5529 # * alt Text for HTML alt attribute (defaults to empty)
5530 # * class Set a class for img node
5531 # * link Set the target of the image link. Can be external, interwiki, or local
5532 # vertical-align values (no % or length right now):
5533 # * baseline
5534 # * sub
5535 # * super
5536 # * top
5537 # * text-top
5538 # * middle
5539 # * bottom
5540 # * text-bottom
5542 $parts = StringUtils::explode( "|", $options );
5544 # Give extensions a chance to select the file revision for us
5545 $options = array();
5546 $descQuery = false;
5547 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5548 array( $this, $title, &$options, &$descQuery ) );
5549 # Fetch and register the file (file title may be different via hooks)
5550 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5552 # Get parameter map
5553 $handler = $file ? $file->getHandler() : false;
5555 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5557 if ( !$file ) {
5558 $this->addTrackingCategory( 'broken-file-category' );
5561 # Process the input parameters
5562 $caption = '';
5563 $params = array( 'frame' => array(), 'handler' => array(),
5564 'horizAlign' => array(), 'vertAlign' => array() );
5565 $seenformat = false;
5566 foreach ( $parts as $part ) {
5567 $part = trim( $part );
5568 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5569 $validated = false;
5570 if ( isset( $paramMap[$magicName] ) ) {
5571 list( $type, $paramName ) = $paramMap[$magicName];
5573 # Special case; width and height come in one variable together
5574 if ( $type === 'handler' && $paramName === 'width' ) {
5575 $parsedWidthParam = $this->parseWidthParam( $value );
5576 if ( isset( $parsedWidthParam['width'] ) ) {
5577 $width = $parsedWidthParam['width'];
5578 if ( $handler->validateParam( 'width', $width ) ) {
5579 $params[$type]['width'] = $width;
5580 $validated = true;
5583 if ( isset( $parsedWidthParam['height'] ) ) {
5584 $height = $parsedWidthParam['height'];
5585 if ( $handler->validateParam( 'height', $height ) ) {
5586 $params[$type]['height'] = $height;
5587 $validated = true;
5590 # else no validation -- bug 13436
5591 } else {
5592 if ( $type === 'handler' ) {
5593 # Validate handler parameter
5594 $validated = $handler->validateParam( $paramName, $value );
5595 } else {
5596 # Validate internal parameters
5597 switch ( $paramName ) {
5598 case 'manualthumb':
5599 case 'alt':
5600 case 'class':
5601 # @todo FIXME: Possibly check validity here for
5602 # manualthumb? downstream behavior seems odd with
5603 # missing manual thumbs.
5604 $validated = true;
5605 $value = $this->stripAltText( $value, $holders );
5606 break;
5607 case 'link':
5608 $chars = self::EXT_LINK_URL_CLASS;
5609 $prots = $this->mUrlProtocols;
5610 if ( $value === '' ) {
5611 $paramName = 'no-link';
5612 $value = true;
5613 $validated = true;
5614 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5615 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5616 $paramName = 'link-url';
5617 $this->mOutput->addExternalLink( $value );
5618 if ( $this->mOptions->getExternalLinkTarget() ) {
5619 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5621 $validated = true;
5623 } else {
5624 $linkTitle = Title::newFromText( $value );
5625 if ( $linkTitle ) {
5626 $paramName = 'link-title';
5627 $value = $linkTitle;
5628 $this->mOutput->addLink( $linkTitle );
5629 $validated = true;
5632 break;
5633 case 'frameless':
5634 case 'framed':
5635 case 'thumbnail':
5636 // use first appearing option, discard others.
5637 $validated = ! $seenformat;
5638 $seenformat = true;
5639 break;
5640 default:
5641 # Most other things appear to be empty or numeric...
5642 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5646 if ( $validated ) {
5647 $params[$type][$paramName] = $value;
5651 if ( !$validated ) {
5652 $caption = $part;
5656 # Process alignment parameters
5657 if ( $params['horizAlign'] ) {
5658 $params['frame']['align'] = key( $params['horizAlign'] );
5660 if ( $params['vertAlign'] ) {
5661 $params['frame']['valign'] = key( $params['vertAlign'] );
5664 $params['frame']['caption'] = $caption;
5666 # Will the image be presented in a frame, with the caption below?
5667 $imageIsFramed = isset( $params['frame']['frame'] )
5668 || isset( $params['frame']['framed'] )
5669 || isset( $params['frame']['thumbnail'] )
5670 || isset( $params['frame']['manualthumb'] );
5672 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5673 # came to also set the caption, ordinary text after the image -- which
5674 # makes no sense, because that just repeats the text multiple times in
5675 # screen readers. It *also* came to set the title attribute.
5677 # Now that we have an alt attribute, we should not set the alt text to
5678 # equal the caption: that's worse than useless, it just repeats the
5679 # text. This is the framed/thumbnail case. If there's no caption, we
5680 # use the unnamed parameter for alt text as well, just for the time be-
5681 # ing, if the unnamed param is set and the alt param is not.
5683 # For the future, we need to figure out if we want to tweak this more,
5684 # e.g., introducing a title= parameter for the title; ignoring the un-
5685 # named parameter entirely for images without a caption; adding an ex-
5686 # plicit caption= parameter and preserving the old magic unnamed para-
5687 # meter for BC; ...
5688 if ( $imageIsFramed ) { # Framed image
5689 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5690 # No caption or alt text, add the filename as the alt text so
5691 # that screen readers at least get some description of the image
5692 $params['frame']['alt'] = $title->getText();
5694 # Do not set $params['frame']['title'] because tooltips don't make sense
5695 # for framed images
5696 } else { # Inline image
5697 if ( !isset( $params['frame']['alt'] ) ) {
5698 # No alt text, use the "caption" for the alt text
5699 if ( $caption !== '' ) {
5700 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5701 } else {
5702 # No caption, fall back to using the filename for the
5703 # alt text
5704 $params['frame']['alt'] = $title->getText();
5707 # Use the "caption" for the tooltip text
5708 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5711 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5713 # Linker does the rest
5714 $time = isset( $options['time'] ) ? $options['time'] : false;
5715 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5716 $time, $descQuery, $this->mOptions->getThumbSize() );
5718 # Give the handler a chance to modify the parser object
5719 if ( $handler ) {
5720 $handler->parserTransformHook( $this, $file );
5723 return $ret;
5727 * @param string $caption
5728 * @param LinkHolderArray|bool $holders
5729 * @return mixed|string
5731 protected function stripAltText( $caption, $holders ) {
5732 # Strip bad stuff out of the title (tooltip). We can't just use
5733 # replaceLinkHoldersText() here, because if this function is called
5734 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5735 if ( $holders ) {
5736 $tooltip = $holders->replaceText( $caption );
5737 } else {
5738 $tooltip = $this->replaceLinkHoldersText( $caption );
5741 # make sure there are no placeholders in thumbnail attributes
5742 # that are later expanded to html- so expand them now and
5743 # remove the tags
5744 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5745 $tooltip = Sanitizer::stripAllTags( $tooltip );
5747 return $tooltip;
5751 * Set a flag in the output object indicating that the content is dynamic and
5752 * shouldn't be cached.
5754 function disableCache() {
5755 wfDebug( "Parser output marked as uncacheable.\n" );
5756 if ( !$this->mOutput ) {
5757 throw new MWException( __METHOD__ .
5758 " can only be called when actually parsing something" );
5760 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5761 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5765 * Callback from the Sanitizer for expanding items found in HTML attribute
5766 * values, so they can be safely tested and escaped.
5768 * @param string $text
5769 * @param bool|PPFrame $frame
5770 * @return string
5772 function attributeStripCallback( &$text, $frame = false ) {
5773 $text = $this->replaceVariables( $text, $frame );
5774 $text = $this->mStripState->unstripBoth( $text );
5775 return $text;
5779 * Accessor
5781 * @return array
5783 function getTags() {
5784 return array_merge(
5785 array_keys( $this->mTransparentTagHooks ),
5786 array_keys( $this->mTagHooks ),
5787 array_keys( $this->mFunctionTagHooks )
5792 * Replace transparent tags in $text with the values given by the callbacks.
5794 * Transparent tag hooks are like regular XML-style tag hooks, except they
5795 * operate late in the transformation sequence, on HTML instead of wikitext.
5797 * @param string $text
5799 * @return string
5801 function replaceTransparentTags( $text ) {
5802 $matches = array();
5803 $elements = array_keys( $this->mTransparentTagHooks );
5804 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5805 $replacements = array();
5807 foreach ( $matches as $marker => $data ) {
5808 list( $element, $content, $params, $tag ) = $data;
5809 $tagName = strtolower( $element );
5810 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5811 $output = call_user_func_array(
5812 $this->mTransparentTagHooks[$tagName],
5813 array( $content, $params, $this )
5815 } else {
5816 $output = $tag;
5818 $replacements[$marker] = $output;
5820 return strtr( $text, $replacements );
5824 * Break wikitext input into sections, and either pull or replace
5825 * some particular section's text.
5827 * External callers should use the getSection and replaceSection methods.
5829 * @param string $text Page wikitext
5830 * @param string $section A section identifier string of the form:
5831 * "<flag1> - <flag2> - ... - <section number>"
5833 * Currently the only recognised flag is "T", which means the target section number
5834 * was derived during a template inclusion parse, in other words this is a template
5835 * section edit link. If no flags are given, it was an ordinary section edit link.
5836 * This flag is required to avoid a section numbering mismatch when a section is
5837 * enclosed by "<includeonly>" (bug 6563).
5839 * The section number 0 pulls the text before the first heading; other numbers will
5840 * pull the given section along with its lower-level subsections. If the section is
5841 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5843 * Section 0 is always considered to exist, even if it only contains the empty
5844 * string. If $text is the empty string and section 0 is replaced, $newText is
5845 * returned.
5847 * @param string $mode One of "get" or "replace"
5848 * @param string $newText Replacement text for section data.
5849 * @return string For "get", the extracted section text.
5850 * for "replace", the whole page with the section replaced.
5852 private function extractSections( $text, $section, $mode, $newText = '' ) {
5853 global $wgTitle; # not generally used but removes an ugly failure mode
5855 $magicScopeVariable = $this->lock();
5856 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5857 $outText = '';
5858 $frame = $this->getPreprocessor()->newFrame();
5860 # Process section extraction flags
5861 $flags = 0;
5862 $sectionParts = explode( '-', $section );
5863 $sectionIndex = array_pop( $sectionParts );
5864 foreach ( $sectionParts as $part ) {
5865 if ( $part === 'T' ) {
5866 $flags |= self::PTD_FOR_INCLUSION;
5870 # Check for empty input
5871 if ( strval( $text ) === '' ) {
5872 # Only sections 0 and T-0 exist in an empty document
5873 if ( $sectionIndex == 0 ) {
5874 if ( $mode === 'get' ) {
5875 return '';
5876 } else {
5877 return $newText;
5879 } else {
5880 if ( $mode === 'get' ) {
5881 return $newText;
5882 } else {
5883 return $text;
5888 # Preprocess the text
5889 $root = $this->preprocessToDom( $text, $flags );
5891 # <h> nodes indicate section breaks
5892 # They can only occur at the top level, so we can find them by iterating the root's children
5893 $node = $root->getFirstChild();
5895 # Find the target section
5896 if ( $sectionIndex == 0 ) {
5897 # Section zero doesn't nest, level=big
5898 $targetLevel = 1000;
5899 } else {
5900 while ( $node ) {
5901 if ( $node->getName() === 'h' ) {
5902 $bits = $node->splitHeading();
5903 if ( $bits['i'] == $sectionIndex ) {
5904 $targetLevel = $bits['level'];
5905 break;
5908 if ( $mode === 'replace' ) {
5909 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5911 $node = $node->getNextSibling();
5915 if ( !$node ) {
5916 # Not found
5917 if ( $mode === 'get' ) {
5918 return $newText;
5919 } else {
5920 return $text;
5924 # Find the end of the section, including nested sections
5925 do {
5926 if ( $node->getName() === 'h' ) {
5927 $bits = $node->splitHeading();
5928 $curLevel = $bits['level'];
5929 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5930 break;
5933 if ( $mode === 'get' ) {
5934 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5936 $node = $node->getNextSibling();
5937 } while ( $node );
5939 # Write out the remainder (in replace mode only)
5940 if ( $mode === 'replace' ) {
5941 # Output the replacement text
5942 # Add two newlines on -- trailing whitespace in $newText is conventionally
5943 # stripped by the editor, so we need both newlines to restore the paragraph gap
5944 # Only add trailing whitespace if there is newText
5945 if ( $newText != "" ) {
5946 $outText .= $newText . "\n\n";
5949 while ( $node ) {
5950 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5951 $node = $node->getNextSibling();
5955 if ( is_string( $outText ) ) {
5956 # Re-insert stripped tags
5957 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5960 return $outText;
5964 * This function returns the text of a section, specified by a number ($section).
5965 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5966 * the first section before any such heading (section 0).
5968 * If a section contains subsections, these are also returned.
5970 * @param string $text Text to look in
5971 * @param string $section Section identifier
5972 * @param string $deftext Default to return if section is not found
5973 * @return string Text of the requested section
5975 public function getSection( $text, $section, $deftext = '' ) {
5976 return $this->extractSections( $text, $section, "get", $deftext );
5980 * This function returns $oldtext after the content of the section
5981 * specified by $section has been replaced with $text. If the target
5982 * section does not exist, $oldtext is returned unchanged.
5984 * @param string $oldtext Former text of the article
5985 * @param int $section Section identifier
5986 * @param string $text Replacing text
5987 * @return string Modified text
5989 public function replaceSection( $oldtext, $section, $text ) {
5990 return $this->extractSections( $oldtext, $section, "replace", $text );
5994 * Get the ID of the revision we are parsing
5996 * @return int|null
5998 function getRevisionId() {
5999 return $this->mRevisionId;
6003 * Get the revision object for $this->mRevisionId
6005 * @return Revision|null Either a Revision object or null
6006 * @since 1.23 (public since 1.23)
6008 public function getRevisionObject() {
6009 if ( !is_null( $this->mRevisionObject ) ) {
6010 return $this->mRevisionObject;
6012 if ( is_null( $this->mRevisionId ) ) {
6013 return null;
6016 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
6017 return $this->mRevisionObject;
6021 * Get the timestamp associated with the current revision, adjusted for
6022 * the default server-local timestamp
6023 * @return string
6025 function getRevisionTimestamp() {
6026 if ( is_null( $this->mRevisionTimestamp ) ) {
6027 wfProfileIn( __METHOD__ );
6029 global $wgContLang;
6031 $revObject = $this->getRevisionObject();
6032 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
6034 # The cryptic '' timezone parameter tells to use the site-default
6035 # timezone offset instead of the user settings.
6037 # Since this value will be saved into the parser cache, served
6038 # to other users, and potentially even used inside links and such,
6039 # it needs to be consistent for all visitors.
6040 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
6042 wfProfileOut( __METHOD__ );
6044 return $this->mRevisionTimestamp;
6048 * Get the name of the user that edited the last revision
6050 * @return string User name
6052 function getRevisionUser() {
6053 if ( is_null( $this->mRevisionUser ) ) {
6054 $revObject = $this->getRevisionObject();
6056 # if this template is subst: the revision id will be blank,
6057 # so just use the current user's name
6058 if ( $revObject ) {
6059 $this->mRevisionUser = $revObject->getUserText();
6060 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
6061 $this->mRevisionUser = $this->getUser()->getName();
6064 return $this->mRevisionUser;
6068 * Get the size of the revision
6070 * @return int|null Revision size
6072 function getRevisionSize() {
6073 if ( is_null( $this->mRevisionSize ) ) {
6074 $revObject = $this->getRevisionObject();
6076 # if this variable is subst: the revision id will be blank,
6077 # so just use the parser input size, because the own substituation
6078 # will change the size.
6079 if ( $revObject ) {
6080 $this->mRevisionSize = $revObject->getSize();
6081 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
6082 $this->mRevisionSize = $this->mInputSize;
6085 return $this->mRevisionSize;
6089 * Mutator for $mDefaultSort
6091 * @param string $sort New value
6093 public function setDefaultSort( $sort ) {
6094 $this->mDefaultSort = $sort;
6095 $this->mOutput->setProperty( 'defaultsort', $sort );
6099 * Accessor for $mDefaultSort
6100 * Will use the empty string if none is set.
6102 * This value is treated as a prefix, so the
6103 * empty string is equivalent to sorting by
6104 * page name.
6106 * @return string
6108 public function getDefaultSort() {
6109 if ( $this->mDefaultSort !== false ) {
6110 return $this->mDefaultSort;
6111 } else {
6112 return '';
6117 * Accessor for $mDefaultSort
6118 * Unlike getDefaultSort(), will return false if none is set
6120 * @return string|bool
6122 public function getCustomDefaultSort() {
6123 return $this->mDefaultSort;
6127 * Try to guess the section anchor name based on a wikitext fragment
6128 * presumably extracted from a heading, for example "Header" from
6129 * "== Header ==".
6131 * @param string $text
6133 * @return string
6135 public function guessSectionNameFromWikiText( $text ) {
6136 # Strip out wikitext links(they break the anchor)
6137 $text = $this->stripSectionName( $text );
6138 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6139 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
6143 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6144 * instead. For use in redirects, since IE6 interprets Redirect: headers
6145 * as something other than UTF-8 (apparently?), resulting in breakage.
6147 * @param string $text The section name
6148 * @return string An anchor
6150 public function guessLegacySectionNameFromWikiText( $text ) {
6151 # Strip out wikitext links(they break the anchor)
6152 $text = $this->stripSectionName( $text );
6153 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6154 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
6158 * Strips a text string of wikitext for use in a section anchor
6160 * Accepts a text string and then removes all wikitext from the
6161 * string and leaves only the resultant text (i.e. the result of
6162 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6163 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6164 * to create valid section anchors by mimicing the output of the
6165 * parser when headings are parsed.
6167 * @param string $text Text string to be stripped of wikitext
6168 * for use in a Section anchor
6169 * @return string Filtered text string
6171 public function stripSectionName( $text ) {
6172 # Strip internal link markup
6173 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6174 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6176 # Strip external link markup
6177 # @todo FIXME: Not tolerant to blank link text
6178 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6179 # on how many empty links there are on the page - need to figure that out.
6180 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6182 # Parse wikitext quotes (italics & bold)
6183 $text = $this->doQuotes( $text );
6185 # Strip HTML tags
6186 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
6187 return $text;
6191 * strip/replaceVariables/unstrip for preprocessor regression testing
6193 * @param string $text
6194 * @param Title $title
6195 * @param ParserOptions $options
6196 * @param int $outputType
6198 * @return string
6200 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
6201 $magicScopeVariable = $this->lock();
6202 $this->startParse( $title, $options, $outputType, true );
6204 $text = $this->replaceVariables( $text );
6205 $text = $this->mStripState->unstripBoth( $text );
6206 $text = Sanitizer::removeHTMLtags( $text );
6207 return $text;
6211 * @param string $text
6212 * @param Title $title
6213 * @param ParserOptions $options
6214 * @return string
6216 function testPst( $text, Title $title, ParserOptions $options ) {
6217 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6221 * @param string $text
6222 * @param Title $title
6223 * @param ParserOptions $options
6224 * @return string
6226 function testPreprocess( $text, Title $title, ParserOptions $options ) {
6227 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
6231 * Call a callback function on all regions of the given text that are not
6232 * inside strip markers, and replace those regions with the return value
6233 * of the callback. For example, with input:
6235 * aaa<MARKER>bbb
6237 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6238 * two strings will be replaced with the value returned by the callback in
6239 * each case.
6241 * @param string $s
6242 * @param callable $callback
6244 * @return string
6246 function markerSkipCallback( $s, $callback ) {
6247 $i = 0;
6248 $out = '';
6249 while ( $i < strlen( $s ) ) {
6250 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
6251 if ( $markerStart === false ) {
6252 $out .= call_user_func( $callback, substr( $s, $i ) );
6253 break;
6254 } else {
6255 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6256 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
6257 if ( $markerEnd === false ) {
6258 $out .= substr( $s, $markerStart );
6259 break;
6260 } else {
6261 $markerEnd += strlen( self::MARKER_SUFFIX );
6262 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6263 $i = $markerEnd;
6267 return $out;
6271 * Remove any strip markers found in the given text.
6273 * @param string $text Input string
6274 * @return string
6276 function killMarkers( $text ) {
6277 return $this->mStripState->killMarkers( $text );
6281 * Save the parser state required to convert the given half-parsed text to
6282 * HTML. "Half-parsed" in this context means the output of
6283 * recursiveTagParse() or internalParse(). This output has strip markers
6284 * from replaceVariables (extensionSubstitution() etc.), and link
6285 * placeholders from replaceLinkHolders().
6287 * Returns an array which can be serialized and stored persistently. This
6288 * array can later be loaded into another parser instance with
6289 * unserializeHalfParsedText(). The text can then be safely incorporated into
6290 * the return value of a parser hook.
6292 * @param string $text
6294 * @return array
6296 function serializeHalfParsedText( $text ) {
6297 wfProfileIn( __METHOD__ );
6298 $data = array(
6299 'text' => $text,
6300 'version' => self::HALF_PARSED_VERSION,
6301 'stripState' => $this->mStripState->getSubState( $text ),
6302 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6304 wfProfileOut( __METHOD__ );
6305 return $data;
6309 * Load the parser state given in the $data array, which is assumed to
6310 * have been generated by serializeHalfParsedText(). The text contents is
6311 * extracted from the array, and its markers are transformed into markers
6312 * appropriate for the current Parser instance. This transformed text is
6313 * returned, and can be safely included in the return value of a parser
6314 * hook.
6316 * If the $data array has been stored persistently, the caller should first
6317 * check whether it is still valid, by calling isValidHalfParsedText().
6319 * @param array $data Serialized data
6320 * @throws MWException
6321 * @return string
6323 function unserializeHalfParsedText( $data ) {
6324 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6325 throw new MWException( __METHOD__ . ': invalid version' );
6328 # First, extract the strip state.
6329 $texts = array( $data['text'] );
6330 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6332 # Now renumber links
6333 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6335 # Should be good to go.
6336 return $texts[0];
6340 * Returns true if the given array, presumed to be generated by
6341 * serializeHalfParsedText(), is compatible with the current version of the
6342 * parser.
6344 * @param array $data
6346 * @return bool
6348 function isValidHalfParsedText( $data ) {
6349 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6353 * Parsed a width param of imagelink like 300px or 200x300px
6355 * @param string $value
6357 * @return array
6358 * @since 1.20
6360 public function parseWidthParam( $value ) {
6361 $parsedWidthParam = array();
6362 if ( $value === '' ) {
6363 return $parsedWidthParam;
6365 $m = array();
6366 # (bug 13500) In both cases (width/height and width only),
6367 # permit trailing "px" for backward compatibility.
6368 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6369 $width = intval( $m[1] );
6370 $height = intval( $m[2] );
6371 $parsedWidthParam['width'] = $width;
6372 $parsedWidthParam['height'] = $height;
6373 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6374 $width = intval( $value );
6375 $parsedWidthParam['width'] = $width;
6377 return $parsedWidthParam;
6381 * Lock the current instance of the parser.
6383 * This is meant to stop someone from calling the parser
6384 * recursively and messing up all the strip state.
6386 * @throws MWException If parser is in a parse
6387 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6389 protected function lock() {
6390 if ( $this->mInParse ) {
6391 throw new MWException( "Parser state cleared while parsing. "
6392 . "Did you call Parser::parse recursively?" );
6394 $this->mInParse = true;
6396 $that = $this;
6397 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6398 $that->mInParse = false;
6399 } );
6401 return $recursiveCheck;