Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / parser / Parser.php
bloba9b0c82c625c6af2cf7ac277bdfc81ef5c9a4e51
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 const SFH_NO_HASH = 1;
83 const SFH_OBJECT_ARGS = 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
89 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
90 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
91 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
93 # Regular expression for a non-newline space
94 const SPACE_NOT_NL = '(?:\t|&nbsp;|&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
96 # State constants for the definition list colon extraction
97 const COLON_STATE_TEXT = 0;
98 const COLON_STATE_TAG = 1;
99 const COLON_STATE_TAGSTART = 2;
100 const COLON_STATE_CLOSETAG = 3;
101 const COLON_STATE_TAGSLASH = 4;
102 const COLON_STATE_COMMENT = 5;
103 const COLON_STATE_COMMENTDASH = 6;
104 const COLON_STATE_COMMENTDASHDASH = 7;
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION = 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML = 1; # like parse()
112 const OT_WIKI = 2; # like preSaveTransform()
113 const OT_PREPROCESS = 3; # like preprocess()
114 const OT_MSG = 3;
115 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX = "-QINU\x7f";
120 # Markers used for wrapping the table of contents
121 const TOC_START = '<mw:toc>';
122 const TOC_END = '</mw:toc>';
124 # Persistent:
125 public $mTagHooks = array();
126 public $mTransparentTagHooks = array();
127 public $mFunctionHooks = array();
128 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
129 public $mFunctionTagHooks = array();
130 public $mStripList = array();
131 public $mDefaultStripList = array();
132 public $mVarCache = array();
133 public $mImageParams = array();
134 public $mImageParamsMagicArray = array();
135 public $mMarkerIndex = 0;
136 public $mFirstCall = true;
138 # Initialised by initialiseVariables()
141 * @var MagicWordArray
143 public $mVariables;
146 * @var MagicWordArray
148 public $mSubstWords;
149 # Initialised in constructor
150 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols;
152 # Cleared with clearState():
154 * @var ParserOutput
156 public $mOutput;
157 public $mAutonumber, $mDTopen;
160 * @var StripState
162 public $mStripState;
164 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
166 * @var LinkHolderArray
168 public $mLinkHolders;
170 public $mLinkID;
171 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
172 public $mDefaultSort;
173 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
174 public $mExpensiveFunctionCount; # number of expensive parser function calls
175 public $mShowToc, $mForceTocPosition;
178 * @var User
180 public $mUser; # User object; only used when doing pre-save transform
182 # Temporary
183 # These are variables reset at least once per parse regardless of $clearState
186 * @var ParserOptions
188 public $mOptions;
191 * @var Title
193 public $mTitle; # Title context, used for self-link rendering and similar things
194 public $mOutputType; # Output type, one of the OT_xxx constants
195 public $ot; # Shortcut alias, see setOutputType()
196 public $mRevisionObject; # The revision object of the specified revision ID
197 public $mRevisionId; # ID to display in {{REVISIONID}} tags
198 public $mRevisionTimestamp; # The timestamp of the specified revision ID
199 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
200 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
201 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
202 public $mInputSize = false; # For {{PAGESIZE}} on current page.
205 * @var string
207 public $mUniqPrefix;
210 * @var array Array with the language name of each language link (i.e. the
211 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
212 * duplicate language links to the ParserOutput.
214 public $mLangLinkLanguages;
217 * @var MapCacheLRU|null
218 * @since 1.24
220 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
222 public $currentRevisionCache;
225 * @var bool Recursive call protection.
226 * This variable should be treated as if it were private.
228 public $mInParse = false;
230 /** @var SectionProfiler */
231 protected $mProfiler;
234 * @param array $conf
236 public function __construct( $conf = array() ) {
237 $this->mConf = $conf;
238 $this->mUrlProtocols = wfUrlProtocols();
239 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
240 self::EXT_LINK_URL_CLASS . '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
241 if ( isset( $conf['preprocessorClass'] ) ) {
242 $this->mPreprocessorClass = $conf['preprocessorClass'];
243 } elseif ( defined( 'HPHP_VERSION' ) ) {
244 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
245 $this->mPreprocessorClass = 'Preprocessor_Hash';
246 } elseif ( extension_loaded( 'domxml' ) ) {
247 # PECL extension that conflicts with the core DOM extension (bug 13770)
248 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
249 $this->mPreprocessorClass = 'Preprocessor_Hash';
250 } elseif ( extension_loaded( 'dom' ) ) {
251 $this->mPreprocessorClass = 'Preprocessor_DOM';
252 } else {
253 $this->mPreprocessorClass = 'Preprocessor_Hash';
255 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
259 * Reduce memory usage to reduce the impact of circular references
261 public function __destruct() {
262 if ( isset( $this->mLinkHolders ) ) {
263 unset( $this->mLinkHolders );
265 foreach ( $this as $name => $value ) {
266 unset( $this->$name );
271 * Allow extensions to clean up when the parser is cloned
273 public function __clone() {
274 $this->mInParse = false;
276 // Bug 56226: When you create a reference "to" an object field, that
277 // makes the object field itself be a reference too (until the other
278 // reference goes out of scope). When cloning, any field that's a
279 // reference is copied as a reference in the new object. Both of these
280 // are defined PHP5 behaviors, as inconvenient as it is for us when old
281 // hooks from PHP4 days are passing fields by reference.
282 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
283 // Make a non-reference copy of the field, then rebind the field to
284 // reference the new copy.
285 $tmp = $this->$k;
286 $this->$k =& $tmp;
287 unset( $tmp );
290 Hooks::run( 'ParserCloned', array( $this ) );
294 * Do various kinds of initialisation on the first call of the parser
296 public function firstCallInit() {
297 if ( !$this->mFirstCall ) {
298 return;
300 $this->mFirstCall = false;
302 CoreParserFunctions::register( $this );
303 CoreTagHooks::register( $this );
304 $this->initialiseVariables();
306 Hooks::run( 'ParserFirstCallInit', array( &$this ) );
310 * Clear Parser state
312 * @private
314 public function clearState() {
315 if ( $this->mFirstCall ) {
316 $this->firstCallInit();
318 $this->mOutput = new ParserOutput;
319 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
320 $this->mAutonumber = 0;
321 $this->mLastSection = '';
322 $this->mDTopen = false;
323 $this->mIncludeCount = array();
324 $this->mArgStack = false;
325 $this->mInPre = false;
326 $this->mLinkHolders = new LinkHolderArray( $this );
327 $this->mLinkID = 0;
328 $this->mRevisionObject = $this->mRevisionTimestamp =
329 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null;
330 $this->mVarCache = array();
331 $this->mUser = null;
332 $this->mLangLinkLanguages = array();
333 $this->currentRevisionCache = null;
336 * Prefix for temporary replacement strings for the multipass parser.
337 * \x07 should never appear in input as it's disallowed in XML.
338 * Using it at the front also gives us a little extra robustness
339 * since it shouldn't match when butted up against identifier-like
340 * string constructs.
342 * Must not consist of all title characters, or else it will change
343 * the behavior of <nowiki> in a link.
345 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
346 $this->mStripState = new StripState( $this->mUniqPrefix );
348 # Clear these on every parse, bug 4549
349 $this->mTplRedirCache = $this->mTplDomCache = array();
351 $this->mShowToc = true;
352 $this->mForceTocPosition = false;
353 $this->mIncludeSizes = array(
354 'post-expand' => 0,
355 'arg' => 0,
357 $this->mPPNodeCount = 0;
358 $this->mGeneratedPPNodeCount = 0;
359 $this->mHighestExpansionDepth = 0;
360 $this->mDefaultSort = false;
361 $this->mHeadings = array();
362 $this->mDoubleUnderscores = array();
363 $this->mExpensiveFunctionCount = 0;
365 # Fix cloning
366 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
367 $this->mPreprocessor = null;
370 $this->mProfiler = new SectionProfiler();
372 Hooks::run( 'ParserClearState', array( &$this ) );
376 * Convert wikitext to HTML
377 * Do not call this function recursively.
379 * @param string $text Text we want to parse
380 * @param Title $title
381 * @param ParserOptions $options
382 * @param bool $linestart
383 * @param bool $clearState
384 * @param int $revid Number to pass in {{REVISIONID}}
385 * @return ParserOutput A ParserOutput
387 public function parse( $text, Title $title, ParserOptions $options,
388 $linestart = true, $clearState = true, $revid = null
391 * First pass--just handle <nowiki> sections, pass the rest off
392 * to internalParse() which does all the real work.
395 global $wgShowHostnames;
396 $fname = __METHOD__ . '-' . wfGetCaller();
398 if ( $clearState ) {
399 $magicScopeVariable = $this->lock();
402 $this->startParse( $title, $options, self::OT_HTML, $clearState );
404 $this->currentRevisionCache = null;
405 $this->mInputSize = strlen( $text );
406 if ( $this->mOptions->getEnableLimitReport() ) {
407 $this->mOutput->resetParseStartTime();
410 # Remove the strip marker tag prefix from the input, if present.
411 if ( $clearState ) {
412 $text = str_replace( $this->mUniqPrefix, '', $text );
415 $oldRevisionId = $this->mRevisionId;
416 $oldRevisionObject = $this->mRevisionObject;
417 $oldRevisionTimestamp = $this->mRevisionTimestamp;
418 $oldRevisionUser = $this->mRevisionUser;
419 $oldRevisionSize = $this->mRevisionSize;
420 if ( $revid !== null ) {
421 $this->mRevisionId = $revid;
422 $this->mRevisionObject = null;
423 $this->mRevisionTimestamp = null;
424 $this->mRevisionUser = null;
425 $this->mRevisionSize = null;
428 Hooks::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
429 # No more strip!
430 Hooks::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
431 $text = $this->internalParse( $text );
432 Hooks::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) );
434 $text = $this->internalParseHalfParsed( $text, true, $linestart );
437 * A converted title will be provided in the output object if title and
438 * content conversion are enabled, the article text does not contain
439 * a conversion-suppressing double-underscore tag, and no
440 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
441 * automatic link conversion.
443 if ( !( $options->getDisableTitleConversion()
444 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
445 || isset( $this->mDoubleUnderscores['notitleconvert'] )
446 || $this->mOutput->getDisplayTitle() !== false )
448 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
449 if ( $convruletitle ) {
450 $this->mOutput->setTitleText( $convruletitle );
451 } else {
452 $titleText = $this->getConverterLanguage()->convertTitle( $title );
453 $this->mOutput->setTitleText( $titleText );
457 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
458 $this->limitationWarn( 'expensive-parserfunction',
459 $this->mExpensiveFunctionCount,
460 $this->mOptions->getExpensiveParserFunctionLimit()
464 # Information on include size limits, for the benefit of users who try to skirt them
465 if ( $this->mOptions->getEnableLimitReport() ) {
466 $max = $this->mOptions->getMaxIncludeSize();
468 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' );
469 if ( $cpuTime !== null ) {
470 $this->mOutput->setLimitReportData( 'limitreport-cputime',
471 sprintf( "%.3f", $cpuTime )
475 $wallTime = $this->mOutput->getTimeSinceStart( 'wall' );
476 $this->mOutput->setLimitReportData( 'limitreport-walltime',
477 sprintf( "%.3f", $wallTime )
480 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes',
481 array( $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() )
483 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes',
484 array( $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() )
486 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize',
487 array( $this->mIncludeSizes['post-expand'], $max )
489 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize',
490 array( $this->mIncludeSizes['arg'], $max )
492 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth',
493 array( $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() )
495 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount',
496 array( $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() )
498 Hooks::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput ) );
500 $limitReport = "NewPP limit report\n";
501 if ( $wgShowHostnames ) {
502 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
504 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
505 if ( Hooks::run( 'ParserLimitReportFormat',
506 array( $key, &$value, &$limitReport, false, false )
507 ) ) {
508 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
509 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
510 ->inLanguage( 'en' )->useDatabase( false );
511 if ( !$valueMsg->exists() ) {
512 $valueMsg = new RawMessage( '$1' );
514 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
515 $valueMsg->params( $value );
516 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
520 // Since we're not really outputting HTML, decode the entities and
521 // then re-encode the things that need hiding inside HTML comments.
522 $limitReport = htmlspecialchars_decode( $limitReport );
523 Hooks::run( 'ParserLimitReport', array( $this, &$limitReport ) );
525 // Sanitize for comment. Note '‐' in the replacement is U+2010,
526 // which looks much like the problematic '-'.
527 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&amp;' ), $limitReport );
528 $text .= "\n<!-- \n$limitReport-->\n";
530 // Add on template profiling data
531 $dataByFunc = $this->mProfiler->getFunctionStats();
532 uasort( $dataByFunc, function ( $a, $b ) {
533 return $a['real'] < $b['real']; // descending order
534 } );
535 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
536 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
537 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
538 $item['%real'], $item['real'], $item['calls'],
539 htmlspecialchars( $item['name'] ) );
541 $text .= "\n<!-- \n$profileReport-->\n";
543 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
544 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
545 $this->mTitle->getPrefixedDBkey() );
548 $this->mOutput->setText( $text );
550 $this->mRevisionId = $oldRevisionId;
551 $this->mRevisionObject = $oldRevisionObject;
552 $this->mRevisionTimestamp = $oldRevisionTimestamp;
553 $this->mRevisionUser = $oldRevisionUser;
554 $this->mRevisionSize = $oldRevisionSize;
555 $this->mInputSize = false;
556 $this->currentRevisionCache = null;
558 return $this->mOutput;
562 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
563 * can be called from an extension tag hook.
565 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
566 * instead, which means that lists and links have not been fully parsed yet,
567 * and strip markers are still present.
569 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
571 * Use this function if you're a parser tag hook and you want to parse
572 * wikitext before or after applying additional transformations, and you
573 * intend to *return the result as hook output*, which will cause it to go
574 * through the rest of parsing process automatically.
576 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
577 * $text are not expanded
579 * @param string $text Text extension wants to have parsed
580 * @param bool|PPFrame $frame The frame to use for expanding any template variables
581 * @return string UNSAFE half-parsed HTML
583 public function recursiveTagParse( $text, $frame = false ) {
584 Hooks::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
585 Hooks::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
586 $text = $this->internalParse( $text, false, $frame );
587 return $text;
591 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
592 * point can be called from an extension tag hook.
594 * The output of this function is fully-parsed HTML that is safe for output.
595 * If you're a parser tag hook, you might want to use recursiveTagParse()
596 * instead.
598 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
599 * $text are not expanded
601 * @since 1.25
603 * @param string $text Text extension wants to have parsed
604 * @param bool|PPFrame $frame The frame to use for expanding any template variables
605 * @return string Fully parsed HTML
607 public function recursiveTagParseFully( $text, $frame = false ) {
608 $text = $this->recursiveTagParse( $text, $frame );
609 $text = $this->internalParseHalfParsed( $text, false );
610 return $text;
614 * Expand templates and variables in the text, producing valid, static wikitext.
615 * Also removes comments.
616 * Do not call this function recursively.
617 * @param string $text
618 * @param Title $title
619 * @param ParserOptions $options
620 * @param int|null $revid
621 * @param bool|PPFrame $frame
622 * @return mixed|string
624 public function preprocess( $text, Title $title = null,
625 ParserOptions $options, $revid = null, $frame = false
627 $magicScopeVariable = $this->lock();
628 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
629 if ( $revid !== null ) {
630 $this->mRevisionId = $revid;
632 Hooks::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
633 Hooks::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
634 $text = $this->replaceVariables( $text, $frame );
635 $text = $this->mStripState->unstripBoth( $text );
636 return $text;
640 * Recursive parser entry point that can be called from an extension tag
641 * hook.
643 * @param string $text Text to be expanded
644 * @param bool|PPFrame $frame The frame to use for expanding any template variables
645 * @return string
646 * @since 1.19
648 public function recursivePreprocess( $text, $frame = false ) {
649 $text = $this->replaceVariables( $text, $frame );
650 $text = $this->mStripState->unstripBoth( $text );
651 return $text;
655 * Process the wikitext for the "?preload=" feature. (bug 5210)
657 * "<noinclude>", "<includeonly>" etc. are parsed as for template
658 * transclusion, comments, templates, arguments, tags hooks and parser
659 * functions are untouched.
661 * @param string $text
662 * @param Title $title
663 * @param ParserOptions $options
664 * @param array $params
665 * @return string
667 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = array() ) {
668 $msg = new RawMessage( $text );
669 $text = $msg->params( $params )->plain();
671 # Parser (re)initialisation
672 $magicScopeVariable = $this->lock();
673 $this->startParse( $title, $options, self::OT_PLAIN, true );
675 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
676 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
677 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
678 $text = $this->mStripState->unstripBoth( $text );
679 return $text;
683 * Get a random string
685 * @return string
687 public static function getRandomString() {
688 return wfRandomString( 16 );
692 * Set the current user.
693 * Should only be used when doing pre-save transform.
695 * @param User|null $user User object or null (to reset)
697 public function setUser( $user ) {
698 $this->mUser = $user;
702 * Accessor for mUniqPrefix.
704 * @return string
706 public function uniqPrefix() {
707 if ( !isset( $this->mUniqPrefix ) ) {
708 # @todo FIXME: This is probably *horribly wrong*
709 # LanguageConverter seems to want $wgParser's uniqPrefix, however
710 # if this is called for a parser cache hit, the parser may not
711 # have ever been initialized in the first place.
712 # Not really sure what the heck is supposed to be going on here.
713 return '';
714 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
716 return $this->mUniqPrefix;
720 * Set the context title
722 * @param Title $t
724 public function setTitle( $t ) {
725 if ( !$t ) {
726 $t = Title::newFromText( 'NO TITLE' );
729 if ( $t->hasFragment() ) {
730 # Strip the fragment to avoid various odd effects
731 $this->mTitle = clone $t;
732 $this->mTitle->setFragment( '' );
733 } else {
734 $this->mTitle = $t;
739 * Accessor for the Title object
741 * @return Title
743 public function getTitle() {
744 return $this->mTitle;
748 * Accessor/mutator for the Title object
750 * @param Title $x Title object or null to just get the current one
751 * @return Title
753 public function Title( $x = null ) {
754 return wfSetVar( $this->mTitle, $x );
758 * Set the output type
760 * @param int $ot New value
762 public function setOutputType( $ot ) {
763 $this->mOutputType = $ot;
764 # Shortcut alias
765 $this->ot = array(
766 'html' => $ot == self::OT_HTML,
767 'wiki' => $ot == self::OT_WIKI,
768 'pre' => $ot == self::OT_PREPROCESS,
769 'plain' => $ot == self::OT_PLAIN,
774 * Accessor/mutator for the output type
776 * @param int|null $x New value or null to just get the current one
777 * @return int
779 public function OutputType( $x = null ) {
780 return wfSetVar( $this->mOutputType, $x );
784 * Get the ParserOutput object
786 * @return ParserOutput
788 public function getOutput() {
789 return $this->mOutput;
793 * Get the ParserOptions object
795 * @return ParserOptions
797 public function getOptions() {
798 return $this->mOptions;
802 * Accessor/mutator for the ParserOptions object
804 * @param ParserOptions $x New value or null to just get the current one
805 * @return ParserOptions Current ParserOptions object
807 public function Options( $x = null ) {
808 return wfSetVar( $this->mOptions, $x );
812 * @return int
814 public function nextLinkID() {
815 return $this->mLinkID++;
819 * @param int $id
821 public function setLinkID( $id ) {
822 $this->mLinkID = $id;
826 * Get a language object for use in parser functions such as {{FORMATNUM:}}
827 * @return Language
829 public function getFunctionLang() {
830 return $this->getTargetLanguage();
834 * Get the target language for the content being parsed. This is usually the
835 * language that the content is in.
837 * @since 1.19
839 * @throws MWException
840 * @return Language
842 public function getTargetLanguage() {
843 $target = $this->mOptions->getTargetLanguage();
845 if ( $target !== null ) {
846 return $target;
847 } elseif ( $this->mOptions->getInterfaceMessage() ) {
848 return $this->mOptions->getUserLangObj();
849 } elseif ( is_null( $this->mTitle ) ) {
850 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
853 return $this->mTitle->getPageLanguage();
857 * Get the language object for language conversion
858 * @return Language|null
860 public function getConverterLanguage() {
861 return $this->getTargetLanguage();
865 * Get a User object either from $this->mUser, if set, or from the
866 * ParserOptions object otherwise
868 * @return User
870 public function getUser() {
871 if ( !is_null( $this->mUser ) ) {
872 return $this->mUser;
874 return $this->mOptions->getUser();
878 * Get a preprocessor object
880 * @return Preprocessor
882 public function getPreprocessor() {
883 if ( !isset( $this->mPreprocessor ) ) {
884 $class = $this->mPreprocessorClass;
885 $this->mPreprocessor = new $class( $this );
887 return $this->mPreprocessor;
891 * Replaces all occurrences of HTML-style comments and the given tags
892 * in the text with a random marker and returns the next text. The output
893 * parameter $matches will be an associative array filled with data in
894 * the form:
896 * @code
897 * 'UNIQ-xxxxx' => array(
898 * 'element',
899 * 'tag content',
900 * array( 'param' => 'x' ),
901 * '<element param="x">tag content</element>' ) )
902 * @endcode
904 * @param array $elements List of element names. Comments are always extracted.
905 * @param string $text Source text string.
906 * @param array $matches Out parameter, Array: extracted tags
907 * @param string $uniq_prefix
908 * @return string Stripped text
910 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
911 static $n = 1;
912 $stripped = '';
913 $matches = array();
915 $taglist = implode( '|', $elements );
916 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
918 while ( $text != '' ) {
919 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
920 $stripped .= $p[0];
921 if ( count( $p ) < 5 ) {
922 break;
924 if ( count( $p ) > 5 ) {
925 # comment
926 $element = $p[4];
927 $attributes = '';
928 $close = '';
929 $inside = $p[5];
930 } else {
931 # tag
932 $element = $p[1];
933 $attributes = $p[2];
934 $close = $p[3];
935 $inside = $p[4];
938 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
939 $stripped .= $marker;
941 if ( $close === '/>' ) {
942 # Empty element tag, <tag />
943 $content = null;
944 $text = $inside;
945 $tail = null;
946 } else {
947 if ( $element === '!--' ) {
948 $end = '/(-->)/';
949 } else {
950 $end = "/(<\\/$element\\s*>)/i";
952 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
953 $content = $q[0];
954 if ( count( $q ) < 3 ) {
955 # No end tag -- let it run out to the end of the text.
956 $tail = '';
957 $text = '';
958 } else {
959 $tail = $q[1];
960 $text = $q[2];
964 $matches[$marker] = array( $element,
965 $content,
966 Sanitizer::decodeTagAttributes( $attributes ),
967 "<$element$attributes$close$content$tail" );
969 return $stripped;
973 * Get a list of strippable XML-like elements
975 * @return array
977 public function getStripList() {
978 return $this->mStripList;
982 * Add an item to the strip state
983 * Returns the unique tag which must be inserted into the stripped text
984 * The tag will be replaced with the original text in unstrip()
986 * @param string $text
988 * @return string
990 public function insertStripItem( $text ) {
991 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
992 $this->mMarkerIndex++;
993 $this->mStripState->addGeneral( $rnd, $text );
994 return $rnd;
998 * parse the wiki syntax used to render tables
1000 * @private
1001 * @param string $text
1002 * @return string
1004 public function doTableStuff( $text ) {
1006 $lines = StringUtils::explode( "\n", $text );
1007 $out = '';
1008 $td_history = array(); # Is currently a td tag open?
1009 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1010 $tr_history = array(); # Is currently a tr tag open?
1011 $tr_attributes = array(); # history of tr attributes
1012 $has_opened_tr = array(); # Did this table open a <tr> element?
1013 $indent_level = 0; # indent level of the table
1015 foreach ( $lines as $outLine ) {
1016 $line = trim( $outLine );
1018 if ( $line === '' ) { # empty line, go to next line
1019 $out .= $outLine . "\n";
1020 continue;
1023 $first_character = $line[0];
1024 $matches = array();
1026 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1027 # First check if we are starting a new table
1028 $indent_level = strlen( $matches[1] );
1030 $attributes = $this->mStripState->unstripBoth( $matches[2] );
1031 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
1033 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1034 array_push( $td_history, false );
1035 array_push( $last_tag_history, '' );
1036 array_push( $tr_history, false );
1037 array_push( $tr_attributes, '' );
1038 array_push( $has_opened_tr, false );
1039 } elseif ( count( $td_history ) == 0 ) {
1040 # Don't do any of the following
1041 $out .= $outLine . "\n";
1042 continue;
1043 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1044 # We are ending a table
1045 $line = '</table>' . substr( $line, 2 );
1046 $last_tag = array_pop( $last_tag_history );
1048 if ( !array_pop( $has_opened_tr ) ) {
1049 $line = "<tr><td></td></tr>{$line}";
1052 if ( array_pop( $tr_history ) ) {
1053 $line = "</tr>{$line}";
1056 if ( array_pop( $td_history ) ) {
1057 $line = "</{$last_tag}>{$line}";
1059 array_pop( $tr_attributes );
1060 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1061 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1062 # Now we have a table row
1063 $line = preg_replace( '#^\|-+#', '', $line );
1065 # Whats after the tag is now only attributes
1066 $attributes = $this->mStripState->unstripBoth( $line );
1067 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
1068 array_pop( $tr_attributes );
1069 array_push( $tr_attributes, $attributes );
1071 $line = '';
1072 $last_tag = array_pop( $last_tag_history );
1073 array_pop( $has_opened_tr );
1074 array_push( $has_opened_tr, true );
1076 if ( array_pop( $tr_history ) ) {
1077 $line = '</tr>';
1080 if ( array_pop( $td_history ) ) {
1081 $line = "</{$last_tag}>{$line}";
1084 $outLine = $line;
1085 array_push( $tr_history, false );
1086 array_push( $td_history, false );
1087 array_push( $last_tag_history, '' );
1088 } elseif ( $first_character === '|'
1089 || $first_character === '!'
1090 || substr( $line, 0, 2 ) === '|+'
1092 # This might be cell elements, td, th or captions
1093 if ( substr( $line, 0, 2 ) === '|+' ) {
1094 $first_character = '+';
1095 $line = substr( $line, 1 );
1098 $line = substr( $line, 1 );
1100 if ( $first_character === '!' ) {
1101 $line = str_replace( '!!', '||', $line );
1104 # Split up multiple cells on the same line.
1105 # FIXME : This can result in improper nesting of tags processed
1106 # by earlier parser steps, but should avoid splitting up eg
1107 # attribute values containing literal "||".
1108 $cells = StringUtils::explodeMarkup( '||', $line );
1110 $outLine = '';
1112 # Loop through each table cell
1113 foreach ( $cells as $cell ) {
1114 $previous = '';
1115 if ( $first_character !== '+' ) {
1116 $tr_after = array_pop( $tr_attributes );
1117 if ( !array_pop( $tr_history ) ) {
1118 $previous = "<tr{$tr_after}>\n";
1120 array_push( $tr_history, true );
1121 array_push( $tr_attributes, '' );
1122 array_pop( $has_opened_tr );
1123 array_push( $has_opened_tr, true );
1126 $last_tag = array_pop( $last_tag_history );
1128 if ( array_pop( $td_history ) ) {
1129 $previous = "</{$last_tag}>\n{$previous}";
1132 if ( $first_character === '|' ) {
1133 $last_tag = 'td';
1134 } elseif ( $first_character === '!' ) {
1135 $last_tag = 'th';
1136 } elseif ( $first_character === '+' ) {
1137 $last_tag = 'caption';
1138 } else {
1139 $last_tag = '';
1142 array_push( $last_tag_history, $last_tag );
1144 # A cell could contain both parameters and data
1145 $cell_data = explode( '|', $cell, 2 );
1147 # Bug 553: Note that a '|' inside an invalid link should not
1148 # be mistaken as delimiting cell parameters
1149 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1150 $cell = "{$previous}<{$last_tag}>{$cell}";
1151 } elseif ( count( $cell_data ) == 1 ) {
1152 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1153 } else {
1154 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1155 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1156 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1159 $outLine .= $cell;
1160 array_push( $td_history, true );
1163 $out .= $outLine . "\n";
1166 # Closing open td, tr && table
1167 while ( count( $td_history ) > 0 ) {
1168 if ( array_pop( $td_history ) ) {
1169 $out .= "</td>\n";
1171 if ( array_pop( $tr_history ) ) {
1172 $out .= "</tr>\n";
1174 if ( !array_pop( $has_opened_tr ) ) {
1175 $out .= "<tr><td></td></tr>\n";
1178 $out .= "</table>\n";
1181 # Remove trailing line-ending (b/c)
1182 if ( substr( $out, -1 ) === "\n" ) {
1183 $out = substr( $out, 0, -1 );
1186 # special case: don't return empty table
1187 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1188 $out = '';
1191 return $out;
1195 * Helper function for parse() that transforms wiki markup into half-parsed
1196 * HTML. Only called for $mOutputType == self::OT_HTML.
1198 * @private
1200 * @param string $text
1201 * @param bool $isMain
1202 * @param bool $frame
1204 * @return string
1206 public function internalParse( $text, $isMain = true, $frame = false ) {
1208 $origText = $text;
1210 # Hook to suspend the parser in this state
1211 if ( !Hooks::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
1212 return $text;
1215 # if $frame is provided, then use $frame for replacing any variables
1216 if ( $frame ) {
1217 # use frame depth to infer how include/noinclude tags should be handled
1218 # depth=0 means this is the top-level document; otherwise it's an included document
1219 if ( !$frame->depth ) {
1220 $flag = 0;
1221 } else {
1222 $flag = Parser::PTD_FOR_INCLUSION;
1224 $dom = $this->preprocessToDom( $text, $flag );
1225 $text = $frame->expand( $dom );
1226 } else {
1227 # if $frame is not provided, then use old-style replaceVariables
1228 $text = $this->replaceVariables( $text );
1231 Hooks::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) );
1232 $text = Sanitizer::removeHTMLtags(
1233 $text,
1234 array( &$this, 'attributeStripCallback' ),
1235 false,
1236 array_keys( $this->mTransparentTagHooks )
1238 Hooks::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
1240 # Tables need to come after variable replacement for things to work
1241 # properly; putting them before other transformations should keep
1242 # exciting things like link expansions from showing up in surprising
1243 # places.
1244 $text = $this->doTableStuff( $text );
1246 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1248 $text = $this->doDoubleUnderscore( $text );
1250 $text = $this->doHeadings( $text );
1251 $text = $this->replaceInternalLinks( $text );
1252 $text = $this->doAllQuotes( $text );
1253 $text = $this->replaceExternalLinks( $text );
1255 # replaceInternalLinks may sometimes leave behind
1256 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1257 $text = str_replace( $this->mUniqPrefix . 'NOPARSE', '', $text );
1259 $text = $this->doMagicLinks( $text );
1260 $text = $this->formatHeadings( $text, $origText, $isMain );
1262 return $text;
1266 * Helper function for parse() that transforms half-parsed HTML into fully
1267 * parsed HTML.
1269 * @param string $text
1270 * @param bool $isMain
1271 * @param bool $linestart
1272 * @return string
1274 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1275 global $wgUseTidy, $wgAlwaysUseTidy;
1277 $text = $this->mStripState->unstripGeneral( $text );
1279 # Clean up special characters, only run once, next-to-last before doBlockLevels
1280 $fixtags = array(
1281 # french spaces, last one Guillemet-left
1282 # only if there is something before the space
1283 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
1284 # french spaces, Guillemet-right
1285 '/(\\302\\253) /' => '\\1&#160;',
1286 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1288 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1290 $text = $this->doBlockLevels( $text, $linestart );
1292 $this->replaceLinkHolders( $text );
1295 * The input doesn't get language converted if
1296 * a) It's disabled
1297 * b) Content isn't converted
1298 * c) It's a conversion table
1299 * d) it is an interface message (which is in the user language)
1301 if ( !( $this->mOptions->getDisableContentConversion()
1302 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
1304 if ( !$this->mOptions->getInterfaceMessage() ) {
1305 # The position of the convert() call should not be changed. it
1306 # assumes that the links are all replaced and the only thing left
1307 # is the <nowiki> mark.
1308 $text = $this->getConverterLanguage()->convert( $text );
1312 $text = $this->mStripState->unstripNoWiki( $text );
1314 if ( $isMain ) {
1315 Hooks::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1318 $text = $this->replaceTransparentTags( $text );
1319 $text = $this->mStripState->unstripGeneral( $text );
1321 $text = Sanitizer::normalizeCharReferences( $text );
1323 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
1324 $text = MWTidy::tidy( $text );
1325 } else {
1326 # attempt to sanitize at least some nesting problems
1327 # (bug #2702 and quite a few others)
1328 $tidyregs = array(
1329 # ''Something [http://www.cool.com cool''] -->
1330 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1331 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1332 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1333 # fix up an anchor inside another anchor, only
1334 # at least for a single single nested link (bug 3695)
1335 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1336 '\\1\\2</a>\\3</a>\\1\\4</a>',
1337 # fix div inside inline elements- doBlockLevels won't wrap a line which
1338 # contains a div, so fix it up here; replace
1339 # div with escaped text
1340 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1341 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
1342 # remove empty italic or bold tag pairs, some
1343 # introduced by rules above
1344 '/<([bi])><\/\\1>/' => '',
1347 $text = preg_replace(
1348 array_keys( $tidyregs ),
1349 array_values( $tidyregs ),
1350 $text );
1353 if ( $isMain ) {
1354 Hooks::run( 'ParserAfterTidy', array( &$this, &$text ) );
1357 return $text;
1361 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1362 * magic external links.
1364 * DML
1365 * @private
1367 * @param string $text
1369 * @return string
1371 public function doMagicLinks( $text ) {
1372 $prots = wfUrlProtocolsWithoutProtRel();
1373 $urlChar = self::EXT_LINK_URL_CLASS;
1374 $space = self::SPACE_NOT_NL; # non-newline space
1375 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1376 $spaces = "$space++"; # possessive match of 1 or more spaces
1377 $text = preg_replace_callback(
1378 '!(?: # Start cases
1379 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1380 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1381 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links
1382 \b(?:RFC|PMID) $spaces # m[4]: RFC or PMID, capture number
1383 ([0-9]+)\b |
1384 \bISBN $spaces ( # m[5]: ISBN, capture number
1385 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1386 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1387 [0-9Xx] # check digit
1389 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1390 return $text;
1394 * @throws MWException
1395 * @param array $m
1396 * @return HTML|string
1398 public function magicLinkCallback( $m ) {
1399 if ( isset( $m[1] ) && $m[1] !== '' ) {
1400 # Skip anchor
1401 return $m[0];
1402 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1403 # Skip HTML element
1404 return $m[0];
1405 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1406 # Free external link
1407 return $this->makeFreeExternalLink( $m[0] );
1408 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1409 # RFC or PMID
1410 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1411 $keyword = 'RFC';
1412 $urlmsg = 'rfcurl';
1413 $cssClass = 'mw-magiclink-rfc';
1414 $id = $m[4];
1415 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1416 $keyword = 'PMID';
1417 $urlmsg = 'pubmedurl';
1418 $cssClass = 'mw-magiclink-pmid';
1419 $id = $m[4];
1420 } else {
1421 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1422 substr( $m[0], 0, 20 ) . '"' );
1424 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1425 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1426 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1427 # ISBN
1428 $isbn = $m[5];
1429 $space = self::SPACE_NOT_NL; # non-newline space
1430 $isbn = preg_replace( "/$space/", ' ', $isbn );
1431 $num = strtr( $isbn, array(
1432 '-' => '',
1433 ' ' => '',
1434 'x' => 'X',
1436 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1437 return '<a href="' .
1438 htmlspecialchars( $titleObj->getLocalURL() ) .
1439 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1440 } else {
1441 return $m[0];
1446 * Make a free external link, given a user-supplied URL
1448 * @param string $url
1450 * @return string HTML
1451 * @private
1453 public function makeFreeExternalLink( $url ) {
1455 $trail = '';
1457 # The characters '<' and '>' (which were escaped by
1458 # removeHTMLtags()) should not be included in
1459 # URLs, per RFC 2396.
1460 $m2 = array();
1461 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1462 $trail = substr( $url, $m2[0][1] ) . $trail;
1463 $url = substr( $url, 0, $m2[0][1] );
1466 # Move trailing punctuation to $trail
1467 $sep = ',;\.:!?';
1468 # If there is no left bracket, then consider right brackets fair game too
1469 if ( strpos( $url, '(' ) === false ) {
1470 $sep .= ')';
1473 $urlRev = strrev( $url );
1474 $numSepChars = strspn( $urlRev, $sep );
1475 # Don't break a trailing HTML entity by moving the ; into $trail
1476 # This is in hot code, so use substr_compare to avoid having to
1477 # create a new string object for the comparison
1478 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1479 # more optimization: instead of running preg_match with a $
1480 # anchor, which can be slow, do the match on the reversed
1481 # string starting at the desired offset.
1482 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1483 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1484 $numSepChars--;
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::normalizeLinkUrl( $url );
1505 $this->mOutput->addExternalLink( $pasteurized );
1507 return $text . $trail;
1511 * Parse headers and return html
1513 * @private
1515 * @param string $text
1517 * @return string
1519 public function doHeadings( $text ) {
1520 for ( $i = 6; $i >= 1; --$i ) {
1521 $h = str_repeat( '=', $i );
1522 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1524 return $text;
1528 * Replace single quotes with HTML markup
1529 * @private
1531 * @param string $text
1533 * @return string The altered text
1535 public function doAllQuotes( $text ) {
1536 $outtext = '';
1537 $lines = StringUtils::explode( "\n", $text );
1538 foreach ( $lines as $line ) {
1539 $outtext .= $this->doQuotes( $line ) . "\n";
1541 $outtext = substr( $outtext, 0, -1 );
1542 return $outtext;
1546 * Helper function for doAllQuotes()
1548 * @param string $text
1550 * @return string
1552 public function doQuotes( $text ) {
1553 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1554 $countarr = count( $arr );
1555 if ( $countarr == 1 ) {
1556 return $text;
1559 // First, do some preliminary work. This may shift some apostrophes from
1560 // being mark-up to being text. It also counts the number of occurrences
1561 // of bold and italics mark-ups.
1562 $numbold = 0;
1563 $numitalics = 0;
1564 for ( $i = 1; $i < $countarr; $i += 2 ) {
1565 $thislen = strlen( $arr[$i] );
1566 // If there are ever four apostrophes, assume the first is supposed to
1567 // be text, and the remaining three constitute mark-up for bold text.
1568 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1569 if ( $thislen == 4 ) {
1570 $arr[$i - 1] .= "'";
1571 $arr[$i] = "'''";
1572 $thislen = 3;
1573 } elseif ( $thislen > 5 ) {
1574 // If there are more than 5 apostrophes in a row, assume they're all
1575 // text except for the last 5.
1576 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1577 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1578 $arr[$i] = "'''''";
1579 $thislen = 5;
1581 // Count the number of occurrences of bold and italics mark-ups.
1582 if ( $thislen == 2 ) {
1583 $numitalics++;
1584 } elseif ( $thislen == 3 ) {
1585 $numbold++;
1586 } elseif ( $thislen == 5 ) {
1587 $numitalics++;
1588 $numbold++;
1592 // If there is an odd number of both bold and italics, it is likely
1593 // that one of the bold ones was meant to be an apostrophe followed
1594 // by italics. Which one we cannot know for certain, but it is more
1595 // likely to be one that has a single-letter word before it.
1596 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1597 $firstsingleletterword = -1;
1598 $firstmultiletterword = -1;
1599 $firstspace = -1;
1600 for ( $i = 1; $i < $countarr; $i += 2 ) {
1601 if ( strlen( $arr[$i] ) == 3 ) {
1602 $x1 = substr( $arr[$i - 1], -1 );
1603 $x2 = substr( $arr[$i - 1], -2, 1 );
1604 if ( $x1 === ' ' ) {
1605 if ( $firstspace == -1 ) {
1606 $firstspace = $i;
1608 } elseif ( $x2 === ' ' ) {
1609 if ( $firstsingleletterword == -1 ) {
1610 $firstsingleletterword = $i;
1611 // if $firstsingleletterword is set, we don't
1612 // look at the other options, so we can bail early.
1613 break;
1615 } else {
1616 if ( $firstmultiletterword == -1 ) {
1617 $firstmultiletterword = $i;
1623 // If there is a single-letter word, use it!
1624 if ( $firstsingleletterword > -1 ) {
1625 $arr[$firstsingleletterword] = "''";
1626 $arr[$firstsingleletterword - 1] .= "'";
1627 } elseif ( $firstmultiletterword > -1 ) {
1628 // If not, but there's a multi-letter word, use that one.
1629 $arr[$firstmultiletterword] = "''";
1630 $arr[$firstmultiletterword - 1] .= "'";
1631 } elseif ( $firstspace > -1 ) {
1632 // ... otherwise use the first one that has neither.
1633 // (notice that it is possible for all three to be -1 if, for example,
1634 // there is only one pentuple-apostrophe in the line)
1635 $arr[$firstspace] = "''";
1636 $arr[$firstspace - 1] .= "'";
1640 // Now let's actually convert our apostrophic mush to HTML!
1641 $output = '';
1642 $buffer = '';
1643 $state = '';
1644 $i = 0;
1645 foreach ( $arr as $r ) {
1646 if ( ( $i % 2 ) == 0 ) {
1647 if ( $state === 'both' ) {
1648 $buffer .= $r;
1649 } else {
1650 $output .= $r;
1652 } else {
1653 $thislen = strlen( $r );
1654 if ( $thislen == 2 ) {
1655 if ( $state === 'i' ) {
1656 $output .= '</i>';
1657 $state = '';
1658 } elseif ( $state === 'bi' ) {
1659 $output .= '</i>';
1660 $state = 'b';
1661 } elseif ( $state === 'ib' ) {
1662 $output .= '</b></i><b>';
1663 $state = 'b';
1664 } elseif ( $state === 'both' ) {
1665 $output .= '<b><i>' . $buffer . '</i>';
1666 $state = 'b';
1667 } else { // $state can be 'b' or ''
1668 $output .= '<i>';
1669 $state .= 'i';
1671 } elseif ( $thislen == 3 ) {
1672 if ( $state === 'b' ) {
1673 $output .= '</b>';
1674 $state = '';
1675 } elseif ( $state === 'bi' ) {
1676 $output .= '</i></b><i>';
1677 $state = 'i';
1678 } elseif ( $state === 'ib' ) {
1679 $output .= '</b>';
1680 $state = 'i';
1681 } elseif ( $state === 'both' ) {
1682 $output .= '<i><b>' . $buffer . '</b>';
1683 $state = 'i';
1684 } else { // $state can be 'i' or ''
1685 $output .= '<b>';
1686 $state .= 'b';
1688 } elseif ( $thislen == 5 ) {
1689 if ( $state === 'b' ) {
1690 $output .= '</b><i>';
1691 $state = 'i';
1692 } elseif ( $state === 'i' ) {
1693 $output .= '</i><b>';
1694 $state = 'b';
1695 } elseif ( $state === 'bi' ) {
1696 $output .= '</i></b>';
1697 $state = '';
1698 } elseif ( $state === 'ib' ) {
1699 $output .= '</b></i>';
1700 $state = '';
1701 } elseif ( $state === 'both' ) {
1702 $output .= '<i><b>' . $buffer . '</b></i>';
1703 $state = '';
1704 } else { // ($state == '')
1705 $buffer = '';
1706 $state = 'both';
1710 $i++;
1712 // Now close all remaining tags. Notice that the order is important.
1713 if ( $state === 'b' || $state === 'ib' ) {
1714 $output .= '</b>';
1716 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1717 $output .= '</i>';
1719 if ( $state === 'bi' ) {
1720 $output .= '</b>';
1722 // There might be lonely ''''', so make sure we have a buffer
1723 if ( $state === 'both' && $buffer ) {
1724 $output .= '<b><i>' . $buffer . '</i></b>';
1726 return $output;
1730 * Replace external links (REL)
1732 * Note: this is all very hackish and the order of execution matters a lot.
1733 * Make sure to run tests/parserTests.php if you change this code.
1735 * @private
1737 * @param string $text
1739 * @throws MWException
1740 * @return string
1742 public function replaceExternalLinks( $text ) {
1744 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1745 if ( $bits === false ) {
1746 throw new MWException( "PCRE needs to be compiled with "
1747 . "--enable-unicode-properties in order for MediaWiki to function" );
1749 $s = array_shift( $bits );
1751 $i = 0;
1752 while ( $i < count( $bits ) ) {
1753 $url = $bits[$i++];
1754 $i++; // protocol
1755 $text = $bits[$i++];
1756 $trail = $bits[$i++];
1758 # The characters '<' and '>' (which were escaped by
1759 # removeHTMLtags()) should not be included in
1760 # URLs, per RFC 2396.
1761 $m2 = array();
1762 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1763 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1764 $url = substr( $url, 0, $m2[0][1] );
1767 # If the link text is an image URL, replace it with an <img> tag
1768 # This happened by accident in the original parser, but some people used it extensively
1769 $img = $this->maybeMakeExternalImage( $text );
1770 if ( $img !== false ) {
1771 $text = $img;
1774 $dtrail = '';
1776 # Set linktype for CSS - if URL==text, link is essentially free
1777 $linktype = ( $text === $url ) ? 'free' : 'text';
1779 # No link text, e.g. [http://domain.tld/some.link]
1780 if ( $text == '' ) {
1781 # Autonumber
1782 $langObj = $this->getTargetLanguage();
1783 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1784 $linktype = 'autonumber';
1785 } else {
1786 # Have link text, e.g. [http://domain.tld/some.link text]s
1787 # Check for trail
1788 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1791 $text = $this->getConverterLanguage()->markNoConversion( $text );
1793 $url = Sanitizer::cleanUrl( $url );
1795 # Use the encoded URL
1796 # This means that users can paste URLs directly into the text
1797 # Funny characters like ö aren't valid in URLs anyway
1798 # This was changed in August 2004
1799 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1800 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1802 # Register link in the output object.
1803 # Replace unnecessary URL escape codes with the referenced character
1804 # This prevents spammers from hiding links from the filters
1805 $pasteurized = self::normalizeLinkUrl( $url );
1806 $this->mOutput->addExternalLink( $pasteurized );
1809 return $s;
1813 * Get the rel attribute for a particular external link.
1815 * @since 1.21
1816 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1817 * nofollow if appropriate
1818 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1819 * @return string|null Rel attribute for $url
1821 public static function getExternalLinkRel( $url = false, $title = null ) {
1822 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1823 $ns = $title ? $title->getNamespace() : false;
1824 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1825 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1827 return 'nofollow';
1829 return null;
1833 * Get an associative array of additional HTML attributes appropriate for a
1834 * particular external link. This currently may include rel => nofollow
1835 * (depending on configuration, namespace, and the URL's domain) and/or a
1836 * target attribute (depending on configuration).
1838 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1839 * nofollow if appropriate
1840 * @return array Associative array of HTML attributes
1842 public function getExternalLinkAttribs( $url = false ) {
1843 $attribs = array();
1844 $attribs['rel'] = self::getExternalLinkRel( $url, $this->mTitle );
1846 if ( $this->mOptions->getExternalLinkTarget() ) {
1847 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1849 return $attribs;
1853 * Replace unusual escape codes in a URL with their equivalent characters
1855 * @deprecated since 1.24, use normalizeLinkUrl
1856 * @param string $url
1857 * @return string
1859 public static function replaceUnusualEscapes( $url ) {
1860 wfDeprecated( __METHOD__, '1.24' );
1861 return self::normalizeLinkUrl( $url );
1865 * Replace unusual escape codes in a URL with their equivalent characters
1867 * This generally follows the syntax defined in RFC 3986, with special
1868 * consideration for HTTP query strings.
1870 * @param string $url
1871 * @return string
1873 public static function normalizeLinkUrl( $url ) {
1874 # First, make sure unsafe characters are encoded
1875 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1876 function ( $m ) {
1877 return rawurlencode( $m[0] );
1879 $url
1882 $ret = '';
1883 $end = strlen( $url );
1885 # Fragment part - 'fragment'
1886 $start = strpos( $url, '#' );
1887 if ( $start !== false && $start < $end ) {
1888 $ret = self::normalizeUrlComponent(
1889 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1890 $end = $start;
1893 # Query part - 'query' minus &=+;
1894 $start = strpos( $url, '?' );
1895 if ( $start !== false && $start < $end ) {
1896 $ret = self::normalizeUrlComponent(
1897 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1898 $end = $start;
1901 # Scheme and path part - 'pchar'
1902 # (we assume no userinfo or encoded colons in the host)
1903 $ret = self::normalizeUrlComponent(
1904 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1906 return $ret;
1909 private static function normalizeUrlComponent( $component, $unsafe ) {
1910 $callback = function ( $matches ) use ( $unsafe ) {
1911 $char = urldecode( $matches[0] );
1912 $ord = ord( $char );
1913 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1914 # Unescape it
1915 return $char;
1916 } else {
1917 # Leave it escaped, but use uppercase for a-f
1918 return strtoupper( $matches[0] );
1921 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1925 * make an image if it's allowed, either through the global
1926 * option, through the exception, or through the on-wiki whitelist
1928 * @param string $url
1930 * @return string
1932 private function maybeMakeExternalImage( $url ) {
1933 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1934 $imagesexception = !empty( $imagesfrom );
1935 $text = false;
1936 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1937 if ( $imagesexception && is_array( $imagesfrom ) ) {
1938 $imagematch = false;
1939 foreach ( $imagesfrom as $match ) {
1940 if ( strpos( $url, $match ) === 0 ) {
1941 $imagematch = true;
1942 break;
1945 } elseif ( $imagesexception ) {
1946 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1947 } else {
1948 $imagematch = false;
1951 if ( $this->mOptions->getAllowExternalImages()
1952 || ( $imagesexception && $imagematch )
1954 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1955 # Image found
1956 $text = Linker::makeExternalImage( $url );
1959 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1960 && preg_match( self::EXT_IMAGE_REGEX, $url )
1962 $whitelist = explode(
1963 "\n",
1964 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1967 foreach ( $whitelist as $entry ) {
1968 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1969 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
1970 continue;
1972 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1973 # Image matches a whitelist entry
1974 $text = Linker::makeExternalImage( $url );
1975 break;
1979 return $text;
1983 * Process [[ ]] wikilinks
1985 * @param string $s
1987 * @return string Processed text
1989 * @private
1991 public function replaceInternalLinks( $s ) {
1992 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1993 return $s;
1997 * Process [[ ]] wikilinks (RIL)
1998 * @param string $s
1999 * @throws MWException
2000 * @return LinkHolderArray
2002 * @private
2004 public function replaceInternalLinks2( &$s ) {
2005 global $wgExtraInterlanguageLinkPrefixes;
2007 static $tc = false, $e1, $e1_img;
2008 # the % is needed to support urlencoded titles as well
2009 if ( !$tc ) {
2010 $tc = Title::legalChars() . '#%';
2011 # Match a link having the form [[namespace:link|alternate]]trail
2012 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2013 # Match cases where there is no "]]", which might still be images
2014 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2017 $holders = new LinkHolderArray( $this );
2019 # split the entire text string on occurrences of [[
2020 $a = StringUtils::explode( '[[', ' ' . $s );
2021 # get the first element (all text up to first [[), and remove the space we added
2022 $s = $a->current();
2023 $a->next();
2024 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2025 $s = substr( $s, 1 );
2027 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2028 $e2 = null;
2029 if ( $useLinkPrefixExtension ) {
2030 # Match the end of a line for a word that's not followed by whitespace,
2031 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2032 global $wgContLang;
2033 $charset = $wgContLang->linkPrefixCharset();
2034 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2037 if ( is_null( $this->mTitle ) ) {
2038 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2040 $nottalk = !$this->mTitle->isTalkPage();
2042 if ( $useLinkPrefixExtension ) {
2043 $m = array();
2044 if ( preg_match( $e2, $s, $m ) ) {
2045 $first_prefix = $m[2];
2046 } else {
2047 $first_prefix = false;
2049 } else {
2050 $prefix = '';
2053 $useSubpages = $this->areSubpagesAllowed();
2055 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2056 # Loop for each link
2057 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2058 // @codingStandardsIgnoreStart
2060 # Check for excessive memory usage
2061 if ( $holders->isBig() ) {
2062 # Too big
2063 # Do the existence check, replace the link holders and clear the array
2064 $holders->replace( $s );
2065 $holders->clear();
2068 if ( $useLinkPrefixExtension ) {
2069 if ( preg_match( $e2, $s, $m ) ) {
2070 $prefix = $m[2];
2071 $s = $m[1];
2072 } else {
2073 $prefix = '';
2075 # first link
2076 if ( $first_prefix ) {
2077 $prefix = $first_prefix;
2078 $first_prefix = false;
2082 $might_be_img = false;
2084 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2085 $text = $m[2];
2086 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2087 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2088 # the real problem is with the $e1 regex
2089 # See bug 1300.
2091 # Still some problems for cases where the ] is meant to be outside punctuation,
2092 # and no image is in sight. See bug 2095.
2094 if ( $text !== ''
2095 && substr( $m[3], 0, 1 ) === ']'
2096 && strpos( $text, '[' ) !== false
2098 $text .= ']'; # so that replaceExternalLinks($text) works later
2099 $m[3] = substr( $m[3], 1 );
2101 # fix up urlencoded title texts
2102 if ( strpos( $m[1], '%' ) !== false ) {
2103 # Should anchors '#' also be rejected?
2104 $m[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $m[1] ) );
2106 $trail = $m[3];
2107 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2108 # Invalid, but might be an image with a link in its caption
2109 $might_be_img = true;
2110 $text = $m[2];
2111 if ( strpos( $m[1], '%' ) !== false ) {
2112 $m[1] = rawurldecode( $m[1] );
2114 $trail = "";
2115 } else { # Invalid form; output directly
2116 $s .= $prefix . '[[' . $line;
2117 continue;
2120 $origLink = $m[1];
2122 # Don't allow internal links to pages containing
2123 # PROTO: where PROTO is a valid URL protocol; these
2124 # should be external links.
2125 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) {
2126 $s .= $prefix . '[[' . $line;
2127 continue;
2130 # Make subpage if necessary
2131 if ( $useSubpages ) {
2132 $link = $this->maybeDoSubpageLink( $origLink, $text );
2133 } else {
2134 $link = $origLink;
2137 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2138 if ( !$noforce ) {
2139 # Strip off leading ':'
2140 $link = substr( $link, 1 );
2143 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
2144 if ( $nt === null ) {
2145 $s .= $prefix . '[[' . $line;
2146 continue;
2149 $ns = $nt->getNamespace();
2150 $iw = $nt->getInterwiki();
2152 if ( $might_be_img ) { # if this is actually an invalid link
2153 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2154 $found = false;
2155 while ( true ) {
2156 # look at the next 'line' to see if we can close it there
2157 $a->next();
2158 $next_line = $a->current();
2159 if ( $next_line === false || $next_line === null ) {
2160 break;
2162 $m = explode( ']]', $next_line, 3 );
2163 if ( count( $m ) == 3 ) {
2164 # the first ]] closes the inner link, the second the image
2165 $found = true;
2166 $text .= "[[{$m[0]}]]{$m[1]}";
2167 $trail = $m[2];
2168 break;
2169 } elseif ( count( $m ) == 2 ) {
2170 # if there's exactly one ]] that's fine, we'll keep looking
2171 $text .= "[[{$m[0]}]]{$m[1]}";
2172 } else {
2173 # if $next_line is invalid too, we need look no further
2174 $text .= '[[' . $next_line;
2175 break;
2178 if ( !$found ) {
2179 # we couldn't find the end of this imageLink, so output it raw
2180 # but don't ignore what might be perfectly normal links in the text we've examined
2181 $holders->merge( $this->replaceInternalLinks2( $text ) );
2182 $s .= "{$prefix}[[$link|$text";
2183 # note: no $trail, because without an end, there *is* no trail
2184 continue;
2186 } else { # it's not an image, so output it raw
2187 $s .= "{$prefix}[[$link|$text";
2188 # note: no $trail, because without an end, there *is* no trail
2189 continue;
2193 $wasblank = ( $text == '' );
2194 if ( $wasblank ) {
2195 $text = $link;
2196 } else {
2197 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2198 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2199 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2200 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2201 $text = $this->doQuotes( $text );
2204 # Link not escaped by : , create the various objects
2205 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2206 # Interwikis
2207 if (
2208 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2209 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2210 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2213 # Bug 24502: filter duplicates
2214 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2215 $this->mLangLinkLanguages[$iw] = true;
2216 $this->mOutput->addLanguageLink( $nt->getFullText() );
2219 $s = rtrim( $s . $prefix );
2220 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2221 continue;
2224 if ( $ns == NS_FILE ) {
2225 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2226 if ( $wasblank ) {
2227 # if no parameters were passed, $text
2228 # becomes something like "File:Foo.png",
2229 # which we don't want to pass on to the
2230 # image generator
2231 $text = '';
2232 } else {
2233 # recursively parse links inside the image caption
2234 # actually, this will parse them in any other parameters, too,
2235 # but it might be hard to fix that, and it doesn't matter ATM
2236 $text = $this->replaceExternalLinks( $text );
2237 $holders->merge( $this->replaceInternalLinks2( $text ) );
2239 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2240 $s .= $prefix . $this->armorLinks(
2241 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2242 } else {
2243 $s .= $prefix . $trail;
2245 continue;
2248 if ( $ns == NS_CATEGORY ) {
2249 $s = rtrim( $s . "\n" ); # bug 87
2251 if ( $wasblank ) {
2252 $sortkey = $this->getDefaultSort();
2253 } else {
2254 $sortkey = $text;
2256 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2257 $sortkey = str_replace( "\n", '', $sortkey );
2258 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2259 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2262 * Strip the whitespace Category links produce, see bug 87
2264 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2266 continue;
2270 # Self-link checking. For some languages, variants of the title are checked in
2271 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2272 # for linking to a different variant.
2273 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2274 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2275 continue;
2278 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2279 # @todo FIXME: Should do batch file existence checks, see comment below
2280 if ( $ns == NS_MEDIA ) {
2281 # Give extensions a chance to select the file revision for us
2282 $options = array();
2283 $descQuery = false;
2284 Hooks::run( 'BeforeParserFetchFileAndTitle',
2285 array( $this, $nt, &$options, &$descQuery ) );
2286 # Fetch and register the file (file title may be different via hooks)
2287 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2288 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2289 $s .= $prefix . $this->armorLinks(
2290 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2291 continue;
2294 # Some titles, such as valid special pages or files in foreign repos, should
2295 # be shown as bluelinks even though they're not included in the page table
2297 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2298 # batch file existence checks for NS_FILE and NS_MEDIA
2299 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2300 $this->mOutput->addLink( $nt );
2301 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2302 } else {
2303 # Links will be added to the output link list after checking
2304 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2307 return $holders;
2311 * Render a forced-blue link inline; protect against double expansion of
2312 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2313 * Since this little disaster has to split off the trail text to avoid
2314 * breaking URLs in the following text without breaking trails on the
2315 * wiki links, it's been made into a horrible function.
2317 * @param Title $nt
2318 * @param string $text
2319 * @param array|string $query
2320 * @param string $trail
2321 * @param string $prefix
2322 * @return string HTML-wikitext mix oh yuck
2324 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2325 list( $inside, $trail ) = Linker::splitTrail( $trail );
2327 if ( is_string( $query ) ) {
2328 $query = wfCgiToArray( $query );
2330 if ( $text == '' ) {
2331 $text = htmlspecialchars( $nt->getPrefixedText() );
2334 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2336 return $this->armorLinks( $link ) . $trail;
2340 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2341 * going to go through further parsing steps before inline URL expansion.
2343 * Not needed quite as much as it used to be since free links are a bit
2344 * more sensible these days. But bracketed links are still an issue.
2346 * @param string $text More-or-less HTML
2347 * @return string Less-or-more HTML with NOPARSE bits
2349 public function armorLinks( $text ) {
2350 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2351 "{$this->mUniqPrefix}NOPARSE$1", $text );
2355 * Return true if subpage links should be expanded on this page.
2356 * @return bool
2358 public function areSubpagesAllowed() {
2359 # Some namespaces don't allow subpages
2360 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2364 * Handle link to subpage if necessary
2366 * @param string $target The source of the link
2367 * @param string &$text The link text, modified as necessary
2368 * @return string The full name of the link
2369 * @private
2371 public function maybeDoSubpageLink( $target, &$text ) {
2372 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2375 /**#@+
2376 * Used by doBlockLevels()
2377 * @private
2379 * @return string
2381 public function closeParagraph() {
2382 $result = '';
2383 if ( $this->mLastSection != '' ) {
2384 $result = '</' . $this->mLastSection . ">\n";
2386 $this->mInPre = false;
2387 $this->mLastSection = '';
2388 return $result;
2392 * getCommon() returns the length of the longest common substring
2393 * of both arguments, starting at the beginning of both.
2394 * @private
2396 * @param string $st1
2397 * @param string $st2
2399 * @return int
2401 public function getCommon( $st1, $st2 ) {
2402 $fl = strlen( $st1 );
2403 $shorter = strlen( $st2 );
2404 if ( $fl < $shorter ) {
2405 $shorter = $fl;
2408 for ( $i = 0; $i < $shorter; ++$i ) {
2409 if ( $st1[$i] != $st2[$i] ) {
2410 break;
2413 return $i;
2417 * These next three functions open, continue, and close the list
2418 * element appropriate to the prefix character passed into them.
2419 * @private
2421 * @param string $char
2423 * @return string
2425 public function openList( $char ) {
2426 $result = $this->closeParagraph();
2428 if ( '*' === $char ) {
2429 $result .= "<ul><li>";
2430 } elseif ( '#' === $char ) {
2431 $result .= "<ol><li>";
2432 } elseif ( ':' === $char ) {
2433 $result .= "<dl><dd>";
2434 } elseif ( ';' === $char ) {
2435 $result .= "<dl><dt>";
2436 $this->mDTopen = true;
2437 } else {
2438 $result = '<!-- ERR 1 -->';
2441 return $result;
2445 * TODO: document
2446 * @param string $char
2447 * @private
2449 * @return string
2451 public function nextItem( $char ) {
2452 if ( '*' === $char || '#' === $char ) {
2453 return "</li>\n<li>";
2454 } elseif ( ':' === $char || ';' === $char ) {
2455 $close = "</dd>\n";
2456 if ( $this->mDTopen ) {
2457 $close = "</dt>\n";
2459 if ( ';' === $char ) {
2460 $this->mDTopen = true;
2461 return $close . '<dt>';
2462 } else {
2463 $this->mDTopen = false;
2464 return $close . '<dd>';
2467 return '<!-- ERR 2 -->';
2471 * @todo Document
2472 * @param string $char
2473 * @private
2475 * @return string
2477 public function closeList( $char ) {
2478 if ( '*' === $char ) {
2479 $text = "</li></ul>";
2480 } elseif ( '#' === $char ) {
2481 $text = "</li></ol>";
2482 } elseif ( ':' === $char ) {
2483 if ( $this->mDTopen ) {
2484 $this->mDTopen = false;
2485 $text = "</dt></dl>";
2486 } else {
2487 $text = "</dd></dl>";
2489 } else {
2490 return '<!-- ERR 3 -->';
2492 return $text;
2494 /**#@-*/
2497 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2499 * @param string $text
2500 * @param bool $linestart Whether or not this is at the start of a line.
2501 * @private
2502 * @return string The lists rendered as HTML
2504 public function doBlockLevels( $text, $linestart ) {
2506 # Parsing through the text line by line. The main thing
2507 # happening here is handling of block-level elements p, pre,
2508 # and making lists from lines starting with * # : etc.
2510 $textLines = StringUtils::explode( "\n", $text );
2512 $lastPrefix = $output = '';
2513 $this->mDTopen = $inBlockElem = false;
2514 $prefixLength = 0;
2515 $paragraphStack = false;
2516 $inBlockquote = false;
2518 foreach ( $textLines as $oLine ) {
2519 # Fix up $linestart
2520 if ( !$linestart ) {
2521 $output .= $oLine;
2522 $linestart = true;
2523 continue;
2525 # * = ul
2526 # # = ol
2527 # ; = dt
2528 # : = dd
2530 $lastPrefixLength = strlen( $lastPrefix );
2531 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2532 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2533 # If not in a <pre> element, scan for and figure out what prefixes are there.
2534 if ( !$this->mInPre ) {
2535 # Multiple prefixes may abut each other for nested lists.
2536 $prefixLength = strspn( $oLine, '*#:;' );
2537 $prefix = substr( $oLine, 0, $prefixLength );
2539 # eh?
2540 # ; and : are both from definition-lists, so they're equivalent
2541 # for the purposes of determining whether or not we need to open/close
2542 # elements.
2543 $prefix2 = str_replace( ';', ':', $prefix );
2544 $t = substr( $oLine, $prefixLength );
2545 $this->mInPre = (bool)$preOpenMatch;
2546 } else {
2547 # Don't interpret any other prefixes in preformatted text
2548 $prefixLength = 0;
2549 $prefix = $prefix2 = '';
2550 $t = $oLine;
2553 # List generation
2554 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2555 # Same as the last item, so no need to deal with nesting or opening stuff
2556 $output .= $this->nextItem( substr( $prefix, -1 ) );
2557 $paragraphStack = false;
2559 if ( substr( $prefix, -1 ) === ';' ) {
2560 # The one nasty exception: definition lists work like this:
2561 # ; title : definition text
2562 # So we check for : in the remainder text to split up the
2563 # title and definition, without b0rking links.
2564 $term = $t2 = '';
2565 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2566 $t = $t2;
2567 $output .= $term . $this->nextItem( ':' );
2570 } elseif ( $prefixLength || $lastPrefixLength ) {
2571 # We need to open or close prefixes, or both.
2573 # Either open or close a level...
2574 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2575 $paragraphStack = false;
2577 # Close all the prefixes which aren't shared.
2578 while ( $commonPrefixLength < $lastPrefixLength ) {
2579 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2580 --$lastPrefixLength;
2583 # Continue the current prefix if appropriate.
2584 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2585 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2588 # Open prefixes where appropriate.
2589 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2590 $output .= "\n";
2592 while ( $prefixLength > $commonPrefixLength ) {
2593 $char = substr( $prefix, $commonPrefixLength, 1 );
2594 $output .= $this->openList( $char );
2596 if ( ';' === $char ) {
2597 # @todo FIXME: This is dupe of code above
2598 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2599 $t = $t2;
2600 $output .= $term . $this->nextItem( ':' );
2603 ++$commonPrefixLength;
2605 if ( !$prefixLength && $lastPrefix ) {
2606 $output .= "\n";
2608 $lastPrefix = $prefix2;
2611 # If we have no prefixes, go to paragraph mode.
2612 if ( 0 == $prefixLength ) {
2613 # No prefix (not in list)--go to paragraph mode
2614 # XXX: use a stack for nestable elements like span, table and div
2615 $openmatch = preg_match(
2616 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2617 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2620 $closematch = preg_match(
2621 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2622 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2623 . $this->mUniqPrefix
2624 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2628 if ( $openmatch || $closematch ) {
2629 $paragraphStack = false;
2630 # @todo bug 5718: paragraph closed
2631 $output .= $this->closeParagraph();
2632 if ( $preOpenMatch && !$preCloseMatch ) {
2633 $this->mInPre = true;
2635 $bqOffset = 0;
2636 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset ) ) {
2637 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2638 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
2640 $inBlockElem = !$closematch;
2641 } elseif ( !$inBlockElem && !$this->mInPre ) {
2642 if ( ' ' == substr( $t, 0, 1 )
2643 && ( $this->mLastSection === 'pre' || trim( $t ) != '' )
2644 && !$inBlockquote
2646 # pre
2647 if ( $this->mLastSection !== 'pre' ) {
2648 $paragraphStack = false;
2649 $output .= $this->closeParagraph() . '<pre>';
2650 $this->mLastSection = 'pre';
2652 $t = substr( $t, 1 );
2653 } else {
2654 # paragraph
2655 if ( trim( $t ) === '' ) {
2656 if ( $paragraphStack ) {
2657 $output .= $paragraphStack . '<br />';
2658 $paragraphStack = false;
2659 $this->mLastSection = 'p';
2660 } else {
2661 if ( $this->mLastSection !== 'p' ) {
2662 $output .= $this->closeParagraph();
2663 $this->mLastSection = '';
2664 $paragraphStack = '<p>';
2665 } else {
2666 $paragraphStack = '</p><p>';
2669 } else {
2670 if ( $paragraphStack ) {
2671 $output .= $paragraphStack;
2672 $paragraphStack = false;
2673 $this->mLastSection = 'p';
2674 } elseif ( $this->mLastSection !== 'p' ) {
2675 $output .= $this->closeParagraph() . '<p>';
2676 $this->mLastSection = 'p';
2682 # somewhere above we forget to get out of pre block (bug 785)
2683 if ( $preCloseMatch && $this->mInPre ) {
2684 $this->mInPre = false;
2686 if ( $paragraphStack === false ) {
2687 $output .= $t;
2688 if ( $prefixLength === 0 ) {
2689 $output .= "\n";
2693 while ( $prefixLength ) {
2694 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2695 --$prefixLength;
2696 if ( !$prefixLength ) {
2697 $output .= "\n";
2700 if ( $this->mLastSection != '' ) {
2701 $output .= '</' . $this->mLastSection . '>';
2702 $this->mLastSection = '';
2705 return $output;
2709 * Split up a string on ':', ignoring any occurrences inside tags
2710 * to prevent illegal overlapping.
2712 * @param string $str The string to split
2713 * @param string &$before Set to everything before the ':'
2714 * @param string &$after Set to everything after the ':'
2715 * @throws MWException
2716 * @return string The position of the ':', or false if none found
2718 public function findColonNoLinks( $str, &$before, &$after ) {
2720 $pos = strpos( $str, ':' );
2721 if ( $pos === false ) {
2722 # Nothing to find!
2723 return false;
2726 $lt = strpos( $str, '<' );
2727 if ( $lt === false || $lt > $pos ) {
2728 # Easy; no tag nesting to worry about
2729 $before = substr( $str, 0, $pos );
2730 $after = substr( $str, $pos + 1 );
2731 return $pos;
2734 # Ugly state machine to walk through avoiding tags.
2735 $state = self::COLON_STATE_TEXT;
2736 $stack = 0;
2737 $len = strlen( $str );
2738 for ( $i = 0; $i < $len; $i++ ) {
2739 $c = $str[$i];
2741 switch ( $state ) {
2742 # (Using the number is a performance hack for common cases)
2743 case 0: # self::COLON_STATE_TEXT:
2744 switch ( $c ) {
2745 case "<":
2746 # Could be either a <start> tag or an </end> tag
2747 $state = self::COLON_STATE_TAGSTART;
2748 break;
2749 case ":":
2750 if ( $stack == 0 ) {
2751 # We found it!
2752 $before = substr( $str, 0, $i );
2753 $after = substr( $str, $i + 1 );
2754 return $i;
2756 # Embedded in a tag; don't break it.
2757 break;
2758 default:
2759 # Skip ahead looking for something interesting
2760 $colon = strpos( $str, ':', $i );
2761 if ( $colon === false ) {
2762 # Nothing else interesting
2763 return false;
2765 $lt = strpos( $str, '<', $i );
2766 if ( $stack === 0 ) {
2767 if ( $lt === false || $colon < $lt ) {
2768 # We found it!
2769 $before = substr( $str, 0, $colon );
2770 $after = substr( $str, $colon + 1 );
2771 return $i;
2774 if ( $lt === false ) {
2775 # Nothing else interesting to find; abort!
2776 # We're nested, but there's no close tags left. Abort!
2777 break 2;
2779 # Skip ahead to next tag start
2780 $i = $lt;
2781 $state = self::COLON_STATE_TAGSTART;
2783 break;
2784 case 1: # self::COLON_STATE_TAG:
2785 # In a <tag>
2786 switch ( $c ) {
2787 case ">":
2788 $stack++;
2789 $state = self::COLON_STATE_TEXT;
2790 break;
2791 case "/":
2792 # Slash may be followed by >?
2793 $state = self::COLON_STATE_TAGSLASH;
2794 break;
2795 default:
2796 # ignore
2798 break;
2799 case 2: # self::COLON_STATE_TAGSTART:
2800 switch ( $c ) {
2801 case "/":
2802 $state = self::COLON_STATE_CLOSETAG;
2803 break;
2804 case "!":
2805 $state = self::COLON_STATE_COMMENT;
2806 break;
2807 case ">":
2808 # Illegal early close? This shouldn't happen D:
2809 $state = self::COLON_STATE_TEXT;
2810 break;
2811 default:
2812 $state = self::COLON_STATE_TAG;
2814 break;
2815 case 3: # self::COLON_STATE_CLOSETAG:
2816 # In a </tag>
2817 if ( $c === ">" ) {
2818 $stack--;
2819 if ( $stack < 0 ) {
2820 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
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 throw new MWException( "State machine error in " . __METHOD__ );
2858 if ( $stack > 0 ) {
2859 wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2860 return false;
2862 return false;
2866 * Return value of a magic variable (like PAGENAME)
2868 * @private
2870 * @param int $index
2871 * @param bool|PPFrame $frame
2873 * @throws MWException
2874 * @return string
2876 public function getVariableValue( $index, $frame = false ) {
2877 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2878 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2880 if ( is_null( $this->mTitle ) ) {
2881 // If no title set, bad things are going to happen
2882 // later. Title should always be set since this
2883 // should only be called in the middle of a parse
2884 // operation (but the unit-tests do funky stuff)
2885 throw new MWException( __METHOD__ . ' Should only be '
2886 . ' called while parsing (no title set)' );
2890 * Some of these require message or data lookups and can be
2891 * expensive to check many times.
2893 if ( Hooks::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2894 if ( isset( $this->mVarCache[$index] ) ) {
2895 return $this->mVarCache[$index];
2899 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2900 Hooks::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2902 $pageLang = $this->getFunctionLang();
2904 switch ( $index ) {
2905 case '!':
2906 $value = '|';
2907 break;
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 'currenttimestamp':
3178 $value = wfTimestamp( TS_MW, $ts );
3179 break;
3180 case 'localtimestamp':
3181 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
3182 break;
3183 case 'currentversion':
3184 $value = SpecialVersion::getVersion();
3185 break;
3186 case 'articlepath':
3187 return $wgArticlePath;
3188 case 'sitename':
3189 return $wgSitename;
3190 case 'server':
3191 return $wgServer;
3192 case 'servername':
3193 return $wgServerName;
3194 case 'scriptpath':
3195 return $wgScriptPath;
3196 case 'stylepath':
3197 return $wgStylePath;
3198 case 'directionmark':
3199 return $pageLang->getDirMark();
3200 case 'contentlanguage':
3201 global $wgLanguageCode;
3202 return $wgLanguageCode;
3203 case 'cascadingsources':
3204 $value = CoreParserFunctions::cascadingsources( $this );
3205 break;
3206 default:
3207 $ret = null;
3208 Hooks::run(
3209 'ParserGetVariableValueSwitch',
3210 array( &$this, &$this->mVarCache, &$index, &$ret, &$frame )
3213 return $ret;
3216 if ( $index ) {
3217 $this->mVarCache[$index] = $value;
3220 return $value;
3224 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3226 * @private
3228 public function initialiseVariables() {
3229 $variableIDs = MagicWord::getVariableIDs();
3230 $substIDs = MagicWord::getSubstIDs();
3232 $this->mVariables = new MagicWordArray( $variableIDs );
3233 $this->mSubstWords = new MagicWordArray( $substIDs );
3237 * Preprocess some wikitext and return the document tree.
3238 * This is the ghost of replace_variables().
3240 * @param string $text The text to parse
3241 * @param int $flags Bitwise combination of:
3242 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3243 * included. Default is to assume a direct page view.
3245 * The generated DOM tree must depend only on the input text and the flags.
3246 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3248 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3249 * change in the DOM tree for a given text, must be passed through the section identifier
3250 * in the section edit link and thus back to extractSections().
3252 * The output of this function is currently only cached in process memory, but a persistent
3253 * cache may be implemented at a later date which takes further advantage of these strict
3254 * dependency requirements.
3256 * @return PPNode
3258 public function preprocessToDom( $text, $flags = 0 ) {
3259 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3260 return $dom;
3264 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3266 * @param string $s
3268 * @return array
3270 public static function splitWhitespace( $s ) {
3271 $ltrimmed = ltrim( $s );
3272 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3273 $trimmed = rtrim( $ltrimmed );
3274 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3275 if ( $diff > 0 ) {
3276 $w2 = substr( $ltrimmed, -$diff );
3277 } else {
3278 $w2 = '';
3280 return array( $w1, $trimmed, $w2 );
3284 * Replace magic variables, templates, and template arguments
3285 * with the appropriate text. Templates are substituted recursively,
3286 * taking care to avoid infinite loops.
3288 * Note that the substitution depends on value of $mOutputType:
3289 * self::OT_WIKI: only {{subst:}} templates
3290 * self::OT_PREPROCESS: templates but not extension tags
3291 * self::OT_HTML: all templates and extension tags
3293 * @param string $text The text to transform
3294 * @param bool|PPFrame $frame Object describing the arguments passed to the
3295 * template. Arguments may also be provided as an associative array, as
3296 * was the usual case before MW1.12. Providing arguments this way may be
3297 * useful for extensions wishing to perform variable replacement
3298 * explicitly.
3299 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3300 * double-brace expansion.
3301 * @return string
3303 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3304 # Is there any text? Also, Prevent too big inclusions!
3305 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3306 return $text;
3309 if ( $frame === false ) {
3310 $frame = $this->getPreprocessor()->newFrame();
3311 } elseif ( !( $frame instanceof PPFrame ) ) {
3312 wfDebug( __METHOD__ . " called using plain parameters instead of "
3313 . "a PPFrame instance. Creating custom frame.\n" );
3314 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3317 $dom = $this->preprocessToDom( $text );
3318 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3319 $text = $frame->expand( $dom, $flags );
3321 return $text;
3325 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3327 * @param array $args
3329 * @return array
3331 public static function createAssocArgs( $args ) {
3332 $assocArgs = array();
3333 $index = 1;
3334 foreach ( $args as $arg ) {
3335 $eqpos = strpos( $arg, '=' );
3336 if ( $eqpos === false ) {
3337 $assocArgs[$index++] = $arg;
3338 } else {
3339 $name = trim( substr( $arg, 0, $eqpos ) );
3340 $value = trim( substr( $arg, $eqpos + 1 ) );
3341 if ( $value === false ) {
3342 $value = '';
3344 if ( $name !== false ) {
3345 $assocArgs[$name] = $value;
3350 return $assocArgs;
3354 * Warn the user when a parser limitation is reached
3355 * Will warn at most once the user per limitation type
3357 * @param string $limitationType Should be one of:
3358 * 'expensive-parserfunction' (corresponding messages:
3359 * 'expensive-parserfunction-warning',
3360 * 'expensive-parserfunction-category')
3361 * 'post-expand-template-argument' (corresponding messages:
3362 * 'post-expand-template-argument-warning',
3363 * 'post-expand-template-argument-category')
3364 * 'post-expand-template-inclusion' (corresponding messages:
3365 * 'post-expand-template-inclusion-warning',
3366 * 'post-expand-template-inclusion-category')
3367 * 'node-count-exceeded' (corresponding messages:
3368 * 'node-count-exceeded-warning',
3369 * 'node-count-exceeded-category')
3370 * 'expansion-depth-exceeded' (corresponding messages:
3371 * 'expansion-depth-exceeded-warning',
3372 * 'expansion-depth-exceeded-category')
3373 * @param string|int|null $current Current value
3374 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3375 * exceeded, provide the values (optional)
3377 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3378 # does no harm if $current and $max are present but are unnecessary for the message
3379 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3380 ->inLanguage( $this->mOptions->getUserLangObj() )->text();
3381 $this->mOutput->addWarning( $warning );
3382 $this->addTrackingCategory( "$limitationType-category" );
3386 * Return the text of a template, after recursively
3387 * replacing any variables or templates within the template.
3389 * @param array $piece The parts of the template
3390 * $piece['title']: the title, i.e. the part before the |
3391 * $piece['parts']: the parameter array
3392 * $piece['lineStart']: whether the brace was at the start of a line
3393 * @param PPFrame $frame The current frame, contains template arguments
3394 * @throws Exception
3395 * @return string The text of the template
3397 public function braceSubstitution( $piece, $frame ) {
3399 // Flags
3401 // $text has been filled
3402 $found = false;
3403 // wiki markup in $text should be escaped
3404 $nowiki = false;
3405 // $text is HTML, armour it against wikitext transformation
3406 $isHTML = false;
3407 // Force interwiki transclusion to be done in raw mode not rendered
3408 $forceRawInterwiki = false;
3409 // $text is a DOM node needing expansion in a child frame
3410 $isChildObj = false;
3411 // $text is a DOM node needing expansion in the current frame
3412 $isLocalObj = false;
3414 # Title object, where $text came from
3415 $title = false;
3417 # $part1 is the bit before the first |, and must contain only title characters.
3418 # Various prefixes will be stripped from it later.
3419 $titleWithSpaces = $frame->expand( $piece['title'] );
3420 $part1 = trim( $titleWithSpaces );
3421 $titleText = false;
3423 # Original title text preserved for various purposes
3424 $originalTitle = $part1;
3426 # $args is a list of argument nodes, starting from index 0, not including $part1
3427 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3428 # below won't work b/c this $args isn't an object
3429 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3431 $profileSection = null; // profile templates
3433 # SUBST
3434 if ( !$found ) {
3436 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3438 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3439 # Decide whether to expand template or keep wikitext as-is.
3440 if ( $this->ot['wiki'] ) {
3441 if ( $substMatch === false ) {
3442 $literal = true; # literal when in PST with no prefix
3443 } else {
3444 $literal = false; # expand when in PST with subst: or safesubst:
3446 } else {
3447 if ( $substMatch == 'subst' ) {
3448 $literal = true; # literal when not in PST with plain subst:
3449 } else {
3450 $literal = false; # expand when not in PST with safesubst: or no prefix
3453 if ( $literal ) {
3454 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3455 $isLocalObj = true;
3456 $found = true;
3460 # Variables
3461 if ( !$found && $args->getLength() == 0 ) {
3462 $id = $this->mVariables->matchStartToEnd( $part1 );
3463 if ( $id !== false ) {
3464 $text = $this->getVariableValue( $id, $frame );
3465 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3466 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3468 $found = true;
3472 # MSG, MSGNW and RAW
3473 if ( !$found ) {
3474 # Check for MSGNW:
3475 $mwMsgnw = MagicWord::get( 'msgnw' );
3476 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3477 $nowiki = true;
3478 } else {
3479 # Remove obsolete MSG:
3480 $mwMsg = MagicWord::get( 'msg' );
3481 $mwMsg->matchStartAndRemove( $part1 );
3484 # Check for RAW:
3485 $mwRaw = MagicWord::get( 'raw' );
3486 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3487 $forceRawInterwiki = true;
3491 # Parser functions
3492 if ( !$found ) {
3494 $colonPos = strpos( $part1, ':' );
3495 if ( $colonPos !== false ) {
3496 $func = substr( $part1, 0, $colonPos );
3497 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3498 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3499 $funcArgs[] = $args->item( $i );
3501 try {
3502 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3503 } catch ( Exception $ex ) {
3504 throw $ex;
3507 # The interface for parser functions allows for extracting
3508 # flags into the local scope. Extract any forwarded flags
3509 # here.
3510 extract( $result );
3514 # Finish mangling title and then check for loops.
3515 # Set $title to a Title object and $titleText to the PDBK
3516 if ( !$found ) {
3517 $ns = NS_TEMPLATE;
3518 # Split the title into page and subpage
3519 $subpage = '';
3520 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3521 if ( $part1 !== $relative ) {
3522 $part1 = $relative;
3523 $ns = $this->mTitle->getNamespace();
3525 $title = Title::newFromText( $part1, $ns );
3526 if ( $title ) {
3527 $titleText = $title->getPrefixedText();
3528 # Check for language variants if the template is not found
3529 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3530 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3532 # Do recursion depth check
3533 $limit = $this->mOptions->getMaxTemplateDepth();
3534 if ( $frame->depth >= $limit ) {
3535 $found = true;
3536 $text = '<span class="error">'
3537 . wfMessage( 'parser-template-recursion-depth-warning' )
3538 ->numParams( $limit )->inContentLanguage()->text()
3539 . '</span>';
3544 # Load from database
3545 if ( !$found && $title ) {
3546 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3547 if ( !$title->isExternal() ) {
3548 if ( $title->isSpecialPage()
3549 && $this->mOptions->getAllowSpecialInclusion()
3550 && $this->ot['html']
3552 // Pass the template arguments as URL parameters.
3553 // "uselang" will have no effect since the Language object
3554 // is forced to the one defined in ParserOptions.
3555 $pageArgs = array();
3556 $argsLength = $args->getLength();
3557 for ( $i = 0; $i < $argsLength; $i++ ) {
3558 $bits = $args->item( $i )->splitArg();
3559 if ( strval( $bits['index'] ) === '' ) {
3560 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3561 $value = trim( $frame->expand( $bits['value'] ) );
3562 $pageArgs[$name] = $value;
3566 // Create a new context to execute the special page
3567 $context = new RequestContext;
3568 $context->setTitle( $title );
3569 $context->setRequest( new FauxRequest( $pageArgs ) );
3570 $context->setUser( $this->getUser() );
3571 $context->setLanguage( $this->mOptions->getUserLangObj() );
3572 $ret = SpecialPageFactory::capturePath( $title, $context );
3573 if ( $ret ) {
3574 $text = $context->getOutput()->getHTML();
3575 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3576 $found = true;
3577 $isHTML = true;
3578 $this->disableCache();
3580 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3581 $found = false; # access denied
3582 wfDebug( __METHOD__ . ": template inclusion denied for " .
3583 $title->getPrefixedDBkey() . "\n" );
3584 } else {
3585 list( $text, $title ) = $this->getTemplateDom( $title );
3586 if ( $text !== false ) {
3587 $found = true;
3588 $isChildObj = true;
3592 # If the title is valid but undisplayable, make a link to it
3593 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3594 $text = "[[:$titleText]]";
3595 $found = true;
3597 } elseif ( $title->isTrans() ) {
3598 # Interwiki transclusion
3599 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3600 $text = $this->interwikiTransclude( $title, 'render' );
3601 $isHTML = true;
3602 } else {
3603 $text = $this->interwikiTransclude( $title, 'raw' );
3604 # Preprocess it like a template
3605 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3606 $isChildObj = true;
3608 $found = true;
3611 # Do infinite loop check
3612 # This has to be done after redirect resolution to avoid infinite loops via redirects
3613 if ( !$frame->loopCheck( $title ) ) {
3614 $found = true;
3615 $text = '<span class="error">'
3616 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3617 . '</span>';
3618 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3622 # If we haven't found text to substitute by now, we're done
3623 # Recover the source wikitext and return it
3624 if ( !$found ) {
3625 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3626 if ( $profileSection ) {
3627 $this->mProfiler->scopedProfileOut( $profileSection );
3629 return array( 'object' => $text );
3632 # Expand DOM-style return values in a child frame
3633 if ( $isChildObj ) {
3634 # Clean up argument array
3635 $newFrame = $frame->newChild( $args, $title );
3637 if ( $nowiki ) {
3638 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3639 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3640 # Expansion is eligible for the empty-frame cache
3641 $text = $newFrame->cachedExpand( $titleText, $text );
3642 } else {
3643 # Uncached expansion
3644 $text = $newFrame->expand( $text );
3647 if ( $isLocalObj && $nowiki ) {
3648 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3649 $isLocalObj = false;
3652 if ( $profileSection ) {
3653 $this->mProfiler->scopedProfileOut( $profileSection );
3656 # Replace raw HTML by a placeholder
3657 if ( $isHTML ) {
3658 $text = $this->insertStripItem( $text );
3659 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3660 # Escape nowiki-style return values
3661 $text = wfEscapeWikiText( $text );
3662 } elseif ( is_string( $text )
3663 && !$piece['lineStart']
3664 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3666 # Bug 529: if the template begins with a table or block-level
3667 # element, it should be treated as beginning a new line.
3668 # This behavior is somewhat controversial.
3669 $text = "\n" . $text;
3672 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3673 # Error, oversize inclusion
3674 if ( $titleText !== false ) {
3675 # Make a working, properly escaped link if possible (bug 23588)
3676 $text = "[[:$titleText]]";
3677 } else {
3678 # This will probably not be a working link, but at least it may
3679 # provide some hint of where the problem is
3680 preg_replace( '/^:/', '', $originalTitle );
3681 $text = "[[:$originalTitle]]";
3683 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3684 . 'post-expand include size too large -->' );
3685 $this->limitationWarn( 'post-expand-template-inclusion' );
3688 if ( $isLocalObj ) {
3689 $ret = array( 'object' => $text );
3690 } else {
3691 $ret = array( 'text' => $text );
3694 return $ret;
3698 * Call a parser function and return an array with text and flags.
3700 * The returned array will always contain a boolean 'found', indicating
3701 * whether the parser function was found or not. It may also contain the
3702 * following:
3703 * text: string|object, resulting wikitext or PP DOM object
3704 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3705 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3706 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3707 * nowiki: bool, wiki markup in $text should be escaped
3709 * @since 1.21
3710 * @param PPFrame $frame The current frame, contains template arguments
3711 * @param string $function Function name
3712 * @param array $args Arguments to the function
3713 * @throws MWException
3714 * @return array
3716 public function callParserFunction( $frame, $function, array $args = array() ) {
3717 global $wgContLang;
3720 # Case sensitive functions
3721 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3722 $function = $this->mFunctionSynonyms[1][$function];
3723 } else {
3724 # Case insensitive functions
3725 $function = $wgContLang->lc( $function );
3726 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3727 $function = $this->mFunctionSynonyms[0][$function];
3728 } else {
3729 return array( 'found' => false );
3733 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3735 # Workaround for PHP bug 35229 and similar
3736 if ( !is_callable( $callback ) ) {
3737 throw new MWException( "Tag hook for $function is not callable\n" );
3740 $allArgs = array( &$this );
3741 if ( $flags & self::SFH_OBJECT_ARGS ) {
3742 # Convert arguments to PPNodes and collect for appending to $allArgs
3743 $funcArgs = array();
3744 foreach ( $args as $k => $v ) {
3745 if ( $v instanceof PPNode || $k === 0 ) {
3746 $funcArgs[] = $v;
3747 } else {
3748 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
3752 # Add a frame parameter, and pass the arguments as an array
3753 $allArgs[] = $frame;
3754 $allArgs[] = $funcArgs;
3755 } else {
3756 # Convert arguments to plain text and append to $allArgs
3757 foreach ( $args as $k => $v ) {
3758 if ( $v instanceof PPNode ) {
3759 $allArgs[] = trim( $frame->expand( $v ) );
3760 } elseif ( is_int( $k ) && $k >= 0 ) {
3761 $allArgs[] = trim( $v );
3762 } else {
3763 $allArgs[] = trim( "$k=$v" );
3768 $result = call_user_func_array( $callback, $allArgs );
3770 # The interface for function hooks allows them to return a wikitext
3771 # string or an array containing the string and any flags. This mungs
3772 # things around to match what this method should return.
3773 if ( !is_array( $result ) ) {
3774 $result = array(
3775 'found' => true,
3776 'text' => $result,
3778 } else {
3779 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3780 $result['text'] = $result[0];
3782 unset( $result[0] );
3783 $result += array(
3784 'found' => true,
3788 $noparse = true;
3789 $preprocessFlags = 0;
3790 if ( isset( $result['noparse'] ) ) {
3791 $noparse = $result['noparse'];
3793 if ( isset( $result['preprocessFlags'] ) ) {
3794 $preprocessFlags = $result['preprocessFlags'];
3797 if ( !$noparse ) {
3798 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3799 $result['isChildObj'] = true;
3802 return $result;
3806 * Get the semi-parsed DOM representation of a template with a given title,
3807 * and its redirect destination title. Cached.
3809 * @param Title $title
3811 * @return array
3813 public function getTemplateDom( $title ) {
3814 $cacheTitle = $title;
3815 $titleText = $title->getPrefixedDBkey();
3817 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3818 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3819 $title = Title::makeTitle( $ns, $dbk );
3820 $titleText = $title->getPrefixedDBkey();
3822 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3823 return array( $this->mTplDomCache[$titleText], $title );
3826 # Cache miss, go to the database
3827 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3829 if ( $text === false ) {
3830 $this->mTplDomCache[$titleText] = false;
3831 return array( false, $title );
3834 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3835 $this->mTplDomCache[$titleText] = $dom;
3837 if ( !$title->equals( $cacheTitle ) ) {
3838 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3839 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3842 return array( $dom, $title );
3846 * Fetch the current revision of a given title. Note that the revision
3847 * (and even the title) may not exist in the database, so everything
3848 * contributing to the output of the parser should use this method
3849 * where possible, rather than getting the revisions themselves. This
3850 * method also caches its results, so using it benefits performance.
3852 * @since 1.24
3853 * @param Title $title
3854 * @return Revision
3856 public function fetchCurrentRevisionOfTitle( $title ) {
3857 $cacheKey = $title->getPrefixedDBkey();
3858 if ( !$this->currentRevisionCache ) {
3859 $this->currentRevisionCache = new MapCacheLRU( 100 );
3861 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3862 $this->currentRevisionCache->set( $cacheKey,
3863 // Defaults to Parser::statelessFetchRevision()
3864 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3867 return $this->currentRevisionCache->get( $cacheKey );
3871 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3872 * without passing them on to it.
3874 * @since 1.24
3875 * @param Title $title
3876 * @param Parser|bool $parser
3877 * @return Revision
3879 public static function statelessFetchRevision( $title, $parser = false ) {
3880 return Revision::newFromTitle( $title );
3884 * Fetch the unparsed text of a template and register a reference to it.
3885 * @param Title $title
3886 * @return array ( string or false, Title )
3888 public function fetchTemplateAndTitle( $title ) {
3889 // Defaults to Parser::statelessFetchTemplate()
3890 $templateCb = $this->mOptions->getTemplateCallback();
3891 $stuff = call_user_func( $templateCb, $title, $this );
3892 $text = $stuff['text'];
3893 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3894 if ( isset( $stuff['deps'] ) ) {
3895 foreach ( $stuff['deps'] as $dep ) {
3896 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3897 if ( $dep['title']->equals( $this->getTitle() ) ) {
3898 // If we transclude ourselves, the final result
3899 // will change based on the new version of the page
3900 $this->mOutput->setFlag( 'vary-revision' );
3904 return array( $text, $finalTitle );
3908 * Fetch the unparsed text of a template and register a reference to it.
3909 * @param Title $title
3910 * @return string|bool
3912 public function fetchTemplate( $title ) {
3913 $rv = $this->fetchTemplateAndTitle( $title );
3914 return $rv[0];
3918 * Static function to get a template
3919 * Can be overridden via ParserOptions::setTemplateCallback().
3921 * @param Title $title
3922 * @param bool|Parser $parser
3924 * @return array
3926 public static function statelessFetchTemplate( $title, $parser = false ) {
3927 $text = $skip = false;
3928 $finalTitle = $title;
3929 $deps = array();
3931 # Loop to fetch the article, with up to 1 redirect
3932 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3933 # Give extensions a chance to select the revision instead
3934 $id = false; # Assume current
3935 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3936 array( $parser, $title, &$skip, &$id ) );
3938 if ( $skip ) {
3939 $text = false;
3940 $deps[] = array(
3941 'title' => $title,
3942 'page_id' => $title->getArticleID(),
3943 'rev_id' => null
3945 break;
3947 # Get the revision
3948 if ( $id ) {
3949 $rev = Revision::newFromId( $id );
3950 } elseif ( $parser ) {
3951 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3952 } else {
3953 $rev = Revision::newFromTitle( $title );
3955 $rev_id = $rev ? $rev->getId() : 0;
3956 # If there is no current revision, there is no page
3957 if ( $id === false && !$rev ) {
3958 $linkCache = LinkCache::singleton();
3959 $linkCache->addBadLinkObj( $title );
3962 $deps[] = array(
3963 'title' => $title,
3964 'page_id' => $title->getArticleID(),
3965 'rev_id' => $rev_id );
3966 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3967 # We fetched a rev from a different title; register it too...
3968 $deps[] = array(
3969 'title' => $rev->getTitle(),
3970 'page_id' => $rev->getPage(),
3971 'rev_id' => $rev_id );
3974 if ( $rev ) {
3975 $content = $rev->getContent();
3976 $text = $content ? $content->getWikitextForTransclusion() : null;
3978 if ( $text === false || $text === null ) {
3979 $text = false;
3980 break;
3982 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3983 global $wgContLang;
3984 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3985 if ( !$message->exists() ) {
3986 $text = false;
3987 break;
3989 $content = $message->content();
3990 $text = $message->plain();
3991 } else {
3992 break;
3994 if ( !$content ) {
3995 break;
3997 # Redirect?
3998 $finalTitle = $title;
3999 $title = $content->getRedirectTarget();
4001 return array(
4002 'text' => $text,
4003 'finalTitle' => $finalTitle,
4004 'deps' => $deps );
4008 * Fetch a file and its title and register a reference to it.
4009 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4010 * @param Title $title
4011 * @param array $options Array of options to RepoGroup::findFile
4012 * @return File|bool
4014 public function fetchFile( $title, $options = array() ) {
4015 $res = $this->fetchFileAndTitle( $title, $options );
4016 return $res[0];
4020 * Fetch a file and its title and register a reference to it.
4021 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4022 * @param Title $title
4023 * @param array $options Array of options to RepoGroup::findFile
4024 * @return array ( File or false, Title of file )
4026 public function fetchFileAndTitle( $title, $options = array() ) {
4027 $file = $this->fetchFileNoRegister( $title, $options );
4029 $time = $file ? $file->getTimestamp() : false;
4030 $sha1 = $file ? $file->getSha1() : false;
4031 # Register the file as a dependency...
4032 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
4033 if ( $file && !$title->equals( $file->getTitle() ) ) {
4034 # Update fetched file title
4035 $title = $file->getTitle();
4036 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
4038 return array( $file, $title );
4042 * Helper function for fetchFileAndTitle.
4044 * Also useful if you need to fetch a file but not use it yet,
4045 * for example to get the file's handler.
4047 * @param Title $title
4048 * @param array $options Array of options to RepoGroup::findFile
4049 * @return File|bool
4051 protected function fetchFileNoRegister( $title, $options = array() ) {
4052 if ( isset( $options['broken'] ) ) {
4053 $file = false; // broken thumbnail forced by hook
4054 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4055 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
4056 } else { // get by (name,timestamp)
4057 $file = wfFindFile( $title, $options );
4059 return $file;
4063 * Transclude an interwiki link.
4065 * @param Title $title
4066 * @param string $action
4068 * @return string
4070 public function interwikiTransclude( $title, $action ) {
4071 global $wgEnableScaryTranscluding;
4073 if ( !$wgEnableScaryTranscluding ) {
4074 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4077 $url = $title->getFullURL( array( 'action' => $action ) );
4079 if ( strlen( $url ) > 255 ) {
4080 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4082 return $this->fetchScaryTemplateMaybeFromCache( $url );
4086 * @param string $url
4087 * @return mixed|string
4089 public function fetchScaryTemplateMaybeFromCache( $url ) {
4090 global $wgTranscludeCacheExpiry;
4091 $dbr = wfGetDB( DB_SLAVE );
4092 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4093 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4094 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4095 if ( $obj ) {
4096 return $obj->tc_contents;
4099 $req = MWHttpRequest::factory( $url );
4100 $status = $req->execute(); // Status object
4101 if ( $status->isOK() ) {
4102 $text = $req->getContent();
4103 } elseif ( $req->getStatus() != 200 ) {
4104 // Though we failed to fetch the content, this status is useless.
4105 return wfMessage( 'scarytranscludefailed-httpstatus' )
4106 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4107 } else {
4108 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4111 $dbw = wfGetDB( DB_MASTER );
4112 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4113 'tc_url' => $url,
4114 'tc_time' => $dbw->timestamp( time() ),
4115 'tc_contents' => $text
4116 ) );
4117 return $text;
4121 * Triple brace replacement -- used for template arguments
4122 * @private
4124 * @param array $piece
4125 * @param PPFrame $frame
4127 * @return array
4129 public function argSubstitution( $piece, $frame ) {
4131 $error = false;
4132 $parts = $piece['parts'];
4133 $nameWithSpaces = $frame->expand( $piece['title'] );
4134 $argName = trim( $nameWithSpaces );
4135 $object = false;
4136 $text = $frame->getArgument( $argName );
4137 if ( $text === false && $parts->getLength() > 0
4138 && ( $this->ot['html']
4139 || $this->ot['pre']
4140 || ( $this->ot['wiki'] && $frame->isTemplate() )
4143 # No match in frame, use the supplied default
4144 $object = $parts->item( 0 )->getChildren();
4146 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4147 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4148 $this->limitationWarn( 'post-expand-template-argument' );
4151 if ( $text === false && $object === false ) {
4152 # No match anywhere
4153 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4155 if ( $error !== false ) {
4156 $text .= $error;
4158 if ( $object !== false ) {
4159 $ret = array( 'object' => $object );
4160 } else {
4161 $ret = array( 'text' => $text );
4164 return $ret;
4168 * Return the text to be used for a given extension tag.
4169 * This is the ghost of strip().
4171 * @param array $params Associative array of parameters:
4172 * name PPNode for the tag name
4173 * attr PPNode for unparsed text where tag attributes are thought to be
4174 * attributes Optional associative array of parsed attributes
4175 * inner Contents of extension element
4176 * noClose Original text did not have a close tag
4177 * @param PPFrame $frame
4179 * @throws MWException
4180 * @return string
4182 public function extensionSubstitution( $params, $frame ) {
4183 $name = $frame->expand( $params['name'] );
4184 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
4185 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
4186 $marker = "{$this->mUniqPrefix}-$name-"
4187 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
4189 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
4190 ( $this->ot['html'] || $this->ot['pre'] );
4191 if ( $isFunctionTag ) {
4192 $markerType = 'none';
4193 } else {
4194 $markerType = 'general';
4196 if ( $this->ot['html'] || $isFunctionTag ) {
4197 $name = strtolower( $name );
4198 $attributes = Sanitizer::decodeTagAttributes( $attrText );
4199 if ( isset( $params['attributes'] ) ) {
4200 $attributes = $attributes + $params['attributes'];
4203 if ( isset( $this->mTagHooks[$name] ) ) {
4204 # Workaround for PHP bug 35229 and similar
4205 if ( !is_callable( $this->mTagHooks[$name] ) ) {
4206 throw new MWException( "Tag hook for $name is not callable\n" );
4208 $output = call_user_func_array( $this->mTagHooks[$name],
4209 array( $content, $attributes, $this, $frame ) );
4210 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
4211 list( $callback, ) = $this->mFunctionTagHooks[$name];
4212 if ( !is_callable( $callback ) ) {
4213 throw new MWException( "Tag hook for $name is not callable\n" );
4216 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4217 } else {
4218 $output = '<span class="error">Invalid tag extension name: ' .
4219 htmlspecialchars( $name ) . '</span>';
4222 if ( is_array( $output ) ) {
4223 # Extract flags to local scope (to override $markerType)
4224 $flags = $output;
4225 $output = $flags[0];
4226 unset( $flags[0] );
4227 extract( $flags );
4229 } else {
4230 if ( is_null( $attrText ) ) {
4231 $attrText = '';
4233 if ( isset( $params['attributes'] ) ) {
4234 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4235 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4236 htmlspecialchars( $attrValue ) . '"';
4239 if ( $content === null ) {
4240 $output = "<$name$attrText/>";
4241 } else {
4242 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4243 $output = "<$name$attrText>$content$close";
4247 if ( $markerType === 'none' ) {
4248 return $output;
4249 } elseif ( $markerType === 'nowiki' ) {
4250 $this->mStripState->addNoWiki( $marker, $output );
4251 } elseif ( $markerType === 'general' ) {
4252 $this->mStripState->addGeneral( $marker, $output );
4253 } else {
4254 throw new MWException( __METHOD__ . ': invalid marker type' );
4256 return $marker;
4260 * Increment an include size counter
4262 * @param string $type The type of expansion
4263 * @param int $size The size of the text
4264 * @return bool False if this inclusion would take it over the maximum, true otherwise
4266 public function incrementIncludeSize( $type, $size ) {
4267 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4268 return false;
4269 } else {
4270 $this->mIncludeSizes[$type] += $size;
4271 return true;
4276 * Increment the expensive function count
4278 * @return bool False if the limit has been exceeded
4280 public function incrementExpensiveFunctionCount() {
4281 $this->mExpensiveFunctionCount++;
4282 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4286 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4287 * Fills $this->mDoubleUnderscores, returns the modified text
4289 * @param string $text
4291 * @return string
4293 public function doDoubleUnderscore( $text ) {
4295 # The position of __TOC__ needs to be recorded
4296 $mw = MagicWord::get( 'toc' );
4297 if ( $mw->match( $text ) ) {
4298 $this->mShowToc = true;
4299 $this->mForceTocPosition = true;
4301 # Set a placeholder. At the end we'll fill it in with the TOC.
4302 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4304 # Only keep the first one.
4305 $text = $mw->replace( '', $text );
4308 # Now match and remove the rest of them
4309 $mwa = MagicWord::getDoubleUnderscoreArray();
4310 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4312 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4313 $this->mOutput->mNoGallery = true;
4315 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4316 $this->mShowToc = false;
4318 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4319 && $this->mTitle->getNamespace() == NS_CATEGORY
4321 $this->addTrackingCategory( 'hidden-category-category' );
4323 # (bug 8068) Allow control over whether robots index a page.
4325 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4326 # is not desirable, the last one on the page should win.
4327 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4328 $this->mOutput->setIndexPolicy( 'noindex' );
4329 $this->addTrackingCategory( 'noindex-category' );
4331 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4332 $this->mOutput->setIndexPolicy( 'index' );
4333 $this->addTrackingCategory( 'index-category' );
4336 # Cache all double underscores in the database
4337 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4338 $this->mOutput->setProperty( $key, '' );
4341 return $text;
4345 * @see ParserOutput::addTrackingCategory()
4346 * @param string $msg Message key
4347 * @return bool Whether the addition was successful
4349 public function addTrackingCategory( $msg ) {
4350 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4354 * This function accomplishes several tasks:
4355 * 1) Auto-number headings if that option is enabled
4356 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4357 * 3) Add a Table of contents on the top for users who have enabled the option
4358 * 4) Auto-anchor headings
4360 * It loops through all headlines, collects the necessary data, then splits up the
4361 * string and re-inserts the newly formatted headlines.
4363 * @param string $text
4364 * @param string $origText Original, untouched wikitext
4365 * @param bool $isMain
4366 * @return mixed|string
4367 * @private
4369 public function formatHeadings( $text, $origText, $isMain = true ) {
4370 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4372 # Inhibit editsection links if requested in the page
4373 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4374 $maybeShowEditLink = $showEditLink = false;
4375 } else {
4376 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4377 $showEditLink = $this->mOptions->getEditSection();
4379 if ( $showEditLink ) {
4380 $this->mOutput->setEditSectionTokens( true );
4383 # Get all headlines for numbering them and adding funky stuff like [edit]
4384 # links - this is for later, but we need the number of headlines right now
4385 $matches = array();
4386 $numMatches = preg_match_all(
4387 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4388 $text,
4389 $matches
4392 # if there are fewer than 4 headlines in the article, do not show TOC
4393 # unless it's been explicitly enabled.
4394 $enoughToc = $this->mShowToc &&
4395 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4397 # Allow user to stipulate that a page should have a "new section"
4398 # link added via __NEWSECTIONLINK__
4399 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4400 $this->mOutput->setNewSection( true );
4403 # Allow user to remove the "new section"
4404 # link via __NONEWSECTIONLINK__
4405 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4406 $this->mOutput->hideNewSection( true );
4409 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4410 # override above conditions and always show TOC above first header
4411 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4412 $this->mShowToc = true;
4413 $enoughToc = true;
4416 # headline counter
4417 $headlineCount = 0;
4418 $numVisible = 0;
4420 # Ugh .. the TOC should have neat indentation levels which can be
4421 # passed to the skin functions. These are determined here
4422 $toc = '';
4423 $full = '';
4424 $head = array();
4425 $sublevelCount = array();
4426 $levelCount = array();
4427 $level = 0;
4428 $prevlevel = 0;
4429 $toclevel = 0;
4430 $prevtoclevel = 0;
4431 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4432 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4433 $oldType = $this->mOutputType;
4434 $this->setOutputType( self::OT_WIKI );
4435 $frame = $this->getPreprocessor()->newFrame();
4436 $root = $this->preprocessToDom( $origText );
4437 $node = $root->getFirstChild();
4438 $byteOffset = 0;
4439 $tocraw = array();
4440 $refers = array();
4442 foreach ( $matches[3] as $headline ) {
4443 $isTemplate = false;
4444 $titleText = false;
4445 $sectionIndex = false;
4446 $numbering = '';
4447 $markerMatches = array();
4448 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4449 $serial = $markerMatches[1];
4450 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4451 $isTemplate = ( $titleText != $baseTitleText );
4452 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4455 if ( $toclevel ) {
4456 $prevlevel = $level;
4458 $level = $matches[1][$headlineCount];
4460 if ( $level > $prevlevel ) {
4461 # Increase TOC level
4462 $toclevel++;
4463 $sublevelCount[$toclevel] = 0;
4464 if ( $toclevel < $wgMaxTocLevel ) {
4465 $prevtoclevel = $toclevel;
4466 $toc .= Linker::tocIndent();
4467 $numVisible++;
4469 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4470 # Decrease TOC level, find level to jump to
4472 for ( $i = $toclevel; $i > 0; $i-- ) {
4473 if ( $levelCount[$i] == $level ) {
4474 # Found last matching level
4475 $toclevel = $i;
4476 break;
4477 } elseif ( $levelCount[$i] < $level ) {
4478 # Found first matching level below current level
4479 $toclevel = $i + 1;
4480 break;
4483 if ( $i == 0 ) {
4484 $toclevel = 1;
4486 if ( $toclevel < $wgMaxTocLevel ) {
4487 if ( $prevtoclevel < $wgMaxTocLevel ) {
4488 # Unindent only if the previous toc level was shown :p
4489 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4490 $prevtoclevel = $toclevel;
4491 } else {
4492 $toc .= Linker::tocLineEnd();
4495 } else {
4496 # No change in level, end TOC line
4497 if ( $toclevel < $wgMaxTocLevel ) {
4498 $toc .= Linker::tocLineEnd();
4502 $levelCount[$toclevel] = $level;
4504 # count number of headlines for each level
4505 $sublevelCount[$toclevel]++;
4506 $dot = 0;
4507 for ( $i = 1; $i <= $toclevel; $i++ ) {
4508 if ( !empty( $sublevelCount[$i] ) ) {
4509 if ( $dot ) {
4510 $numbering .= '.';
4512 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4513 $dot = 1;
4517 # The safe header is a version of the header text safe to use for links
4519 # Remove link placeholders by the link text.
4520 # <!--LINK number-->
4521 # turns into
4522 # link text with suffix
4523 # Do this before unstrip since link text can contain strip markers
4524 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4526 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4527 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4529 # Strip out HTML (first regex removes any tag not allowed)
4530 # Allowed tags are:
4531 # * <sup> and <sub> (bug 8393)
4532 # * <i> (bug 26375)
4533 # * <b> (r105284)
4534 # * <bdi> (bug 72884)
4535 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4537 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4538 # to allow setting directionality in toc items.
4539 $tocline = preg_replace(
4540 array(
4541 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4542 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4544 array( '', '<$1>' ),
4545 $safeHeadline
4547 $tocline = trim( $tocline );
4549 # For the anchor, strip out HTML-y stuff period
4550 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4551 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4553 # Save headline for section edit hint before it's escaped
4554 $headlineHint = $safeHeadline;
4556 if ( $wgExperimentalHtmlIds ) {
4557 # For reverse compatibility, provide an id that's
4558 # HTML4-compatible, like we used to.
4560 # It may be worth noting, academically, that it's possible for
4561 # the legacy anchor to conflict with a non-legacy headline
4562 # anchor on the page. In this case likely the "correct" thing
4563 # would be to either drop the legacy anchors or make sure
4564 # they're numbered first. However, this would require people
4565 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4566 # manually, so let's not bother worrying about it.
4567 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4568 array( 'noninitial', 'legacy' ) );
4569 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4571 if ( $legacyHeadline == $safeHeadline ) {
4572 # No reason to have both (in fact, we can't)
4573 $legacyHeadline = false;
4575 } else {
4576 $legacyHeadline = false;
4577 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4578 'noninitial' );
4581 # HTML names must be case-insensitively unique (bug 10721).
4582 # This does not apply to Unicode characters per
4583 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4584 # @todo FIXME: We may be changing them depending on the current locale.
4585 $arrayKey = strtolower( $safeHeadline );
4586 if ( $legacyHeadline === false ) {
4587 $legacyArrayKey = false;
4588 } else {
4589 $legacyArrayKey = strtolower( $legacyHeadline );
4592 # Create the anchor for linking from the TOC to the section
4593 $anchor = $safeHeadline;
4594 $legacyAnchor = $legacyHeadline;
4595 if ( isset( $refers[$arrayKey] ) ) {
4596 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++$i );
4597 $anchor .= "_$i";
4598 $refers["${arrayKey}_$i"] = true;
4599 } else {
4600 $refers[$arrayKey] = true;
4602 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4603 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++$i );
4604 $legacyAnchor .= "_$i";
4605 $refers["${legacyArrayKey}_$i"] = true;
4606 } else {
4607 $refers[$legacyArrayKey] = true;
4610 # Don't number the heading if it is the only one (looks silly)
4611 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4612 # the two are different if the line contains a link
4613 $headline = Html::element(
4614 'span',
4615 array( 'class' => 'mw-headline-number' ),
4616 $numbering
4617 ) . ' ' . $headline;
4620 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4621 $toc .= Linker::tocLine( $anchor, $tocline,
4622 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4625 # Add the section to the section tree
4626 # Find the DOM node for this header
4627 $noOffset = ( $isTemplate || $sectionIndex === false );
4628 while ( $node && !$noOffset ) {
4629 if ( $node->getName() === 'h' ) {
4630 $bits = $node->splitHeading();
4631 if ( $bits['i'] == $sectionIndex ) {
4632 break;
4635 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4636 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4637 $node = $node->getNextSibling();
4639 $tocraw[] = array(
4640 'toclevel' => $toclevel,
4641 'level' => $level,
4642 'line' => $tocline,
4643 'number' => $numbering,
4644 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4645 'fromtitle' => $titleText,
4646 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4647 'anchor' => $anchor,
4650 # give headline the correct <h#> tag
4651 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4652 // Output edit section links as markers with styles that can be customized by skins
4653 if ( $isTemplate ) {
4654 # Put a T flag in the section identifier, to indicate to extractSections()
4655 # that sections inside <includeonly> should be counted.
4656 $editsectionPage = $titleText;
4657 $editsectionSection = "T-$sectionIndex";
4658 $editsectionContent = null;
4659 } else {
4660 $editsectionPage = $this->mTitle->getPrefixedText();
4661 $editsectionSection = $sectionIndex;
4662 $editsectionContent = $headlineHint;
4664 // We use a bit of pesudo-xml for editsection markers. The
4665 // language converter is run later on. Using a UNIQ style marker
4666 // leads to the converter screwing up the tokens when it
4667 // converts stuff. And trying to insert strip tags fails too. At
4668 // this point all real inputted tags have already been escaped,
4669 // so we don't have to worry about a user trying to input one of
4670 // these markers directly. We use a page and section attribute
4671 // to stop the language converter from converting these
4672 // important bits of data, but put the headline hint inside a
4673 // content block because the language converter is supposed to
4674 // be able to convert that piece of data.
4675 // Gets replaced with html in ParserOutput::getText
4676 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4677 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4678 if ( $editsectionContent !== null ) {
4679 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4680 } else {
4681 $editlink .= '/>';
4683 } else {
4684 $editlink = '';
4686 $head[$headlineCount] = Linker::makeHeadline( $level,
4687 $matches['attrib'][$headlineCount], $anchor, $headline,
4688 $editlink, $legacyAnchor );
4690 $headlineCount++;
4693 $this->setOutputType( $oldType );
4695 # Never ever show TOC if no headers
4696 if ( $numVisible < 1 ) {
4697 $enoughToc = false;
4700 if ( $enoughToc ) {
4701 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4702 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4704 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4705 $this->mOutput->setTOCHTML( $toc );
4706 $toc = self::TOC_START . $toc . self::TOC_END;
4707 $this->mOutput->addModules( 'mediawiki.toc' );
4710 if ( $isMain ) {
4711 $this->mOutput->setSections( $tocraw );
4714 # split up and insert constructed headlines
4715 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4716 $i = 0;
4718 // build an array of document sections
4719 $sections = array();
4720 foreach ( $blocks as $block ) {
4721 // $head is zero-based, sections aren't.
4722 if ( empty( $head[$i - 1] ) ) {
4723 $sections[$i] = $block;
4724 } else {
4725 $sections[$i] = $head[$i - 1] . $block;
4729 * Send a hook, one per section.
4730 * The idea here is to be able to make section-level DIVs, but to do so in a
4731 * lower-impact, more correct way than r50769
4733 * $this : caller
4734 * $section : the section number
4735 * &$sectionContent : ref to the content of the section
4736 * $showEditLinks : boolean describing whether this section has an edit link
4738 Hooks::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4740 $i++;
4743 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4744 // append the TOC at the beginning
4745 // Top anchor now in skin
4746 $sections[0] = $sections[0] . $toc . "\n";
4749 $full .= join( '', $sections );
4751 if ( $this->mForceTocPosition ) {
4752 return str_replace( '<!--MWTOC-->', $toc, $full );
4753 } else {
4754 return $full;
4759 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4760 * conversion, substituting signatures, {{subst:}} templates, etc.
4762 * @param string $text The text to transform
4763 * @param Title $title The Title object for the current article
4764 * @param User $user The User object describing the current user
4765 * @param ParserOptions $options Parsing options
4766 * @param bool $clearState Whether to clear the parser state first
4767 * @return string The altered wiki markup
4769 public function preSaveTransform( $text, Title $title, User $user,
4770 ParserOptions $options, $clearState = true
4772 if ( $clearState ) {
4773 $magicScopeVariable = $this->lock();
4775 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4776 $this->setUser( $user );
4778 $pairs = array(
4779 "\r\n" => "\n",
4780 "\r" => "\n",
4782 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4783 if ( $options->getPreSaveTransform() ) {
4784 $text = $this->pstPass2( $text, $user );
4786 $text = $this->mStripState->unstripBoth( $text );
4788 $this->setUser( null ); #Reset
4790 return $text;
4794 * Pre-save transform helper function
4796 * @param string $text
4797 * @param User $user
4799 * @return string
4801 private function pstPass2( $text, $user ) {
4802 global $wgContLang;
4804 # Note: This is the timestamp saved as hardcoded wikitext to
4805 # the database, we use $wgContLang here in order to give
4806 # everyone the same signature and use the default one rather
4807 # than the one selected in each user's preferences.
4808 # (see also bug 12815)
4809 $ts = $this->mOptions->getTimestamp();
4810 $timestamp = MWTimestamp::getLocalInstance( $ts );
4811 $ts = $timestamp->format( 'YmdHis' );
4812 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4814 # Allow translation of timezones through wiki. format() can return
4815 # whatever crap the system uses, localised or not, so we cannot
4816 # ship premade translations.
4817 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4818 $msg = wfMessage( $key )->inContentLanguage();
4819 if ( $msg->exists() ) {
4820 $tzMsg = $msg->text();
4823 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4825 # Variable replacement
4826 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4827 $text = $this->replaceVariables( $text );
4829 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4830 # which may corrupt this parser instance via its wfMessage()->text() call-
4832 # Signatures
4833 $sigText = $this->getUserSig( $user );
4834 $text = strtr( $text, array(
4835 '~~~~~' => $d,
4836 '~~~~' => "$sigText $d",
4837 '~~~' => $sigText
4838 ) );
4840 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4841 $tc = '[' . Title::legalChars() . ']';
4842 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4844 // [[ns:page (context)|]]
4845 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4846 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4847 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4848 // [[ns:page (context), context|]] (using either single or double-width comma)
4849 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4850 // [[|page]] (reverse pipe trick: add context from page title)
4851 $p2 = "/\[\[\\|($tc+)]]/";
4853 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4854 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4855 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4856 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4858 $t = $this->mTitle->getText();
4859 $m = array();
4860 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4861 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4862 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4863 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4864 } else {
4865 # if there's no context, don't bother duplicating the title
4866 $text = preg_replace( $p2, '[[\\1]]', $text );
4869 # Trim trailing whitespace
4870 $text = rtrim( $text );
4872 return $text;
4876 * Fetch the user's signature text, if any, and normalize to
4877 * validated, ready-to-insert wikitext.
4878 * If you have pre-fetched the nickname or the fancySig option, you can
4879 * specify them here to save a database query.
4880 * Do not reuse this parser instance after calling getUserSig(),
4881 * as it may have changed if it's the $wgParser.
4883 * @param User $user
4884 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4885 * @param bool|null $fancySig whether the nicknname is the complete signature
4886 * or null to use default value
4887 * @return string
4889 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4890 global $wgMaxSigChars;
4892 $username = $user->getName();
4894 # If not given, retrieve from the user object.
4895 if ( $nickname === false ) {
4896 $nickname = $user->getOption( 'nickname' );
4899 if ( is_null( $fancySig ) ) {
4900 $fancySig = $user->getBoolOption( 'fancysig' );
4903 $nickname = $nickname == null ? $username : $nickname;
4905 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4906 $nickname = $username;
4907 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4908 } elseif ( $fancySig !== false ) {
4909 # Sig. might contain markup; validate this
4910 if ( $this->validateSig( $nickname ) !== false ) {
4911 # Validated; clean up (if needed) and return it
4912 return $this->cleanSig( $nickname, true );
4913 } else {
4914 # Failed to validate; fall back to the default
4915 $nickname = $username;
4916 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4920 # Make sure nickname doesnt get a sig in a sig
4921 $nickname = self::cleanSigInSig( $nickname );
4923 # If we're still here, make it a link to the user page
4924 $userText = wfEscapeWikiText( $username );
4925 $nickText = wfEscapeWikiText( $nickname );
4926 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4928 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4929 ->title( $this->getTitle() )->text();
4933 * Check that the user's signature contains no bad XML
4935 * @param string $text
4936 * @return string|bool An expanded string, or false if invalid.
4938 public function validateSig( $text ) {
4939 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4943 * Clean up signature text
4945 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4946 * 2) Substitute all transclusions
4948 * @param string $text
4949 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4950 * @return string Signature text
4952 public function cleanSig( $text, $parsing = false ) {
4953 if ( !$parsing ) {
4954 global $wgTitle;
4955 $magicScopeVariable = $this->lock();
4956 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4959 # Option to disable this feature
4960 if ( !$this->mOptions->getCleanSignatures() ) {
4961 return $text;
4964 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4965 # => Move this logic to braceSubstitution()
4966 $substWord = MagicWord::get( 'subst' );
4967 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4968 $substText = '{{' . $substWord->getSynonym( 0 );
4970 $text = preg_replace( $substRegex, $substText, $text );
4971 $text = self::cleanSigInSig( $text );
4972 $dom = $this->preprocessToDom( $text );
4973 $frame = $this->getPreprocessor()->newFrame();
4974 $text = $frame->expand( $dom );
4976 if ( !$parsing ) {
4977 $text = $this->mStripState->unstripBoth( $text );
4980 return $text;
4984 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4986 * @param string $text
4987 * @return string Signature text with /~{3,5}/ removed
4989 public static function cleanSigInSig( $text ) {
4990 $text = preg_replace( '/~{3,5}/', '', $text );
4991 return $text;
4995 * Set up some variables which are usually set up in parse()
4996 * so that an external function can call some class members with confidence
4998 * @param Title|null $title
4999 * @param ParserOptions $options
5000 * @param int $outputType
5001 * @param bool $clearState
5003 public function startExternalParse( Title $title = null, ParserOptions $options,
5004 $outputType, $clearState = true
5006 $this->startParse( $title, $options, $outputType, $clearState );
5010 * @param Title|null $title
5011 * @param ParserOptions $options
5012 * @param int $outputType
5013 * @param bool $clearState
5015 private function startParse( Title $title = null, ParserOptions $options,
5016 $outputType, $clearState = true
5018 $this->setTitle( $title );
5019 $this->mOptions = $options;
5020 $this->setOutputType( $outputType );
5021 if ( $clearState ) {
5022 $this->clearState();
5027 * Wrapper for preprocess()
5029 * @param string $text The text to preprocess
5030 * @param ParserOptions $options Options
5031 * @param Title|null $title Title object or null to use $wgTitle
5032 * @return string
5034 public function transformMsg( $text, $options, $title = null ) {
5035 static $executing = false;
5037 # Guard against infinite recursion
5038 if ( $executing ) {
5039 return $text;
5041 $executing = true;
5043 if ( !$title ) {
5044 global $wgTitle;
5045 $title = $wgTitle;
5048 $text = $this->preprocess( $text, $title, $options );
5050 $executing = false;
5051 return $text;
5055 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5056 * The callback should have the following form:
5057 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5059 * Transform and return $text. Use $parser for any required context, e.g. use
5060 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5062 * Hooks may return extended information by returning an array, of which the
5063 * first numbered element (index 0) must be the return string, and all other
5064 * entries are extracted into local variables within an internal function
5065 * in the Parser class.
5067 * This interface (introduced r61913) appears to be undocumented, but
5068 * 'markerName' is used by some core tag hooks to override which strip
5069 * array their results are placed in. **Use great caution if attempting
5070 * this interface, as it is not documented and injudicious use could smash
5071 * private variables.**
5073 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5074 * @param callable $callback The callback function (and object) to use for the tag
5075 * @throws MWException
5076 * @return callable|null The old value of the mTagHooks array associated with the hook
5078 public function setHook( $tag, $callback ) {
5079 $tag = strtolower( $tag );
5080 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5081 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5083 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
5084 $this->mTagHooks[$tag] = $callback;
5085 if ( !in_array( $tag, $this->mStripList ) ) {
5086 $this->mStripList[] = $tag;
5089 return $oldVal;
5093 * As setHook(), but letting the contents be parsed.
5095 * Transparent tag hooks are like regular XML-style tag hooks, except they
5096 * operate late in the transformation sequence, on HTML instead of wikitext.
5098 * This is probably obsoleted by things dealing with parser frames?
5099 * The only extension currently using it is geoserver.
5101 * @since 1.10
5102 * @todo better document or deprecate this
5104 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5105 * @param callable $callback The callback function (and object) to use for the tag
5106 * @throws MWException
5107 * @return callable|null The old value of the mTagHooks array associated with the hook
5109 public function setTransparentTagHook( $tag, $callback ) {
5110 $tag = strtolower( $tag );
5111 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5112 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5114 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
5115 $this->mTransparentTagHooks[$tag] = $callback;
5117 return $oldVal;
5121 * Remove all tag hooks
5123 public function clearTagHooks() {
5124 $this->mTagHooks = array();
5125 $this->mFunctionTagHooks = array();
5126 $this->mStripList = $this->mDefaultStripList;
5130 * Create a function, e.g. {{sum:1|2|3}}
5131 * The callback function should have the form:
5132 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5134 * Or with Parser::SFH_OBJECT_ARGS:
5135 * function myParserFunction( $parser, $frame, $args ) { ... }
5137 * The callback may either return the text result of the function, or an array with the text
5138 * in element 0, and a number of flags in the other elements. The names of the flags are
5139 * specified in the keys. Valid flags are:
5140 * found The text returned is valid, stop processing the template. This
5141 * is on by default.
5142 * nowiki Wiki markup in the return value should be escaped
5143 * isHTML The returned text is HTML, armour it against wikitext transformation
5145 * @param string $id The magic word ID
5146 * @param callable $callback The callback function (and object) to use
5147 * @param int $flags A combination of the following flags:
5148 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5150 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5151 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5152 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5153 * the arguments, and to control the way they are expanded.
5155 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5156 * arguments, for instance:
5157 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5159 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5160 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5161 * working if/when this is changed.
5163 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5164 * expansion.
5166 * Please read the documentation in includes/parser/Preprocessor.php for more information
5167 * about the methods available in PPFrame and PPNode.
5169 * @throws MWException
5170 * @return string|callable The old callback function for this name, if any
5172 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5173 global $wgContLang;
5175 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
5176 $this->mFunctionHooks[$id] = array( $callback, $flags );
5178 # Add to function cache
5179 $mw = MagicWord::get( $id );
5180 if ( !$mw ) {
5181 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
5184 $synonyms = $mw->getSynonyms();
5185 $sensitive = intval( $mw->isCaseSensitive() );
5187 foreach ( $synonyms as $syn ) {
5188 # Case
5189 if ( !$sensitive ) {
5190 $syn = $wgContLang->lc( $syn );
5192 # Add leading hash
5193 if ( !( $flags & self::SFH_NO_HASH ) ) {
5194 $syn = '#' . $syn;
5196 # Remove trailing colon
5197 if ( substr( $syn, -1, 1 ) === ':' ) {
5198 $syn = substr( $syn, 0, -1 );
5200 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
5202 return $oldVal;
5206 * Get all registered function hook identifiers
5208 * @return array
5210 public function getFunctionHooks() {
5211 return array_keys( $this->mFunctionHooks );
5215 * Create a tag function, e.g. "<test>some stuff</test>".
5216 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5217 * Unlike parser functions, their content is not preprocessed.
5218 * @param string $tag
5219 * @param callable $callback
5220 * @param int $flags
5221 * @throws MWException
5222 * @return null
5224 public function setFunctionTagHook( $tag, $callback, $flags ) {
5225 $tag = strtolower( $tag );
5226 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5227 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5229 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
5230 $this->mFunctionTagHooks[$tag] : null;
5231 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
5233 if ( !in_array( $tag, $this->mStripList ) ) {
5234 $this->mStripList[] = $tag;
5237 return $old;
5241 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5242 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5243 * Placeholders created in Skin::makeLinkObj()
5245 * @param string $text
5246 * @param int $options
5248 public function replaceLinkHolders( &$text, $options = 0 ) {
5249 $this->mLinkHolders->replace( $text );
5253 * Replace "<!--LINK-->" link placeholders with plain text of links
5254 * (not HTML-formatted).
5256 * @param string $text
5257 * @return string
5259 public function replaceLinkHoldersText( $text ) {
5260 return $this->mLinkHolders->replaceText( $text );
5264 * Renders an image gallery from a text with one line per image.
5265 * text labels may be given by using |-style alternative text. E.g.
5266 * Image:one.jpg|The number "1"
5267 * Image:tree.jpg|A tree
5268 * given as text will return the HTML of a gallery with two images,
5269 * labeled 'The number "1"' and
5270 * 'A tree'.
5272 * @param string $text
5273 * @param array $params
5274 * @return string HTML
5276 public function renderImageGallery( $text, $params ) {
5278 $mode = false;
5279 if ( isset( $params['mode'] ) ) {
5280 $mode = $params['mode'];
5283 try {
5284 $ig = ImageGalleryBase::factory( $mode );
5285 } catch ( Exception $e ) {
5286 // If invalid type set, fallback to default.
5287 $ig = ImageGalleryBase::factory( false );
5290 $ig->setContextTitle( $this->mTitle );
5291 $ig->setShowBytes( false );
5292 $ig->setShowFilename( false );
5293 $ig->setParser( $this );
5294 $ig->setHideBadImages();
5295 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
5297 if ( isset( $params['showfilename'] ) ) {
5298 $ig->setShowFilename( true );
5299 } else {
5300 $ig->setShowFilename( false );
5302 if ( isset( $params['caption'] ) ) {
5303 $caption = $params['caption'];
5304 $caption = htmlspecialchars( $caption );
5305 $caption = $this->replaceInternalLinks( $caption );
5306 $ig->setCaptionHtml( $caption );
5308 if ( isset( $params['perrow'] ) ) {
5309 $ig->setPerRow( $params['perrow'] );
5311 if ( isset( $params['widths'] ) ) {
5312 $ig->setWidths( $params['widths'] );
5314 if ( isset( $params['heights'] ) ) {
5315 $ig->setHeights( $params['heights'] );
5317 $ig->setAdditionalOptions( $params );
5319 Hooks::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5321 $lines = StringUtils::explode( "\n", $text );
5322 foreach ( $lines as $line ) {
5323 # match lines like these:
5324 # Image:someimage.jpg|This is some image
5325 $matches = array();
5326 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5327 # Skip empty lines
5328 if ( count( $matches ) == 0 ) {
5329 continue;
5332 if ( strpos( $matches[0], '%' ) !== false ) {
5333 $matches[1] = rawurldecode( $matches[1] );
5335 $title = Title::newFromText( $matches[1], NS_FILE );
5336 if ( is_null( $title ) ) {
5337 # Bogus title. Ignore these so we don't bomb out later.
5338 continue;
5341 # We need to get what handler the file uses, to figure out parameters.
5342 # Note, a hook can overide the file name, and chose an entirely different
5343 # file (which potentially could be of a different type and have different handler).
5344 $options = array();
5345 $descQuery = false;
5346 Hooks::run( 'BeforeParserFetchFileAndTitle',
5347 array( $this, $title, &$options, &$descQuery ) );
5348 # Don't register it now, as ImageGallery does that later.
5349 $file = $this->fetchFileNoRegister( $title, $options );
5350 $handler = $file ? $file->getHandler() : false;
5352 $paramMap = array(
5353 'img_alt' => 'gallery-internal-alt',
5354 'img_link' => 'gallery-internal-link',
5356 if ( $handler ) {
5357 $paramMap = $paramMap + $handler->getParamMap();
5358 // We don't want people to specify per-image widths.
5359 // Additionally the width parameter would need special casing anyhow.
5360 unset( $paramMap['img_width'] );
5363 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5365 $label = '';
5366 $alt = '';
5367 $link = '';
5368 $handlerOptions = array();
5369 if ( isset( $matches[3] ) ) {
5370 // look for an |alt= definition while trying not to break existing
5371 // captions with multiple pipes (|) in it, until a more sensible grammar
5372 // is defined for images in galleries
5374 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5375 // splitting on '|' is a bit odd, and different from makeImage.
5376 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5377 $parameterMatches = StringUtils::explode( '|', $matches[3] );
5379 foreach ( $parameterMatches as $parameterMatch ) {
5380 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5381 if ( $magicName ) {
5382 $paramName = $paramMap[$magicName];
5384 switch ( $paramName ) {
5385 case 'gallery-internal-alt':
5386 $alt = $this->stripAltText( $match, false );
5387 break;
5388 case 'gallery-internal-link':
5389 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5390 $chars = self::EXT_LINK_URL_CLASS;
5391 $prots = $this->mUrlProtocols;
5392 //check to see if link matches an absolute url, if not then it must be a wiki link.
5393 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5394 $link = $linkValue;
5395 } else {
5396 $localLinkTitle = Title::newFromText( $linkValue );
5397 if ( $localLinkTitle !== null ) {
5398 $link = $localLinkTitle->getLinkURL();
5401 break;
5402 default:
5403 // Must be a handler specific parameter.
5404 if ( $handler->validateParam( $paramName, $match ) ) {
5405 $handlerOptions[$paramName] = $match;
5406 } else {
5407 // Guess not. Append it to the caption.
5408 wfDebug( "$parameterMatch failed parameter validation\n" );
5409 $label .= '|' . $parameterMatch;
5413 } else {
5414 // concatenate all other pipes
5415 $label .= '|' . $parameterMatch;
5418 // remove the first pipe
5419 $label = substr( $label, 1 );
5422 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5424 $html = $ig->toHTML();
5425 Hooks::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5426 return $html;
5430 * @param string $handler
5431 * @return array
5433 public function getImageParams( $handler ) {
5434 if ( $handler ) {
5435 $handlerClass = get_class( $handler );
5436 } else {
5437 $handlerClass = '';
5439 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5440 # Initialise static lists
5441 static $internalParamNames = array(
5442 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5443 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5444 'bottom', 'text-bottom' ),
5445 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5446 'upright', 'border', 'link', 'alt', 'class' ),
5448 static $internalParamMap;
5449 if ( !$internalParamMap ) {
5450 $internalParamMap = array();
5451 foreach ( $internalParamNames as $type => $names ) {
5452 foreach ( $names as $name ) {
5453 $magicName = str_replace( '-', '_', "img_$name" );
5454 $internalParamMap[$magicName] = array( $type, $name );
5459 # Add handler params
5460 $paramMap = $internalParamMap;
5461 if ( $handler ) {
5462 $handlerParamMap = $handler->getParamMap();
5463 foreach ( $handlerParamMap as $magic => $paramName ) {
5464 $paramMap[$magic] = array( 'handler', $paramName );
5467 $this->mImageParams[$handlerClass] = $paramMap;
5468 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5470 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5474 * Parse image options text and use it to make an image
5476 * @param Title $title
5477 * @param string $options
5478 * @param LinkHolderArray|bool $holders
5479 * @return string HTML
5481 public function makeImage( $title, $options, $holders = false ) {
5482 # Check if the options text is of the form "options|alt text"
5483 # Options are:
5484 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5485 # * left no resizing, just left align. label is used for alt= only
5486 # * right same, but right aligned
5487 # * none same, but not aligned
5488 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5489 # * center center the image
5490 # * frame Keep original image size, no magnify-button.
5491 # * framed Same as "frame"
5492 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5493 # * upright reduce width for upright images, rounded to full __0 px
5494 # * border draw a 1px border around the image
5495 # * alt Text for HTML alt attribute (defaults to empty)
5496 # * class Set a class for img node
5497 # * link Set the target of the image link. Can be external, interwiki, or local
5498 # vertical-align values (no % or length right now):
5499 # * baseline
5500 # * sub
5501 # * super
5502 # * top
5503 # * text-top
5504 # * middle
5505 # * bottom
5506 # * text-bottom
5508 $parts = StringUtils::explode( "|", $options );
5510 # Give extensions a chance to select the file revision for us
5511 $options = array();
5512 $descQuery = false;
5513 Hooks::run( 'BeforeParserFetchFileAndTitle',
5514 array( $this, $title, &$options, &$descQuery ) );
5515 # Fetch and register the file (file title may be different via hooks)
5516 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5518 # Get parameter map
5519 $handler = $file ? $file->getHandler() : false;
5521 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5523 if ( !$file ) {
5524 $this->addTrackingCategory( 'broken-file-category' );
5527 # Process the input parameters
5528 $caption = '';
5529 $params = array( 'frame' => array(), 'handler' => array(),
5530 'horizAlign' => array(), 'vertAlign' => array() );
5531 $seenformat = false;
5532 foreach ( $parts as $part ) {
5533 $part = trim( $part );
5534 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5535 $validated = false;
5536 if ( isset( $paramMap[$magicName] ) ) {
5537 list( $type, $paramName ) = $paramMap[$magicName];
5539 # Special case; width and height come in one variable together
5540 if ( $type === 'handler' && $paramName === 'width' ) {
5541 $parsedWidthParam = $this->parseWidthParam( $value );
5542 if ( isset( $parsedWidthParam['width'] ) ) {
5543 $width = $parsedWidthParam['width'];
5544 if ( $handler->validateParam( 'width', $width ) ) {
5545 $params[$type]['width'] = $width;
5546 $validated = true;
5549 if ( isset( $parsedWidthParam['height'] ) ) {
5550 $height = $parsedWidthParam['height'];
5551 if ( $handler->validateParam( 'height', $height ) ) {
5552 $params[$type]['height'] = $height;
5553 $validated = true;
5556 # else no validation -- bug 13436
5557 } else {
5558 if ( $type === 'handler' ) {
5559 # Validate handler parameter
5560 $validated = $handler->validateParam( $paramName, $value );
5561 } else {
5562 # Validate internal parameters
5563 switch ( $paramName ) {
5564 case 'manualthumb':
5565 case 'alt':
5566 case 'class':
5567 # @todo FIXME: Possibly check validity here for
5568 # manualthumb? downstream behavior seems odd with
5569 # missing manual thumbs.
5570 $validated = true;
5571 $value = $this->stripAltText( $value, $holders );
5572 break;
5573 case 'link':
5574 $chars = self::EXT_LINK_URL_CLASS;
5575 $prots = $this->mUrlProtocols;
5576 if ( $value === '' ) {
5577 $paramName = 'no-link';
5578 $value = true;
5579 $validated = true;
5580 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5581 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5582 $paramName = 'link-url';
5583 $this->mOutput->addExternalLink( $value );
5584 if ( $this->mOptions->getExternalLinkTarget() ) {
5585 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5587 $validated = true;
5589 } else {
5590 $linkTitle = Title::newFromText( $value );
5591 if ( $linkTitle ) {
5592 $paramName = 'link-title';
5593 $value = $linkTitle;
5594 $this->mOutput->addLink( $linkTitle );
5595 $validated = true;
5598 break;
5599 case 'frameless':
5600 case 'framed':
5601 case 'thumbnail':
5602 // use first appearing option, discard others.
5603 $validated = ! $seenformat;
5604 $seenformat = true;
5605 break;
5606 default:
5607 # Most other things appear to be empty or numeric...
5608 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5612 if ( $validated ) {
5613 $params[$type][$paramName] = $value;
5617 if ( !$validated ) {
5618 $caption = $part;
5622 # Process alignment parameters
5623 if ( $params['horizAlign'] ) {
5624 $params['frame']['align'] = key( $params['horizAlign'] );
5626 if ( $params['vertAlign'] ) {
5627 $params['frame']['valign'] = key( $params['vertAlign'] );
5630 $params['frame']['caption'] = $caption;
5632 # Will the image be presented in a frame, with the caption below?
5633 $imageIsFramed = isset( $params['frame']['frame'] )
5634 || isset( $params['frame']['framed'] )
5635 || isset( $params['frame']['thumbnail'] )
5636 || isset( $params['frame']['manualthumb'] );
5638 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5639 # came to also set the caption, ordinary text after the image -- which
5640 # makes no sense, because that just repeats the text multiple times in
5641 # screen readers. It *also* came to set the title attribute.
5643 # Now that we have an alt attribute, we should not set the alt text to
5644 # equal the caption: that's worse than useless, it just repeats the
5645 # text. This is the framed/thumbnail case. If there's no caption, we
5646 # use the unnamed parameter for alt text as well, just for the time be-
5647 # ing, if the unnamed param is set and the alt param is not.
5649 # For the future, we need to figure out if we want to tweak this more,
5650 # e.g., introducing a title= parameter for the title; ignoring the un-
5651 # named parameter entirely for images without a caption; adding an ex-
5652 # plicit caption= parameter and preserving the old magic unnamed para-
5653 # meter for BC; ...
5654 if ( $imageIsFramed ) { # Framed image
5655 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5656 # No caption or alt text, add the filename as the alt text so
5657 # that screen readers at least get some description of the image
5658 $params['frame']['alt'] = $title->getText();
5660 # Do not set $params['frame']['title'] because tooltips don't make sense
5661 # for framed images
5662 } else { # Inline image
5663 if ( !isset( $params['frame']['alt'] ) ) {
5664 # No alt text, use the "caption" for the alt text
5665 if ( $caption !== '' ) {
5666 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5667 } else {
5668 # No caption, fall back to using the filename for the
5669 # alt text
5670 $params['frame']['alt'] = $title->getText();
5673 # Use the "caption" for the tooltip text
5674 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5677 Hooks::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5679 # Linker does the rest
5680 $time = isset( $options['time'] ) ? $options['time'] : false;
5681 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5682 $time, $descQuery, $this->mOptions->getThumbSize() );
5684 # Give the handler a chance to modify the parser object
5685 if ( $handler ) {
5686 $handler->parserTransformHook( $this, $file );
5689 return $ret;
5693 * @param string $caption
5694 * @param LinkHolderArray|bool $holders
5695 * @return mixed|string
5697 protected function stripAltText( $caption, $holders ) {
5698 # Strip bad stuff out of the title (tooltip). We can't just use
5699 # replaceLinkHoldersText() here, because if this function is called
5700 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5701 if ( $holders ) {
5702 $tooltip = $holders->replaceText( $caption );
5703 } else {
5704 $tooltip = $this->replaceLinkHoldersText( $caption );
5707 # make sure there are no placeholders in thumbnail attributes
5708 # that are later expanded to html- so expand them now and
5709 # remove the tags
5710 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5711 $tooltip = Sanitizer::stripAllTags( $tooltip );
5713 return $tooltip;
5717 * Set a flag in the output object indicating that the content is dynamic and
5718 * shouldn't be cached.
5720 public function disableCache() {
5721 wfDebug( "Parser output marked as uncacheable.\n" );
5722 if ( !$this->mOutput ) {
5723 throw new MWException( __METHOD__ .
5724 " can only be called when actually parsing something" );
5726 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5727 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5731 * Callback from the Sanitizer for expanding items found in HTML attribute
5732 * values, so they can be safely tested and escaped.
5734 * @param string $text
5735 * @param bool|PPFrame $frame
5736 * @return string
5738 public function attributeStripCallback( &$text, $frame = false ) {
5739 $text = $this->replaceVariables( $text, $frame );
5740 $text = $this->mStripState->unstripBoth( $text );
5741 return $text;
5745 * Accessor
5747 * @return array
5749 public function getTags() {
5750 return array_merge(
5751 array_keys( $this->mTransparentTagHooks ),
5752 array_keys( $this->mTagHooks ),
5753 array_keys( $this->mFunctionTagHooks )
5758 * Replace transparent tags in $text with the values given by the callbacks.
5760 * Transparent tag hooks are like regular XML-style tag hooks, except they
5761 * operate late in the transformation sequence, on HTML instead of wikitext.
5763 * @param string $text
5765 * @return string
5767 public function replaceTransparentTags( $text ) {
5768 $matches = array();
5769 $elements = array_keys( $this->mTransparentTagHooks );
5770 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5771 $replacements = array();
5773 foreach ( $matches as $marker => $data ) {
5774 list( $element, $content, $params, $tag ) = $data;
5775 $tagName = strtolower( $element );
5776 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5777 $output = call_user_func_array(
5778 $this->mTransparentTagHooks[$tagName],
5779 array( $content, $params, $this )
5781 } else {
5782 $output = $tag;
5784 $replacements[$marker] = $output;
5786 return strtr( $text, $replacements );
5790 * Break wikitext input into sections, and either pull or replace
5791 * some particular section's text.
5793 * External callers should use the getSection and replaceSection methods.
5795 * @param string $text Page wikitext
5796 * @param string|number $sectionId A section identifier string of the form:
5797 * "<flag1> - <flag2> - ... - <section number>"
5799 * Currently the only recognised flag is "T", which means the target section number
5800 * was derived during a template inclusion parse, in other words this is a template
5801 * section edit link. If no flags are given, it was an ordinary section edit link.
5802 * This flag is required to avoid a section numbering mismatch when a section is
5803 * enclosed by "<includeonly>" (bug 6563).
5805 * The section number 0 pulls the text before the first heading; other numbers will
5806 * pull the given section along with its lower-level subsections. If the section is
5807 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5809 * Section 0 is always considered to exist, even if it only contains the empty
5810 * string. If $text is the empty string and section 0 is replaced, $newText is
5811 * returned.
5813 * @param string $mode One of "get" or "replace"
5814 * @param string $newText Replacement text for section data.
5815 * @return string For "get", the extracted section text.
5816 * for "replace", the whole page with the section replaced.
5818 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5819 global $wgTitle; # not generally used but removes an ugly failure mode
5821 $magicScopeVariable = $this->lock();
5822 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5823 $outText = '';
5824 $frame = $this->getPreprocessor()->newFrame();
5826 # Process section extraction flags
5827 $flags = 0;
5828 $sectionParts = explode( '-', $sectionId );
5829 $sectionIndex = array_pop( $sectionParts );
5830 foreach ( $sectionParts as $part ) {
5831 if ( $part === 'T' ) {
5832 $flags |= self::PTD_FOR_INCLUSION;
5836 # Check for empty input
5837 if ( strval( $text ) === '' ) {
5838 # Only sections 0 and T-0 exist in an empty document
5839 if ( $sectionIndex == 0 ) {
5840 if ( $mode === 'get' ) {
5841 return '';
5842 } else {
5843 return $newText;
5845 } else {
5846 if ( $mode === 'get' ) {
5847 return $newText;
5848 } else {
5849 return $text;
5854 # Preprocess the text
5855 $root = $this->preprocessToDom( $text, $flags );
5857 # <h> nodes indicate section breaks
5858 # They can only occur at the top level, so we can find them by iterating the root's children
5859 $node = $root->getFirstChild();
5861 # Find the target section
5862 if ( $sectionIndex == 0 ) {
5863 # Section zero doesn't nest, level=big
5864 $targetLevel = 1000;
5865 } else {
5866 while ( $node ) {
5867 if ( $node->getName() === 'h' ) {
5868 $bits = $node->splitHeading();
5869 if ( $bits['i'] == $sectionIndex ) {
5870 $targetLevel = $bits['level'];
5871 break;
5874 if ( $mode === 'replace' ) {
5875 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5877 $node = $node->getNextSibling();
5881 if ( !$node ) {
5882 # Not found
5883 if ( $mode === 'get' ) {
5884 return $newText;
5885 } else {
5886 return $text;
5890 # Find the end of the section, including nested sections
5891 do {
5892 if ( $node->getName() === 'h' ) {
5893 $bits = $node->splitHeading();
5894 $curLevel = $bits['level'];
5895 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5896 break;
5899 if ( $mode === 'get' ) {
5900 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5902 $node = $node->getNextSibling();
5903 } while ( $node );
5905 # Write out the remainder (in replace mode only)
5906 if ( $mode === 'replace' ) {
5907 # Output the replacement text
5908 # Add two newlines on -- trailing whitespace in $newText is conventionally
5909 # stripped by the editor, so we need both newlines to restore the paragraph gap
5910 # Only add trailing whitespace if there is newText
5911 if ( $newText != "" ) {
5912 $outText .= $newText . "\n\n";
5915 while ( $node ) {
5916 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5917 $node = $node->getNextSibling();
5921 if ( is_string( $outText ) ) {
5922 # Re-insert stripped tags
5923 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5926 return $outText;
5930 * This function returns the text of a section, specified by a number ($section).
5931 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5932 * the first section before any such heading (section 0).
5934 * If a section contains subsections, these are also returned.
5936 * @param string $text Text to look in
5937 * @param string|number $sectionId Section identifier as a number or string
5938 * (e.g. 0, 1 or 'T-1').
5939 * @param string $defaultText Default to return if section is not found
5941 * @return string Text of the requested section
5943 public function getSection( $text, $sectionId, $defaultText = '' ) {
5944 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5948 * This function returns $oldtext after the content of the section
5949 * specified by $section has been replaced with $text. If the target
5950 * section does not exist, $oldtext is returned unchanged.
5952 * @param string $oldText Former text of the article
5953 * @param string|number $sectionId Section identifier as a number or string
5954 * (e.g. 0, 1 or 'T-1').
5955 * @param string $newText Replacing text
5957 * @return string Modified text
5959 public function replaceSection( $oldText, $sectionId, $newText ) {
5960 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5964 * Get the ID of the revision we are parsing
5966 * @return int|null
5968 public function getRevisionId() {
5969 return $this->mRevisionId;
5973 * Get the revision object for $this->mRevisionId
5975 * @return Revision|null Either a Revision object or null
5976 * @since 1.23 (public since 1.23)
5978 public function getRevisionObject() {
5979 if ( !is_null( $this->mRevisionObject ) ) {
5980 return $this->mRevisionObject;
5982 if ( is_null( $this->mRevisionId ) ) {
5983 return null;
5986 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5987 return $this->mRevisionObject;
5991 * Get the timestamp associated with the current revision, adjusted for
5992 * the default server-local timestamp
5993 * @return string
5995 public function getRevisionTimestamp() {
5996 if ( is_null( $this->mRevisionTimestamp ) ) {
5998 global $wgContLang;
6000 $revObject = $this->getRevisionObject();
6001 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
6003 # The cryptic '' timezone parameter tells to use the site-default
6004 # timezone offset instead of the user settings.
6006 # Since this value will be saved into the parser cache, served
6007 # to other users, and potentially even used inside links and such,
6008 # it needs to be consistent for all visitors.
6009 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
6012 return $this->mRevisionTimestamp;
6016 * Get the name of the user that edited the last revision
6018 * @return string User name
6020 public function getRevisionUser() {
6021 if ( is_null( $this->mRevisionUser ) ) {
6022 $revObject = $this->getRevisionObject();
6024 # if this template is subst: the revision id will be blank,
6025 # so just use the current user's name
6026 if ( $revObject ) {
6027 $this->mRevisionUser = $revObject->getUserText();
6028 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
6029 $this->mRevisionUser = $this->getUser()->getName();
6032 return $this->mRevisionUser;
6036 * Get the size of the revision
6038 * @return int|null Revision size
6040 public function getRevisionSize() {
6041 if ( is_null( $this->mRevisionSize ) ) {
6042 $revObject = $this->getRevisionObject();
6044 # if this variable is subst: the revision id will be blank,
6045 # so just use the parser input size, because the own substituation
6046 # will change the size.
6047 if ( $revObject ) {
6048 $this->mRevisionSize = $revObject->getSize();
6049 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
6050 $this->mRevisionSize = $this->mInputSize;
6053 return $this->mRevisionSize;
6057 * Mutator for $mDefaultSort
6059 * @param string $sort New value
6061 public function setDefaultSort( $sort ) {
6062 $this->mDefaultSort = $sort;
6063 $this->mOutput->setProperty( 'defaultsort', $sort );
6067 * Accessor for $mDefaultSort
6068 * Will use the empty string if none is set.
6070 * This value is treated as a prefix, so the
6071 * empty string is equivalent to sorting by
6072 * page name.
6074 * @return string
6076 public function getDefaultSort() {
6077 if ( $this->mDefaultSort !== false ) {
6078 return $this->mDefaultSort;
6079 } else {
6080 return '';
6085 * Accessor for $mDefaultSort
6086 * Unlike getDefaultSort(), will return false if none is set
6088 * @return string|bool
6090 public function getCustomDefaultSort() {
6091 return $this->mDefaultSort;
6095 * Try to guess the section anchor name based on a wikitext fragment
6096 * presumably extracted from a heading, for example "Header" from
6097 * "== Header ==".
6099 * @param string $text
6101 * @return string
6103 public function guessSectionNameFromWikiText( $text ) {
6104 # Strip out wikitext links(they break the anchor)
6105 $text = $this->stripSectionName( $text );
6106 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6107 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
6111 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6112 * instead. For use in redirects, since IE6 interprets Redirect: headers
6113 * as something other than UTF-8 (apparently?), resulting in breakage.
6115 * @param string $text The section name
6116 * @return string An anchor
6118 public function guessLegacySectionNameFromWikiText( $text ) {
6119 # Strip out wikitext links(they break the anchor)
6120 $text = $this->stripSectionName( $text );
6121 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6122 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
6126 * Strips a text string of wikitext for use in a section anchor
6128 * Accepts a text string and then removes all wikitext from the
6129 * string and leaves only the resultant text (i.e. the result of
6130 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6131 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6132 * to create valid section anchors by mimicing the output of the
6133 * parser when headings are parsed.
6135 * @param string $text Text string to be stripped of wikitext
6136 * for use in a Section anchor
6137 * @return string Filtered text string
6139 public function stripSectionName( $text ) {
6140 # Strip internal link markup
6141 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6142 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6144 # Strip external link markup
6145 # @todo FIXME: Not tolerant to blank link text
6146 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6147 # on how many empty links there are on the page - need to figure that out.
6148 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6150 # Parse wikitext quotes (italics & bold)
6151 $text = $this->doQuotes( $text );
6153 # Strip HTML tags
6154 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
6155 return $text;
6159 * strip/replaceVariables/unstrip for preprocessor regression testing
6161 * @param string $text
6162 * @param Title $title
6163 * @param ParserOptions $options
6164 * @param int $outputType
6166 * @return string
6168 public function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
6169 $magicScopeVariable = $this->lock();
6170 $this->startParse( $title, $options, $outputType, true );
6172 $text = $this->replaceVariables( $text );
6173 $text = $this->mStripState->unstripBoth( $text );
6174 $text = Sanitizer::removeHTMLtags( $text );
6175 return $text;
6179 * @param string $text
6180 * @param Title $title
6181 * @param ParserOptions $options
6182 * @return string
6184 public function testPst( $text, Title $title, ParserOptions $options ) {
6185 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6189 * @param string $text
6190 * @param Title $title
6191 * @param ParserOptions $options
6192 * @return string
6194 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
6195 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
6199 * Call a callback function on all regions of the given text that are not
6200 * inside strip markers, and replace those regions with the return value
6201 * of the callback. For example, with input:
6203 * aaa<MARKER>bbb
6205 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6206 * two strings will be replaced with the value returned by the callback in
6207 * each case.
6209 * @param string $s
6210 * @param callable $callback
6212 * @return string
6214 public function markerSkipCallback( $s, $callback ) {
6215 $i = 0;
6216 $out = '';
6217 while ( $i < strlen( $s ) ) {
6218 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
6219 if ( $markerStart === false ) {
6220 $out .= call_user_func( $callback, substr( $s, $i ) );
6221 break;
6222 } else {
6223 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6224 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
6225 if ( $markerEnd === false ) {
6226 $out .= substr( $s, $markerStart );
6227 break;
6228 } else {
6229 $markerEnd += strlen( self::MARKER_SUFFIX );
6230 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6231 $i = $markerEnd;
6235 return $out;
6239 * Remove any strip markers found in the given text.
6241 * @param string $text Input string
6242 * @return string
6244 public function killMarkers( $text ) {
6245 return $this->mStripState->killMarkers( $text );
6249 * Save the parser state required to convert the given half-parsed text to
6250 * HTML. "Half-parsed" in this context means the output of
6251 * recursiveTagParse() or internalParse(). This output has strip markers
6252 * from replaceVariables (extensionSubstitution() etc.), and link
6253 * placeholders from replaceLinkHolders().
6255 * Returns an array which can be serialized and stored persistently. This
6256 * array can later be loaded into another parser instance with
6257 * unserializeHalfParsedText(). The text can then be safely incorporated into
6258 * the return value of a parser hook.
6260 * @param string $text
6262 * @return array
6264 public function serializeHalfParsedText( $text ) {
6265 $data = array(
6266 'text' => $text,
6267 'version' => self::HALF_PARSED_VERSION,
6268 'stripState' => $this->mStripState->getSubState( $text ),
6269 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6271 return $data;
6275 * Load the parser state given in the $data array, which is assumed to
6276 * have been generated by serializeHalfParsedText(). The text contents is
6277 * extracted from the array, and its markers are transformed into markers
6278 * appropriate for the current Parser instance. This transformed text is
6279 * returned, and can be safely included in the return value of a parser
6280 * hook.
6282 * If the $data array has been stored persistently, the caller should first
6283 * check whether it is still valid, by calling isValidHalfParsedText().
6285 * @param array $data Serialized data
6286 * @throws MWException
6287 * @return string
6289 public function unserializeHalfParsedText( $data ) {
6290 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6291 throw new MWException( __METHOD__ . ': invalid version' );
6294 # First, extract the strip state.
6295 $texts = array( $data['text'] );
6296 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6298 # Now renumber links
6299 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6301 # Should be good to go.
6302 return $texts[0];
6306 * Returns true if the given array, presumed to be generated by
6307 * serializeHalfParsedText(), is compatible with the current version of the
6308 * parser.
6310 * @param array $data
6312 * @return bool
6314 public function isValidHalfParsedText( $data ) {
6315 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6319 * Parsed a width param of imagelink like 300px or 200x300px
6321 * @param string $value
6323 * @return array
6324 * @since 1.20
6326 public function parseWidthParam( $value ) {
6327 $parsedWidthParam = array();
6328 if ( $value === '' ) {
6329 return $parsedWidthParam;
6331 $m = array();
6332 # (bug 13500) In both cases (width/height and width only),
6333 # permit trailing "px" for backward compatibility.
6334 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6335 $width = intval( $m[1] );
6336 $height = intval( $m[2] );
6337 $parsedWidthParam['width'] = $width;
6338 $parsedWidthParam['height'] = $height;
6339 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6340 $width = intval( $value );
6341 $parsedWidthParam['width'] = $width;
6343 return $parsedWidthParam;
6347 * Lock the current instance of the parser.
6349 * This is meant to stop someone from calling the parser
6350 * recursively and messing up all the strip state.
6352 * @throws MWException If parser is in a parse
6353 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6355 protected function lock() {
6356 if ( $this->mInParse ) {
6357 throw new MWException( "Parser state cleared while parsing. "
6358 . "Did you call Parser::parse recursively?" );
6360 $this->mInParse = true;
6362 $that = $this;
6363 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6364 $that->mInParse = false;
6365 } );
6367 return $recursiveCheck;
6371 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6373 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6374 * or if there is more than one <p/> tag in the input HTML.
6376 * @param string $html
6377 * @return string
6378 * @since 1.24
6380 public static function stripOuterParagraph( $html ) {
6381 $m = array();
6382 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6383 if ( strpos( $m[1], '</p>' ) === false ) {
6384 $html = $m[1];
6388 return $html;
6392 * Return this parser if it is not doing anything, otherwise
6393 * get a fresh parser. You can use this method by doing
6394 * $myParser = $wgParser->getFreshParser(), or more simply
6395 * $wgParser->getFreshParser()->parse( ... );
6396 * if you're unsure if $wgParser is safe to use.
6398 * @since 1.24
6399 * @return Parser A parser object that is not parsing anything
6401 public function getFreshParser() {
6402 global $wgParserConf;
6403 if ( $this->mInParse ) {
6404 return new $wgParserConf['class']( $wgParserConf );
6405 } else {
6406 return $this;