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
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @defgroup Parser Parser
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
37 * There are seven main entry points into the Parser class:
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
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';
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 T21052
89 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
90 # uses to replace invalid HTML characters.
91 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
92 # Simplified expression to match an IPv4 or IPv6 address, or
93 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
94 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
95 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
96 // phpcs:ignore Generic.Files.LineLength
97 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
98 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
100 # Regular expression for a non-newline space
101 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
103 # Flags for preprocessToDom
104 const PTD_FOR_INCLUSION
= 1;
106 # Allowed values for $this->mOutputType
107 # Parameter to startExternalParse().
108 const OT_HTML
= 1; # like parse()
109 const OT_WIKI
= 2; # like preSaveTransform()
110 const OT_PREPROCESS
= 3; # like preprocess()
112 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 * @var string Prefix and suffix for temporary replacement strings
116 * for the multipass parser.
118 * \x7f should never appear in input as it's disallowed in XML.
119 * Using it at the front also gives us a little extra robustness
120 * since it shouldn't match when butted up against identifier-like
123 * Must not consist of all title characters, or else it will change
124 * the behavior of <nowiki> in a link.
126 * Must have a character that needs escaping in attributes, otherwise
127 * someone could put a strip marker in an attribute, to get around
128 * escaping quote marks, and break out of the attribute. Thus we add
131 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
132 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
134 # Markers used for wrapping the table of contents
135 const TOC_START
= '<mw:toc>';
136 const TOC_END
= '</mw:toc>';
138 /** @var int Assume that no output will later be saved this many seconds after parsing */
142 public $mTagHooks = [];
143 public $mTransparentTagHooks = [];
144 public $mFunctionHooks = [];
145 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
146 public $mFunctionTagHooks = [];
147 public $mStripList = [];
148 public $mDefaultStripList = [];
149 public $mVarCache = [];
150 public $mImageParams = [];
151 public $mImageParamsMagicArray = [];
152 public $mMarkerIndex = 0;
154 * @var bool Whether firstCallInit still needs to be called
156 public $mFirstCall = true;
158 # Initialised by initialiseVariables()
161 * @var MagicWordArray
166 * @var MagicWordArray
169 # Initialised in constructor
170 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
172 # Initialized in getPreprocessor()
173 /** @var Preprocessor */
174 public $mPreprocessor;
176 # Cleared with clearState():
188 public $mIncludeCount;
190 * @var LinkHolderArray
192 public $mLinkHolders;
195 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
196 public $mDefaultSort;
197 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
198 public $mExpensiveFunctionCount; # number of expensive parser function calls
199 public $mShowToc, $mForceTocPosition;
204 public $mUser; # User object; only used when doing pre-save transform
207 # These are variables reset at least once per parse regardless of $clearState
217 public $mTitle; # Title context, used for self-link rendering and similar things
218 public $mOutputType; # Output type, one of the OT_xxx constants
219 public $ot; # Shortcut alias, see setOutputType()
220 public $mRevisionObject; # The revision object of the specified revision ID
221 public $mRevisionId; # ID to display in {{REVISIONID}} tags
222 public $mRevisionTimestamp; # The timestamp of the specified revision ID
223 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
224 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
225 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
226 public $mInputSize = false; # For {{PAGESIZE}} on current page.
229 * @var string Deprecated accessor for the strip marker prefix.
230 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
232 public $mUniqPrefix = self
::MARKER_PREFIX
;
235 * @var array Array with the language name of each language link (i.e. the
236 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
237 * duplicate language links to the ParserOutput.
239 public $mLangLinkLanguages;
242 * @var MapCacheLRU|null
245 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
247 public $currentRevisionCache;
250 * @var bool|string Recursive call protection.
251 * This variable should be treated as if it were private.
253 public $mInParse = false;
255 /** @var SectionProfiler */
256 protected $mProfiler;
261 protected $mLinkRenderer;
263 /** @var MagicWordFactory */
264 private $magicWordFactory;
268 * @param MagicWordFactory|null $magicWordFactory
270 public function __construct( $conf = [], MagicWordFactory
$magicWordFactory = null ) {
271 $this->mConf
= $conf;
272 $this->mUrlProtocols
= wfUrlProtocols();
273 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
274 self
::EXT_LINK_ADDR
.
275 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
276 if ( isset( $conf['preprocessorClass'] ) ) {
277 $this->mPreprocessorClass
= $conf['preprocessorClass'];
278 } elseif ( defined( 'HPHP_VERSION' ) ) {
279 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
280 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
281 } elseif ( extension_loaded( 'domxml' ) ) {
282 # PECL extension that conflicts with the core DOM extension (T15770)
283 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
284 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
285 } elseif ( extension_loaded( 'dom' ) ) {
286 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
288 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
290 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
292 $this->magicWordFactory
= $magicWordFactory;
293 if ( !$magicWordFactory ) {
294 $this->magicWordFactory
= MediaWikiServices
::getInstance()->getMagicWordFactory();
299 * Reduce memory usage to reduce the impact of circular references
301 public function __destruct() {
302 if ( isset( $this->mLinkHolders
) ) {
303 unset( $this->mLinkHolders
);
305 foreach ( $this as $name => $value ) {
306 unset( $this->$name );
311 * Allow extensions to clean up when the parser is cloned
313 public function __clone() {
314 $this->mInParse
= false;
316 // T58226: When you create a reference "to" an object field, that
317 // makes the object field itself be a reference too (until the other
318 // reference goes out of scope). When cloning, any field that's a
319 // reference is copied as a reference in the new object. Both of these
320 // are defined PHP5 behaviors, as inconvenient as it is for us when old
321 // hooks from PHP4 days are passing fields by reference.
322 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
323 // Make a non-reference copy of the field, then rebind the field to
324 // reference the new copy.
330 Hooks
::run( 'ParserCloned', [ $this ] );
334 * Do various kinds of initialisation on the first call of the parser
336 public function firstCallInit() {
337 if ( !$this->mFirstCall
) {
340 $this->mFirstCall
= false;
342 CoreParserFunctions
::register( $this );
343 CoreTagHooks
::register( $this );
344 $this->initialiseVariables();
346 // Avoid PHP 7.1 warning from passing $this by reference
348 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
356 public function clearState() {
357 $this->firstCallInit();
358 $this->mOutput
= new ParserOutput
;
359 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
360 $this->mAutonumber
= 0;
361 $this->mIncludeCount
= [];
362 $this->mLinkHolders
= new LinkHolderArray( $this );
364 $this->mRevisionObject
= $this->mRevisionTimestamp
=
365 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
366 $this->mVarCache
= [];
368 $this->mLangLinkLanguages
= [];
369 $this->currentRevisionCache
= null;
371 $this->mStripState
= new StripState( $this );
373 # Clear these on every parse, T6549
374 $this->mTplRedirCache
= $this->mTplDomCache
= [];
376 $this->mShowToc
= true;
377 $this->mForceTocPosition
= false;
378 $this->mIncludeSizes
= [
382 $this->mPPNodeCount
= 0;
383 $this->mGeneratedPPNodeCount
= 0;
384 $this->mHighestExpansionDepth
= 0;
385 $this->mDefaultSort
= false;
386 $this->mHeadings
= [];
387 $this->mDoubleUnderscores
= [];
388 $this->mExpensiveFunctionCount
= 0;
391 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
392 $this->mPreprocessor
= null;
395 $this->mProfiler
= new SectionProfiler();
397 // Avoid PHP 7.1 warning from passing $this by reference
399 Hooks
::run( 'ParserClearState', [ &$parser ] );
403 * Convert wikitext to HTML
404 * Do not call this function recursively.
406 * @param string $text Text we want to parse
407 * @param Title $title
408 * @param ParserOptions $options
409 * @param bool $linestart
410 * @param bool $clearState
411 * @param int|null $revid Number to pass in {{REVISIONID}}
412 * @return ParserOutput A ParserOutput
414 public function parse(
415 $text, Title
$title, ParserOptions
$options,
416 $linestart = true, $clearState = true, $revid = null
419 // We use U+007F DELETE to construct strip markers, so we have to make
420 // sure that this character does not occur in the input text.
421 $text = strtr( $text, "\x7f", "?" );
422 $magicScopeVariable = $this->lock();
424 // Strip U+0000 NULL (T159174)
425 $text = str_replace( "\000", '', $text );
427 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
429 $this->currentRevisionCache
= null;
430 $this->mInputSize
= strlen( $text );
431 if ( $this->mOptions
->getEnableLimitReport() ) {
432 $this->mOutput
->resetParseStartTime();
435 $oldRevisionId = $this->mRevisionId
;
436 $oldRevisionObject = $this->mRevisionObject
;
437 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
438 $oldRevisionUser = $this->mRevisionUser
;
439 $oldRevisionSize = $this->mRevisionSize
;
440 if ( $revid !== null ) {
441 $this->mRevisionId
= $revid;
442 $this->mRevisionObject
= null;
443 $this->mRevisionTimestamp
= null;
444 $this->mRevisionUser
= null;
445 $this->mRevisionSize
= null;
448 // Avoid PHP 7.1 warning from passing $this by reference
450 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
452 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
453 $text = $this->internalParse( $text );
454 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
456 $text = $this->internalParseHalfParsed( $text, true, $linestart );
459 * A converted title will be provided in the output object if title and
460 * content conversion are enabled, the article text does not contain
461 * a conversion-suppressing double-underscore tag, and no
462 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
463 * automatic link conversion.
465 if ( !( $options->getDisableTitleConversion()
466 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
467 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
468 ||
$this->mOutput
->getDisplayTitle() !== false )
470 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
471 if ( $convruletitle ) {
472 $this->mOutput
->setTitleText( $convruletitle );
474 $titleText = $this->getTargetLanguage()->convertTitle( $title );
475 $this->mOutput
->setTitleText( $titleText );
479 # Compute runtime adaptive expiry if set
480 $this->mOutput
->finalizeAdaptiveCacheExpiry();
482 # Warn if too many heavyweight parser functions were used
483 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
484 $this->limitationWarn( 'expensive-parserfunction',
485 $this->mExpensiveFunctionCount
,
486 $this->mOptions
->getExpensiveParserFunctionLimit()
490 # Information on limits, for the benefit of users who try to skirt them
491 if ( $this->mOptions
->getEnableLimitReport() ) {
492 $text .= $this->makeLimitReport();
495 # Wrap non-interface parser output in a <div> so it can be targeted
497 $class = $this->mOptions
->getWrapOutputClass();
498 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
499 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
502 $this->mOutput
->setText( $text );
504 $this->mRevisionId
= $oldRevisionId;
505 $this->mRevisionObject
= $oldRevisionObject;
506 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
507 $this->mRevisionUser
= $oldRevisionUser;
508 $this->mRevisionSize
= $oldRevisionSize;
509 $this->mInputSize
= false;
510 $this->currentRevisionCache
= null;
512 return $this->mOutput
;
516 * Set the limit report data in the current ParserOutput, and return the
517 * limit report HTML comment.
521 protected function makeLimitReport() {
522 global $wgShowHostnames;
524 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
526 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
527 if ( $cpuTime !== null ) {
528 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
529 sprintf( "%.3f", $cpuTime )
533 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
534 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
535 sprintf( "%.3f", $wallTime )
538 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
539 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
541 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
542 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
544 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
545 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
547 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
548 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
550 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
551 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
553 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
554 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
557 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
558 $this->mOutput
->setLimitReportData( $key, $value );
561 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
563 $limitReport = "NewPP limit report\n";
564 if ( $wgShowHostnames ) {
565 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
567 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
568 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
569 $limitReport .= 'Dynamic content: ' .
570 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
573 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
574 if ( Hooks
::run( 'ParserLimitReportFormat',
575 [ $key, &$value, &$limitReport, false, false ]
577 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
578 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
579 ->inLanguage( 'en' )->useDatabase( false );
580 if ( !$valueMsg->exists() ) {
581 $valueMsg = new RawMessage( '$1' );
583 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
584 $valueMsg->params( $value );
585 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
589 // Since we're not really outputting HTML, decode the entities and
590 // then re-encode the things that need hiding inside HTML comments.
591 $limitReport = htmlspecialchars_decode( $limitReport );
592 // Run deprecated hook
593 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
595 // Sanitize for comment. Note '‐' in the replacement is U+2010,
596 // which looks much like the problematic '-'.
597 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
598 $text = "\n<!-- \n$limitReport-->\n";
600 // Add on template profiling data in human/machine readable way
601 $dataByFunc = $this->mProfiler
->getFunctionStats();
602 uasort( $dataByFunc, function ( $a, $b ) {
603 return $b['real'] <=> $a['real']; // descending order
606 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
607 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
608 $item['%real'], $item['real'], $item['calls'],
609 htmlspecialchars( $item['name'] ) );
611 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
612 $text .= implode( "\n", $profileReport ) . "\n-->\n";
614 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
616 // Add other cache related metadata
617 if ( $wgShowHostnames ) {
618 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
620 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
621 $this->mOutput
->getCacheTime() );
622 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
623 $this->mOutput
->getCacheExpiry() );
624 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
625 $this->mOutput
->hasDynamicContent() );
627 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
628 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
629 $this->mTitle
->getPrefixedDBkey() );
635 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
636 * can be called from an extension tag hook.
638 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
639 * instead, which means that lists and links have not been fully parsed yet,
640 * and strip markers are still present.
642 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
644 * Use this function if you're a parser tag hook and you want to parse
645 * wikitext before or after applying additional transformations, and you
646 * intend to *return the result as hook output*, which will cause it to go
647 * through the rest of parsing process automatically.
649 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
650 * $text are not expanded
652 * @param string $text Text extension wants to have parsed
653 * @param bool|PPFrame $frame The frame to use for expanding any template variables
654 * @return string UNSAFE half-parsed HTML
656 public function recursiveTagParse( $text, $frame = false ) {
657 // Avoid PHP 7.1 warning from passing $this by reference
659 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
660 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
661 $text = $this->internalParse( $text, false, $frame );
666 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
667 * point can be called from an extension tag hook.
669 * The output of this function is fully-parsed HTML that is safe for output.
670 * If you're a parser tag hook, you might want to use recursiveTagParse()
673 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
674 * $text are not expanded
678 * @param string $text Text extension wants to have parsed
679 * @param bool|PPFrame $frame The frame to use for expanding any template variables
680 * @return string Fully parsed HTML
682 public function recursiveTagParseFully( $text, $frame = false ) {
683 $text = $this->recursiveTagParse( $text, $frame );
684 $text = $this->internalParseHalfParsed( $text, false );
689 * Expand templates and variables in the text, producing valid, static wikitext.
690 * Also removes comments.
691 * Do not call this function recursively.
692 * @param string $text
693 * @param Title|null $title
694 * @param ParserOptions $options
695 * @param int|null $revid
696 * @param bool|PPFrame $frame
697 * @return mixed|string
699 public function preprocess( $text, Title
$title = null,
700 ParserOptions
$options, $revid = null, $frame = false
702 $magicScopeVariable = $this->lock();
703 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
704 if ( $revid !== null ) {
705 $this->mRevisionId
= $revid;
707 // Avoid PHP 7.1 warning from passing $this by reference
709 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
710 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
711 $text = $this->replaceVariables( $text, $frame );
712 $text = $this->mStripState
->unstripBoth( $text );
717 * Recursive parser entry point that can be called from an extension tag
720 * @param string $text Text to be expanded
721 * @param bool|PPFrame $frame The frame to use for expanding any template variables
725 public function recursivePreprocess( $text, $frame = false ) {
726 $text = $this->replaceVariables( $text, $frame );
727 $text = $this->mStripState
->unstripBoth( $text );
732 * Process the wikitext for the "?preload=" feature. (T7210)
734 * "<noinclude>", "<includeonly>" etc. are parsed as for template
735 * transclusion, comments, templates, arguments, tags hooks and parser
736 * functions are untouched.
738 * @param string $text
739 * @param Title $title
740 * @param ParserOptions $options
741 * @param array $params
744 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
745 $msg = new RawMessage( $text );
746 $text = $msg->params( $params )->plain();
748 # Parser (re)initialisation
749 $magicScopeVariable = $this->lock();
750 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
752 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
753 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
754 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
755 $text = $this->mStripState
->unstripBoth( $text );
760 * Set the current user.
761 * Should only be used when doing pre-save transform.
763 * @param User|null $user User object or null (to reset)
765 public function setUser( $user ) {
766 $this->mUser
= $user;
770 * Set the context title
774 public function setTitle( $t ) {
776 $t = Title
::newFromText( 'NO TITLE' );
779 if ( $t->hasFragment() ) {
780 # Strip the fragment to avoid various odd effects
781 $this->mTitle
= $t->createFragmentTarget( '' );
788 * Accessor for the Title object
792 public function getTitle() {
793 return $this->mTitle
;
797 * Accessor/mutator for the Title object
799 * @param Title|null $x Title object or null to just get the current one
802 public function Title( $x = null ) {
803 return wfSetVar( $this->mTitle
, $x );
807 * Set the output type
809 * @param int $ot New value
811 public function setOutputType( $ot ) {
812 $this->mOutputType
= $ot;
815 'html' => $ot == self
::OT_HTML
,
816 'wiki' => $ot == self
::OT_WIKI
,
817 'pre' => $ot == self
::OT_PREPROCESS
,
818 'plain' => $ot == self
::OT_PLAIN
,
823 * Accessor/mutator for the output type
825 * @param int|null $x New value or null to just get the current one
828 public function OutputType( $x = null ) {
829 return wfSetVar( $this->mOutputType
, $x );
833 * Get the ParserOutput object
835 * @return ParserOutput
837 public function getOutput() {
838 return $this->mOutput
;
842 * Get the ParserOptions object
844 * @return ParserOptions
846 public function getOptions() {
847 return $this->mOptions
;
851 * Accessor/mutator for the ParserOptions object
853 * @param ParserOptions|null $x New value or null to just get the current one
854 * @return ParserOptions Current ParserOptions object
856 public function Options( $x = null ) {
857 return wfSetVar( $this->mOptions
, $x );
863 public function nextLinkID() {
864 return $this->mLinkID++
;
870 public function setLinkID( $id ) {
871 $this->mLinkID
= $id;
875 * Get a language object for use in parser functions such as {{FORMATNUM:}}
878 public function getFunctionLang() {
879 return $this->getTargetLanguage();
883 * Get the target language for the content being parsed. This is usually the
884 * language that the content is in.
888 * @throws MWException
891 public function getTargetLanguage() {
892 $target = $this->mOptions
->getTargetLanguage();
894 if ( $target !== null ) {
896 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
897 return $this->mOptions
->getUserLangObj();
898 } elseif ( is_null( $this->mTitle
) ) {
899 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
902 return $this->mTitle
->getPageLanguage();
906 * Get the language object for language conversion
907 * @deprecated since 1.32, just use getTargetLanguage()
908 * @return Language|null
910 public function getConverterLanguage() {
911 return $this->getTargetLanguage();
915 * Get a User object either from $this->mUser, if set, or from the
916 * ParserOptions object otherwise
920 public function getUser() {
921 if ( !is_null( $this->mUser
) ) {
924 return $this->mOptions
->getUser();
928 * Get a preprocessor object
930 * @return Preprocessor
932 public function getPreprocessor() {
933 if ( !isset( $this->mPreprocessor
) ) {
934 $class = $this->mPreprocessorClass
;
935 $this->mPreprocessor
= new $class( $this );
937 return $this->mPreprocessor
;
941 * Get a LinkRenderer instance to make links with
944 * @return LinkRenderer
946 public function getLinkRenderer() {
947 if ( !$this->mLinkRenderer
) {
948 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
949 ->getLinkRendererFactory()->create();
950 $this->mLinkRenderer
->setStubThreshold(
951 $this->getOptions()->getStubThreshold()
955 return $this->mLinkRenderer
;
959 * Get the MagicWordFactory that this Parser is using
962 * @return MagicWordFactory
964 public function getMagicWordFactory() {
965 return $this->magicWordFactory
;
969 * Get the content language that this Parser is using
974 public function getContentLanguage() {
975 return $this->magicWordFactory
->getContentLanguage();
979 * Replaces all occurrences of HTML-style comments and the given tags
980 * in the text with a random marker and returns the next text. The output
981 * parameter $matches will be an associative array filled with data in
988 * [ 'param' => 'x' ],
989 * '<element param="x">tag content</element>' ]
992 * @param array $elements List of element names. Comments are always extracted.
993 * @param string $text Source text string.
994 * @param array &$matches Out parameter, Array: extracted tags
995 * @return string Stripped text
997 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1002 $taglist = implode( '|', $elements );
1003 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
1005 while ( $text != '' ) {
1006 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1008 if ( count( $p ) < 5 ) {
1011 if ( count( $p ) > 5 ) {
1020 $attributes = $p[2];
1025 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1026 $stripped .= $marker;
1028 if ( $close === '/>' ) {
1029 # Empty element tag, <tag />
1034 if ( $element === '!--' ) {
1037 $end = "/(<\\/$element\\s*>)/i";
1039 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1041 if ( count( $q ) < 3 ) {
1042 # No end tag -- let it run out to the end of the text.
1051 $matches[$marker] = [ $element,
1053 Sanitizer
::decodeTagAttributes( $attributes ),
1054 "<$element$attributes$close$content$tail" ];
1060 * Get a list of strippable XML-like elements
1064 public function getStripList() {
1065 return $this->mStripList
;
1069 * Add an item to the strip state
1070 * Returns the unique tag which must be inserted into the stripped text
1071 * The tag will be replaced with the original text in unstrip()
1073 * @param string $text
1077 public function insertStripItem( $text ) {
1078 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1079 $this->mMarkerIndex++
;
1080 $this->mStripState
->addGeneral( $marker, $text );
1085 * parse the wiki syntax used to render tables
1088 * @param string $text
1091 public function doTableStuff( $text ) {
1092 $lines = StringUtils
::explode( "\n", $text );
1094 $td_history = []; # Is currently a td tag open?
1095 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1096 $tr_history = []; # Is currently a tr tag open?
1097 $tr_attributes = []; # history of tr attributes
1098 $has_opened_tr = []; # Did this table open a <tr> element?
1099 $indent_level = 0; # indent level of the table
1101 foreach ( $lines as $outLine ) {
1102 $line = trim( $outLine );
1104 if ( $line === '' ) { # empty line, go to next line
1105 $out .= $outLine . "\n";
1109 $first_character = $line[0];
1110 $first_two = substr( $line, 0, 2 );
1113 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1114 # First check if we are starting a new table
1115 $indent_level = strlen( $matches[1] );
1117 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1118 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1120 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1121 array_push( $td_history, false );
1122 array_push( $last_tag_history, '' );
1123 array_push( $tr_history, false );
1124 array_push( $tr_attributes, '' );
1125 array_push( $has_opened_tr, false );
1126 } elseif ( count( $td_history ) == 0 ) {
1127 # Don't do any of the following
1128 $out .= $outLine . "\n";
1130 } elseif ( $first_two === '|}' ) {
1131 # We are ending a table
1132 $line = '</table>' . substr( $line, 2 );
1133 $last_tag = array_pop( $last_tag_history );
1135 if ( !array_pop( $has_opened_tr ) ) {
1136 $line = "<tr><td></td></tr>{$line}";
1139 if ( array_pop( $tr_history ) ) {
1140 $line = "</tr>{$line}";
1143 if ( array_pop( $td_history ) ) {
1144 $line = "</{$last_tag}>{$line}";
1146 array_pop( $tr_attributes );
1147 if ( $indent_level > 0 ) {
1148 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1152 } elseif ( $first_two === '|-' ) {
1153 # Now we have a table row
1154 $line = preg_replace( '#^\|-+#', '', $line );
1156 # Whats after the tag is now only attributes
1157 $attributes = $this->mStripState
->unstripBoth( $line );
1158 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1159 array_pop( $tr_attributes );
1160 array_push( $tr_attributes, $attributes );
1163 $last_tag = array_pop( $last_tag_history );
1164 array_pop( $has_opened_tr );
1165 array_push( $has_opened_tr, true );
1167 if ( array_pop( $tr_history ) ) {
1171 if ( array_pop( $td_history ) ) {
1172 $line = "</{$last_tag}>{$line}";
1176 array_push( $tr_history, false );
1177 array_push( $td_history, false );
1178 array_push( $last_tag_history, '' );
1179 } elseif ( $first_character === '|'
1180 ||
$first_character === '!'
1181 ||
$first_two === '|+'
1183 # This might be cell elements, td, th or captions
1184 if ( $first_two === '|+' ) {
1185 $first_character = '+';
1186 $line = substr( $line, 2 );
1188 $line = substr( $line, 1 );
1191 // Implies both are valid for table headings.
1192 if ( $first_character === '!' ) {
1193 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1196 # Split up multiple cells on the same line.
1197 # FIXME : This can result in improper nesting of tags processed
1198 # by earlier parser steps.
1199 $cells = explode( '||', $line );
1203 # Loop through each table cell
1204 foreach ( $cells as $cell ) {
1206 if ( $first_character !== '+' ) {
1207 $tr_after = array_pop( $tr_attributes );
1208 if ( !array_pop( $tr_history ) ) {
1209 $previous = "<tr{$tr_after}>\n";
1211 array_push( $tr_history, true );
1212 array_push( $tr_attributes, '' );
1213 array_pop( $has_opened_tr );
1214 array_push( $has_opened_tr, true );
1217 $last_tag = array_pop( $last_tag_history );
1219 if ( array_pop( $td_history ) ) {
1220 $previous = "</{$last_tag}>\n{$previous}";
1223 if ( $first_character === '|' ) {
1225 } elseif ( $first_character === '!' ) {
1227 } elseif ( $first_character === '+' ) {
1228 $last_tag = 'caption';
1233 array_push( $last_tag_history, $last_tag );
1235 # A cell could contain both parameters and data
1236 $cell_data = explode( '|', $cell, 2 );
1238 # T2553: Note that a '|' inside an invalid link should not
1239 # be mistaken as delimiting cell parameters
1240 # Bug T153140: Neither should language converter markup.
1241 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1242 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1243 } elseif ( count( $cell_data ) == 1 ) {
1244 // Whitespace in cells is trimmed
1245 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1247 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1248 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1249 // Whitespace in cells is trimmed
1250 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1254 array_push( $td_history, true );
1257 $out .= $outLine . "\n";
1260 # Closing open td, tr && table
1261 while ( count( $td_history ) > 0 ) {
1262 if ( array_pop( $td_history ) ) {
1265 if ( array_pop( $tr_history ) ) {
1268 if ( !array_pop( $has_opened_tr ) ) {
1269 $out .= "<tr><td></td></tr>\n";
1272 $out .= "</table>\n";
1275 # Remove trailing line-ending (b/c)
1276 if ( substr( $out, -1 ) === "\n" ) {
1277 $out = substr( $out, 0, -1 );
1280 # special case: don't return empty table
1281 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1289 * Helper function for parse() that transforms wiki markup into half-parsed
1290 * HTML. Only called for $mOutputType == self::OT_HTML.
1294 * @param string $text The text to parse
1295 * @param bool $isMain Whether this is being called from the main parse() function
1296 * @param PPFrame|bool $frame A pre-processor frame
1300 public function internalParse( $text, $isMain = true, $frame = false ) {
1303 // Avoid PHP 7.1 warning from passing $this by reference
1306 # Hook to suspend the parser in this state
1307 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1311 # if $frame is provided, then use $frame for replacing any variables
1313 # use frame depth to infer how include/noinclude tags should be handled
1314 # depth=0 means this is the top-level document; otherwise it's an included document
1315 if ( !$frame->depth
) {
1318 $flag = self
::PTD_FOR_INCLUSION
;
1320 $dom = $this->preprocessToDom( $text, $flag );
1321 $text = $frame->expand( $dom );
1323 # if $frame is not provided, then use old-style replaceVariables
1324 $text = $this->replaceVariables( $text );
1327 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1328 $text = Sanitizer
::removeHTMLtags(
1330 [ $this, 'attributeStripCallback' ],
1332 array_keys( $this->mTransparentTagHooks
),
1334 [ $this, 'addTrackingCategory' ]
1336 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1338 # Tables need to come after variable replacement for things to work
1339 # properly; putting them before other transformations should keep
1340 # exciting things like link expansions from showing up in surprising
1342 $text = $this->doTableStuff( $text );
1344 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1346 $text = $this->doDoubleUnderscore( $text );
1348 $text = $this->doHeadings( $text );
1349 $text = $this->replaceInternalLinks( $text );
1350 $text = $this->doAllQuotes( $text );
1351 $text = $this->replaceExternalLinks( $text );
1353 # replaceInternalLinks may sometimes leave behind
1354 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1355 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1357 $text = $this->doMagicLinks( $text );
1358 $text = $this->formatHeadings( $text, $origText, $isMain );
1364 * Helper function for parse() that transforms half-parsed HTML into fully
1367 * @param string $text
1368 * @param bool $isMain
1369 * @param bool $linestart
1372 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1373 $text = $this->mStripState
->unstripGeneral( $text );
1375 // Avoid PHP 7.1 warning from passing $this by reference
1379 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1382 # Clean up special characters, only run once, next-to-last before doBlockLevels
1383 $text = Sanitizer
::armorFrenchSpaces( $text );
1385 $text = $this->doBlockLevels( $text, $linestart );
1387 $this->replaceLinkHolders( $text );
1390 * The input doesn't get language converted if
1392 * b) Content isn't converted
1393 * c) It's a conversion table
1394 * d) it is an interface message (which is in the user language)
1396 if ( !( $this->mOptions
->getDisableContentConversion()
1397 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1399 if ( !$this->mOptions
->getInterfaceMessage() ) {
1400 # The position of the convert() call should not be changed. it
1401 # assumes that the links are all replaced and the only thing left
1402 # is the <nowiki> mark.
1403 $text = $this->getTargetLanguage()->convert( $text );
1407 $text = $this->mStripState
->unstripNoWiki( $text );
1410 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1413 $text = $this->replaceTransparentTags( $text );
1414 $text = $this->mStripState
->unstripGeneral( $text );
1416 $text = Sanitizer
::normalizeCharReferences( $text );
1418 if ( MWTidy
::isEnabled() ) {
1419 if ( $this->mOptions
->getTidy() ) {
1420 $text = MWTidy
::tidy( $text );
1423 # attempt to sanitize at least some nesting problems
1424 # (T4702 and quite a few others)
1426 # ''Something [http://www.cool.com cool''] -->
1427 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1428 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1429 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1430 # fix up an anchor inside another anchor, only
1431 # at least for a single single nested link (T5695)
1432 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1433 '\\1\\2</a>\\3</a>\\1\\4</a>',
1434 # fix div inside inline elements- doBlockLevels won't wrap a line which
1435 # contains a div, so fix it up here; replace
1436 # div with escaped text
1437 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1438 '\\1\\3<div\\5>\\6</div>\\8\\9',
1439 # remove empty italic or bold tag pairs, some
1440 # introduced by rules above
1441 '/<([bi])><\/\\1>/' => '',
1444 $text = preg_replace(
1445 array_keys( $tidyregs ),
1446 array_values( $tidyregs ),
1451 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1458 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1459 * magic external links.
1464 * @param string $text
1468 public function doMagicLinks( $text ) {
1469 $prots = wfUrlProtocolsWithoutProtRel();
1470 $urlChar = self
::EXT_LINK_URL_CLASS
;
1471 $addr = self
::EXT_LINK_ADDR
;
1472 $space = self
::SPACE_NOT_NL
; # non-newline space
1473 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1474 $spaces = "$space++"; # possessive match of 1 or more spaces
1475 $text = preg_replace_callback(
1477 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1478 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1479 (\b # m[3]: Free external links
1481 ($addr$urlChar*) # m[4]: Post-protocol path
1483 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1485 \bISBN $spaces ( # m[6]: ISBN, capture number
1486 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1487 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1488 [0-9Xx] # check digit
1490 )!xu", [ $this, 'magicLinkCallback' ], $text );
1495 * @throws MWException
1497 * @return string HTML
1499 public function magicLinkCallback( $m ) {
1500 if ( isset( $m[1] ) && $m[1] !== '' ) {
1503 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1506 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1507 # Free external link
1508 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1509 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1511 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1512 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1517 $cssClass = 'mw-magiclink-rfc';
1518 $trackingCat = 'magiclink-tracking-rfc';
1520 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1521 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1525 $urlmsg = 'pubmedurl';
1526 $cssClass = 'mw-magiclink-pmid';
1527 $trackingCat = 'magiclink-tracking-pmid';
1530 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1531 substr( $m[0], 0, 20 ) . '"' );
1533 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1534 $this->addTrackingCategory( $trackingCat );
1535 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1536 } elseif ( isset( $m[6] ) && $m[6] !== ''
1537 && $this->mOptions
->getMagicISBNLinks()
1541 $space = self
::SPACE_NOT_NL
; # non-newline space
1542 $isbn = preg_replace( "/$space/", ' ', $isbn );
1543 $num = strtr( $isbn, [
1548 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1549 return $this->getLinkRenderer()->makeKnownLink(
1550 SpecialPage
::getTitleFor( 'Booksources', $num ),
1553 'class' => 'internal mw-magiclink-isbn',
1554 'title' => false // suppress title attribute
1563 * Make a free external link, given a user-supplied URL
1565 * @param string $url
1566 * @param int $numPostProto
1567 * The number of characters after the protocol.
1568 * @return string HTML
1571 public function makeFreeExternalLink( $url, $numPostProto ) {
1574 # The characters '<' and '>' (which were escaped by
1575 # removeHTMLtags()) should not be included in
1576 # URLs, per RFC 2396.
1577 # Make terminate a URL as well (bug T84937)
1580 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1585 $trail = substr( $url, $m2[0][1] ) . $trail;
1586 $url = substr( $url, 0, $m2[0][1] );
1589 # Move trailing punctuation to $trail
1591 # If there is no left bracket, then consider right brackets fair game too
1592 if ( strpos( $url, '(' ) === false ) {
1596 $urlRev = strrev( $url );
1597 $numSepChars = strspn( $urlRev, $sep );
1598 # Don't break a trailing HTML entity by moving the ; into $trail
1599 # This is in hot code, so use substr_compare to avoid having to
1600 # create a new string object for the comparison
1601 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1602 # more optimization: instead of running preg_match with a $
1603 # anchor, which can be slow, do the match on the reversed
1604 # string starting at the desired offset.
1605 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1606 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1610 if ( $numSepChars ) {
1611 $trail = substr( $url, -$numSepChars ) . $trail;
1612 $url = substr( $url, 0, -$numSepChars );
1615 # Verify that we still have a real URL after trail removal, and
1616 # not just lone protocol
1617 if ( strlen( $trail ) >= $numPostProto ) {
1618 return $url . $trail;
1621 $url = Sanitizer
::cleanUrl( $url );
1623 # Is this an external image?
1624 $text = $this->maybeMakeExternalImage( $url );
1625 if ( $text === false ) {
1626 # Not an image, make a link
1627 $text = Linker
::makeExternalLink( $url,
1628 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1630 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1631 # Register it in the output object...
1632 $this->mOutput
->addExternalLink( $url );
1634 return $text . $trail;
1638 * Parse headers and return html
1642 * @param string $text
1646 public function doHeadings( $text ) {
1647 for ( $i = 6; $i >= 1; --$i ) {
1648 $h = str_repeat( '=', $i );
1649 // Trim non-newline whitespace from headings
1650 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1651 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1657 * Replace single quotes with HTML markup
1660 * @param string $text
1662 * @return string The altered text
1664 public function doAllQuotes( $text ) {
1666 $lines = StringUtils
::explode( "\n", $text );
1667 foreach ( $lines as $line ) {
1668 $outtext .= $this->doQuotes( $line ) . "\n";
1670 $outtext = substr( $outtext, 0, -1 );
1675 * Helper function for doAllQuotes()
1677 * @param string $text
1681 public function doQuotes( $text ) {
1682 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1683 $countarr = count( $arr );
1684 if ( $countarr == 1 ) {
1688 // First, do some preliminary work. This may shift some apostrophes from
1689 // being mark-up to being text. It also counts the number of occurrences
1690 // of bold and italics mark-ups.
1693 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1694 $thislen = strlen( $arr[$i] );
1695 // If there are ever four apostrophes, assume the first is supposed to
1696 // be text, and the remaining three constitute mark-up for bold text.
1697 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1698 if ( $thislen == 4 ) {
1699 $arr[$i - 1] .= "'";
1702 } elseif ( $thislen > 5 ) {
1703 // If there are more than 5 apostrophes in a row, assume they're all
1704 // text except for the last 5.
1705 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1706 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1710 // Count the number of occurrences of bold and italics mark-ups.
1711 if ( $thislen == 2 ) {
1713 } elseif ( $thislen == 3 ) {
1715 } elseif ( $thislen == 5 ) {
1721 // If there is an odd number of both bold and italics, it is likely
1722 // that one of the bold ones was meant to be an apostrophe followed
1723 // by italics. Which one we cannot know for certain, but it is more
1724 // likely to be one that has a single-letter word before it.
1725 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1726 $firstsingleletterword = -1;
1727 $firstmultiletterword = -1;
1729 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1730 if ( strlen( $arr[$i] ) == 3 ) {
1731 $x1 = substr( $arr[$i - 1], -1 );
1732 $x2 = substr( $arr[$i - 1], -2, 1 );
1733 if ( $x1 === ' ' ) {
1734 if ( $firstspace == -1 ) {
1737 } elseif ( $x2 === ' ' ) {
1738 $firstsingleletterword = $i;
1739 // if $firstsingleletterword is set, we don't
1740 // look at the other options, so we can bail early.
1743 if ( $firstmultiletterword == -1 ) {
1744 $firstmultiletterword = $i;
1750 // If there is a single-letter word, use it!
1751 if ( $firstsingleletterword > -1 ) {
1752 $arr[$firstsingleletterword] = "''";
1753 $arr[$firstsingleletterword - 1] .= "'";
1754 } elseif ( $firstmultiletterword > -1 ) {
1755 // If not, but there's a multi-letter word, use that one.
1756 $arr[$firstmultiletterword] = "''";
1757 $arr[$firstmultiletterword - 1] .= "'";
1758 } elseif ( $firstspace > -1 ) {
1759 // ... otherwise use the first one that has neither.
1760 // (notice that it is possible for all three to be -1 if, for example,
1761 // there is only one pentuple-apostrophe in the line)
1762 $arr[$firstspace] = "''";
1763 $arr[$firstspace - 1] .= "'";
1767 // Now let's actually convert our apostrophic mush to HTML!
1772 foreach ( $arr as $r ) {
1773 if ( ( $i %
2 ) == 0 ) {
1774 if ( $state === 'both' ) {
1780 $thislen = strlen( $r );
1781 if ( $thislen == 2 ) {
1782 if ( $state === 'i' ) {
1785 } elseif ( $state === 'bi' ) {
1788 } elseif ( $state === 'ib' ) {
1789 $output .= '</b></i><b>';
1791 } elseif ( $state === 'both' ) {
1792 $output .= '<b><i>' . $buffer . '</i>';
1794 } else { // $state can be 'b' or ''
1798 } elseif ( $thislen == 3 ) {
1799 if ( $state === 'b' ) {
1802 } elseif ( $state === 'bi' ) {
1803 $output .= '</i></b><i>';
1805 } elseif ( $state === 'ib' ) {
1808 } elseif ( $state === 'both' ) {
1809 $output .= '<i><b>' . $buffer . '</b>';
1811 } else { // $state can be 'i' or ''
1815 } elseif ( $thislen == 5 ) {
1816 if ( $state === 'b' ) {
1817 $output .= '</b><i>';
1819 } elseif ( $state === 'i' ) {
1820 $output .= '</i><b>';
1822 } elseif ( $state === 'bi' ) {
1823 $output .= '</i></b>';
1825 } elseif ( $state === 'ib' ) {
1826 $output .= '</b></i>';
1828 } elseif ( $state === 'both' ) {
1829 $output .= '<i><b>' . $buffer . '</b></i>';
1831 } else { // ($state == '')
1839 // Now close all remaining tags. Notice that the order is important.
1840 if ( $state === 'b' ||
$state === 'ib' ) {
1843 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1846 if ( $state === 'bi' ) {
1849 // There might be lonely ''''', so make sure we have a buffer
1850 if ( $state === 'both' && $buffer ) {
1851 $output .= '<b><i>' . $buffer . '</i></b>';
1857 * Replace external links (REL)
1859 * Note: this is all very hackish and the order of execution matters a lot.
1860 * Make sure to run tests/parser/parserTests.php if you change this code.
1864 * @param string $text
1866 * @throws MWException
1869 public function replaceExternalLinks( $text ) {
1870 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1871 if ( $bits === false ) {
1872 throw new MWException( "PCRE needs to be compiled with "
1873 . "--enable-unicode-properties in order for MediaWiki to function" );
1875 $s = array_shift( $bits );
1878 while ( $i < count( $bits ) ) {
1881 $text = $bits[$i++
];
1882 $trail = $bits[$i++
];
1884 # The characters '<' and '>' (which were escaped by
1885 # removeHTMLtags()) should not be included in
1886 # URLs, per RFC 2396.
1888 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1889 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1890 $url = substr( $url, 0, $m2[0][1] );
1893 # If the link text is an image URL, replace it with an <img> tag
1894 # This happened by accident in the original parser, but some people used it extensively
1895 $img = $this->maybeMakeExternalImage( $text );
1896 if ( $img !== false ) {
1902 # Set linktype for CSS
1905 # No link text, e.g. [http://domain.tld/some.link]
1906 if ( $text == '' ) {
1908 $langObj = $this->getTargetLanguage();
1909 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1910 $linktype = 'autonumber';
1912 # Have link text, e.g. [http://domain.tld/some.link text]s
1914 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1917 // Excluding protocol-relative URLs may avoid many false positives.
1918 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1919 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1922 $url = Sanitizer
::cleanUrl( $url );
1924 # Use the encoded URL
1925 # This means that users can paste URLs directly into the text
1926 # Funny characters like ö aren't valid in URLs anyway
1927 # This was changed in August 2004
1928 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1929 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1931 # Register link in the output object.
1932 $this->mOutput
->addExternalLink( $url );
1939 * Get the rel attribute for a particular external link.
1942 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1943 * nofollow if appropriate
1944 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1945 * @return string|null Rel attribute for $url
1947 public static function getExternalLinkRel( $url = false, $title = null ) {
1948 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1949 $ns = $title ?
$title->getNamespace() : false;
1950 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1951 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1959 * Get an associative array of additional HTML attributes appropriate for a
1960 * particular external link. This currently may include rel => nofollow
1961 * (depending on configuration, namespace, and the URL's domain) and/or a
1962 * target attribute (depending on configuration).
1964 * @param string $url URL to extract the domain from for rel =>
1965 * nofollow if appropriate
1966 * @return array Associative array of HTML attributes
1968 public function getExternalLinkAttribs( $url ) {
1970 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1972 $target = $this->mOptions
->getExternalLinkTarget();
1974 $attribs['target'] = $target;
1975 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1976 // T133507. New windows can navigate parent cross-origin.
1977 // Including noreferrer due to lacking browser
1978 // support of noopener. Eventually noreferrer should be removed.
1979 if ( $rel !== '' ) {
1982 $rel .= 'noreferrer noopener';
1985 $attribs['rel'] = $rel;
1990 * Replace unusual escape codes in a URL with their equivalent characters
1992 * This generally follows the syntax defined in RFC 3986, with special
1993 * consideration for HTTP query strings.
1995 * @param string $url
1998 public static function normalizeLinkUrl( $url ) {
1999 # First, make sure unsafe characters are encoded
2000 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2002 return rawurlencode( $m[0] );
2008 $end = strlen( $url );
2010 # Fragment part - 'fragment'
2011 $start = strpos( $url, '#' );
2012 if ( $start !== false && $start < $end ) {
2013 $ret = self
::normalizeUrlComponent(
2014 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2018 # Query part - 'query' minus &=+;
2019 $start = strpos( $url, '?' );
2020 if ( $start !== false && $start < $end ) {
2021 $ret = self
::normalizeUrlComponent(
2022 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2026 # Scheme and path part - 'pchar'
2027 # (we assume no userinfo or encoded colons in the host)
2028 $ret = self
::normalizeUrlComponent(
2029 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2034 private static function normalizeUrlComponent( $component, $unsafe ) {
2035 $callback = function ( $matches ) use ( $unsafe ) {
2036 $char = urldecode( $matches[0] );
2037 $ord = ord( $char );
2038 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2042 # Leave it escaped, but use uppercase for a-f
2043 return strtoupper( $matches[0] );
2046 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2050 * make an image if it's allowed, either through the global
2051 * option, through the exception, or through the on-wiki whitelist
2053 * @param string $url
2057 private function maybeMakeExternalImage( $url ) {
2058 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2059 $imagesexception = !empty( $imagesfrom );
2061 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2062 if ( $imagesexception && is_array( $imagesfrom ) ) {
2063 $imagematch = false;
2064 foreach ( $imagesfrom as $match ) {
2065 if ( strpos( $url, $match ) === 0 ) {
2070 } elseif ( $imagesexception ) {
2071 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2073 $imagematch = false;
2076 if ( $this->mOptions
->getAllowExternalImages()
2077 ||
( $imagesexception && $imagematch )
2079 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2081 $text = Linker
::makeExternalImage( $url );
2084 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2085 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2087 $whitelist = explode(
2089 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2092 foreach ( $whitelist as $entry ) {
2093 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2094 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2097 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2098 # Image matches a whitelist entry
2099 $text = Linker
::makeExternalImage( $url );
2108 * Process [[ ]] wikilinks
2112 * @return string Processed text
2116 public function replaceInternalLinks( $s ) {
2117 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2122 * Process [[ ]] wikilinks (RIL)
2124 * @throws MWException
2125 * @return LinkHolderArray
2129 public function replaceInternalLinks2( &$s ) {
2130 global $wgExtraInterlanguageLinkPrefixes;
2132 static $tc = false, $e1, $e1_img;
2133 # the % is needed to support urlencoded titles as well
2135 $tc = Title
::legalChars() . '#%';
2136 # Match a link having the form [[namespace:link|alternate]]trail
2137 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2138 # Match cases where there is no "]]", which might still be images
2139 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2142 $holders = new LinkHolderArray( $this );
2144 # split the entire text string on occurrences of [[
2145 $a = StringUtils
::explode( '[[', ' ' . $s );
2146 # get the first element (all text up to first [[), and remove the space we added
2149 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2150 $s = substr( $s, 1 );
2152 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2154 if ( $useLinkPrefixExtension ) {
2155 # Match the end of a line for a word that's not followed by whitespace,
2156 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2157 $charset = $this->getContentLanguage()->linkPrefixCharset();
2158 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2161 if ( is_null( $this->mTitle
) ) {
2162 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2164 $nottalk = !$this->mTitle
->isTalkPage();
2166 if ( $useLinkPrefixExtension ) {
2168 if ( preg_match( $e2, $s, $m ) ) {
2169 $first_prefix = $m[2];
2171 $first_prefix = false;
2177 $useSubpages = $this->areSubpagesAllowed();
2179 # Loop for each link
2180 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2181 # Check for excessive memory usage
2182 if ( $holders->isBig() ) {
2184 # Do the existence check, replace the link holders and clear the array
2185 $holders->replace( $s );
2189 if ( $useLinkPrefixExtension ) {
2190 if ( preg_match( $e2, $s, $m ) ) {
2197 if ( $first_prefix ) {
2198 $prefix = $first_prefix;
2199 $first_prefix = false;
2203 $might_be_img = false;
2205 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2207 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2208 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2209 # the real problem is with the $e1 regex
2211 # Still some problems for cases where the ] is meant to be outside punctuation,
2212 # and no image is in sight. See T4095.
2214 && substr( $m[3], 0, 1 ) === ']'
2215 && strpos( $text, '[' ) !== false
2217 $text .= ']'; # so that replaceExternalLinks($text) works later
2218 $m[3] = substr( $m[3], 1 );
2220 # fix up urlencoded title texts
2221 if ( strpos( $m[1], '%' ) !== false ) {
2222 # Should anchors '#' also be rejected?
2223 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2226 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2227 # Invalid, but might be an image with a link in its caption
2228 $might_be_img = true;
2230 if ( strpos( $m[1], '%' ) !== false ) {
2231 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2234 } else { # Invalid form; output directly
2235 $s .= $prefix . '[[' . $line;
2239 $origLink = ltrim( $m[1], ' ' );
2241 # Don't allow internal links to pages containing
2242 # PROTO: where PROTO is a valid URL protocol; these
2243 # should be external links.
2244 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2245 $s .= $prefix . '[[' . $line;
2249 # Make subpage if necessary
2250 if ( $useSubpages ) {
2251 $link = $this->maybeDoSubpageLink( $origLink, $text );
2256 // \x7f isn't a default legal title char, so most likely strip
2257 // markers will force us into the "invalid form" path above. But,
2258 // just in case, let's assert that xmlish tags aren't valid in
2259 // the title position.
2260 $unstrip = $this->mStripState
->killMarkers( $link );
2261 $noMarkers = ( $unstrip === $link );
2263 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2264 if ( $nt === null ) {
2265 $s .= $prefix . '[[' . $line;
2269 $ns = $nt->getNamespace();
2270 $iw = $nt->getInterwiki();
2272 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2274 if ( $might_be_img ) { # if this is actually an invalid link
2275 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2278 # look at the next 'line' to see if we can close it there
2280 $next_line = $a->current();
2281 if ( $next_line === false ||
$next_line === null ) {
2284 $m = explode( ']]', $next_line, 3 );
2285 if ( count( $m ) == 3 ) {
2286 # the first ]] closes the inner link, the second the image
2288 $text .= "[[{$m[0]}]]{$m[1]}";
2291 } elseif ( count( $m ) == 2 ) {
2292 # if there's exactly one ]] that's fine, we'll keep looking
2293 $text .= "[[{$m[0]}]]{$m[1]}";
2295 # if $next_line is invalid too, we need look no further
2296 $text .= '[[' . $next_line;
2301 # we couldn't find the end of this imageLink, so output it raw
2302 # but don't ignore what might be perfectly normal links in the text we've examined
2303 $holders->merge( $this->replaceInternalLinks2( $text ) );
2304 $s .= "{$prefix}[[$link|$text";
2305 # note: no $trail, because without an end, there *is* no trail
2308 } else { # it's not an image, so output it raw
2309 $s .= "{$prefix}[[$link|$text";
2310 # note: no $trail, because without an end, there *is* no trail
2315 $wasblank = ( $text == '' );
2319 # Strip off leading ':'
2320 $text = substr( $text, 1 );
2323 # T6598 madness. Handle the quotes only if they come from the alternate part
2324 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2325 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2326 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2327 $text = $this->doQuotes( $text );
2330 # Link not escaped by : , create the various objects
2331 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2334 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2335 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2336 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2339 # T26502: filter duplicates
2340 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2341 $this->mLangLinkLanguages
[$iw] = true;
2342 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2346 * Strip the whitespace interwiki links produce, see T10897
2348 $s = rtrim( $s . $prefix ) . $trail; # T175416
2352 if ( $ns == NS_FILE
) {
2353 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2355 # if no parameters were passed, $text
2356 # becomes something like "File:Foo.png",
2357 # which we don't want to pass on to the
2361 # recursively parse links inside the image caption
2362 # actually, this will parse them in any other parameters, too,
2363 # but it might be hard to fix that, and it doesn't matter ATM
2364 $text = $this->replaceExternalLinks( $text );
2365 $holders->merge( $this->replaceInternalLinks2( $text ) );
2367 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2368 $s .= $prefix . $this->armorLinks(
2369 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2372 } elseif ( $ns == NS_CATEGORY
) {
2374 * Strip the whitespace Category links produce, see T2087
2376 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2379 $sortkey = $this->getDefaultSort();
2383 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2384 $sortkey = str_replace( "\n", '', $sortkey );
2385 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2386 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2392 # Self-link checking. For some languages, variants of the title are checked in
2393 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2394 # for linking to a different variant.
2395 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2396 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2400 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2401 # @todo FIXME: Should do batch file existence checks, see comment below
2402 if ( $ns == NS_MEDIA
) {
2403 # Give extensions a chance to select the file revision for us
2406 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2407 [ $this, $nt, &$options, &$descQuery ] );
2408 # Fetch and register the file (file title may be different via hooks)
2409 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2410 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2411 $s .= $prefix . $this->armorLinks(
2412 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2416 # Some titles, such as valid special pages or files in foreign repos, should
2417 # be shown as bluelinks even though they're not included in the page table
2418 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2419 # batch file existence checks for NS_FILE and NS_MEDIA
2420 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2421 $this->mOutput
->addLink( $nt );
2422 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2424 # Links will be added to the output link list after checking
2425 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2432 * Render a forced-blue link inline; protect against double expansion of
2433 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2434 * Since this little disaster has to split off the trail text to avoid
2435 * breaking URLs in the following text without breaking trails on the
2436 * wiki links, it's been made into a horrible function.
2439 * @param string $text
2440 * @param string $trail
2441 * @param string $prefix
2442 * @return string HTML-wikitext mix oh yuck
2444 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2445 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2447 if ( $text == '' ) {
2448 $text = htmlspecialchars( $nt->getPrefixedText() );
2451 $link = $this->getLinkRenderer()->makeKnownLink(
2452 $nt, new HtmlArmor( "$prefix$text$inside" )
2455 return $this->armorLinks( $link ) . $trail;
2459 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2460 * going to go through further parsing steps before inline URL expansion.
2462 * Not needed quite as much as it used to be since free links are a bit
2463 * more sensible these days. But bracketed links are still an issue.
2465 * @param string $text More-or-less HTML
2466 * @return string Less-or-more HTML with NOPARSE bits
2468 public function armorLinks( $text ) {
2469 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2470 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2474 * Return true if subpage links should be expanded on this page.
2477 public function areSubpagesAllowed() {
2478 # Some namespaces don't allow subpages
2479 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2483 * Handle link to subpage if necessary
2485 * @param string $target The source of the link
2486 * @param string &$text The link text, modified as necessary
2487 * @return string The full name of the link
2490 public function maybeDoSubpageLink( $target, &$text ) {
2491 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2495 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2497 * @param string $text
2498 * @param bool $linestart Whether or not this is at the start of a line.
2500 * @return string The lists rendered as HTML
2502 public function doBlockLevels( $text, $linestart ) {
2503 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2507 * Return value of a magic variable (like PAGENAME)
2511 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2512 * @param bool|PPFrame $frame
2514 * @throws MWException
2517 public function getVariableValue( $index, $frame = false ) {
2518 global $wgSitename, $wgServer, $wgServerName;
2519 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2521 if ( is_null( $this->mTitle
) ) {
2522 // If no title set, bad things are going to happen
2523 // later. Title should always be set since this
2524 // should only be called in the middle of a parse
2525 // operation (but the unit-tests do funky stuff)
2526 throw new MWException( __METHOD__
. ' Should only be '
2527 . ' called while parsing (no title set)' );
2530 // Avoid PHP 7.1 warning from passing $this by reference
2534 * Some of these require message or data lookups and can be
2535 * expensive to check many times.
2537 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2538 if ( isset( $this->mVarCache
[$index] ) ) {
2539 return $this->mVarCache
[$index];
2543 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2544 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2546 $pageLang = $this->getFunctionLang();
2552 case 'currentmonth':
2553 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2555 case 'currentmonth1':
2556 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2558 case 'currentmonthname':
2559 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2561 case 'currentmonthnamegen':
2562 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2564 case 'currentmonthabbrev':
2565 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2568 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2571 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2574 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2577 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2579 case 'localmonthname':
2580 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2582 case 'localmonthnamegen':
2583 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2585 case 'localmonthabbrev':
2586 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2589 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2592 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2595 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2598 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2600 case 'fullpagename':
2601 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2603 case 'fullpagenamee':
2604 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2607 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2609 case 'subpagenamee':
2610 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2612 case 'rootpagename':
2613 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2615 case 'rootpagenamee':
2616 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2619 $this->mTitle
->getRootText()
2622 case 'basepagename':
2623 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2625 case 'basepagenamee':
2626 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2629 $this->mTitle
->getBaseText()
2632 case 'talkpagename':
2633 if ( $this->mTitle
->canHaveTalkPage() ) {
2634 $talkPage = $this->mTitle
->getTalkPage();
2635 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2640 case 'talkpagenamee':
2641 if ( $this->mTitle
->canHaveTalkPage() ) {
2642 $talkPage = $this->mTitle
->getTalkPage();
2643 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2648 case 'subjectpagename':
2649 $subjPage = $this->mTitle
->getSubjectPage();
2650 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2652 case 'subjectpagenamee':
2653 $subjPage = $this->mTitle
->getSubjectPage();
2654 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2656 case 'pageid': // requested in T25427
2657 $pageid = $this->getTitle()->getArticleID();
2658 if ( $pageid == 0 ) {
2659 # 0 means the page doesn't exist in the database,
2660 # which means the user is previewing a new page.
2661 # The vary-revision flag must be set, because the magic word
2662 # will have a different value once the page is saved.
2663 $this->mOutput
->setFlag( 'vary-revision' );
2664 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2666 $value = $pageid ?
: null;
2669 # Let the edit saving system know we should parse the page
2670 # *after* a revision ID has been assigned.
2671 $this->mOutput
->setFlag( 'vary-revision-id' );
2672 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2673 $value = $this->mRevisionId
;
2674 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2675 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2676 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2680 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2682 case 'revisionday2':
2683 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2685 case 'revisionmonth':
2686 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2688 case 'revisionmonth1':
2689 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2691 case 'revisionyear':
2692 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2694 case 'revisiontimestamp':
2695 # Let the edit saving system know we should parse the page
2696 # *after* a revision ID has been assigned. This is for null edits.
2697 $this->mOutput
->setFlag( 'vary-revision' );
2698 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2699 $value = $this->getRevisionTimestamp();
2701 case 'revisionuser':
2702 # Let the edit saving system know we should parse the page
2703 # *after* a revision ID has been assigned for null edits.
2704 $this->mOutput
->setFlag( 'vary-user' );
2705 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2706 $value = $this->getRevisionUser();
2708 case 'revisionsize':
2709 $value = $this->getRevisionSize();
2712 $value = str_replace( '_', ' ',
2713 $this->getContentLanguage()->getNsText( $this->mTitle
->getNamespace() ) );
2716 $value = wfUrlencode( $this->getContentLanguage()->
2717 getNsText( $this->mTitle
->getNamespace() ) );
2719 case 'namespacenumber':
2720 $value = $this->mTitle
->getNamespace();
2723 $value = $this->mTitle
->canHaveTalkPage()
2724 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2728 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2730 case 'subjectspace':
2731 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2733 case 'subjectspacee':
2734 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2736 case 'currentdayname':
2737 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2740 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2743 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2746 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2749 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2750 # int to remove the padding
2751 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2754 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2756 case 'localdayname':
2757 $value = $pageLang->getWeekdayName(
2758 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2762 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2765 $value = $pageLang->time(
2766 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2772 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2775 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2776 # int to remove the padding
2777 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2780 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2782 case 'numberofarticles':
2783 $value = $pageLang->formatNum( SiteStats
::articles() );
2785 case 'numberoffiles':
2786 $value = $pageLang->formatNum( SiteStats
::images() );
2788 case 'numberofusers':
2789 $value = $pageLang->formatNum( SiteStats
::users() );
2791 case 'numberofactiveusers':
2792 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2794 case 'numberofpages':
2795 $value = $pageLang->formatNum( SiteStats
::pages() );
2797 case 'numberofadmins':
2798 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2800 case 'numberofedits':
2801 $value = $pageLang->formatNum( SiteStats
::edits() );
2803 case 'currenttimestamp':
2804 $value = wfTimestamp( TS_MW
, $ts );
2806 case 'localtimestamp':
2807 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2809 case 'currentversion':
2810 $value = SpecialVersion
::getVersion();
2813 return $wgArticlePath;
2819 return $wgServerName;
2821 return $wgScriptPath;
2823 return $wgStylePath;
2824 case 'directionmark':
2825 return $pageLang->getDirMark();
2826 case 'contentlanguage':
2827 global $wgLanguageCode;
2828 return $wgLanguageCode;
2829 case 'pagelanguage':
2830 $value = $pageLang->getCode();
2832 case 'cascadingsources':
2833 $value = CoreParserFunctions
::cascadingsources( $this );
2838 'ParserGetVariableValueSwitch',
2839 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2846 $this->mVarCache
[$index] = $value;
2855 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2856 * @param string $variable Parser variable name
2859 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2860 # Get the timezone-adjusted timestamp to be used for this revision
2861 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2862 # Possibly set vary-revision if there is not yet an associated revision
2863 if ( !$this->getRevisionObject() ) {
2864 # Get the timezone-adjusted timestamp $mtts seconds in the future
2866 $this->getContentLanguage()->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2871 if ( $resNow !== $resThen ) {
2872 # Let the edit saving system know we should parse the page
2873 # *after* a revision ID has been assigned. This is for null edits.
2874 $this->mOutput
->setFlag( 'vary-revision' );
2875 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2883 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2887 public function initialiseVariables() {
2888 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2889 $substIDs = $this->magicWordFactory
->getSubstIDs();
2891 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2892 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2896 * Preprocess some wikitext and return the document tree.
2897 * This is the ghost of replace_variables().
2899 * @param string $text The text to parse
2900 * @param int $flags Bitwise combination of:
2901 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2902 * included. Default is to assume a direct page view.
2904 * The generated DOM tree must depend only on the input text and the flags.
2905 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2907 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2908 * change in the DOM tree for a given text, must be passed through the section identifier
2909 * in the section edit link and thus back to extractSections().
2911 * The output of this function is currently only cached in process memory, but a persistent
2912 * cache may be implemented at a later date which takes further advantage of these strict
2913 * dependency requirements.
2917 public function preprocessToDom( $text, $flags = 0 ) {
2918 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2923 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2929 public static function splitWhitespace( $s ) {
2930 $ltrimmed = ltrim( $s );
2931 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2932 $trimmed = rtrim( $ltrimmed );
2933 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2935 $w2 = substr( $ltrimmed, -$diff );
2939 return [ $w1, $trimmed, $w2 ];
2943 * Replace magic variables, templates, and template arguments
2944 * with the appropriate text. Templates are substituted recursively,
2945 * taking care to avoid infinite loops.
2947 * Note that the substitution depends on value of $mOutputType:
2948 * self::OT_WIKI: only {{subst:}} templates
2949 * self::OT_PREPROCESS: templates but not extension tags
2950 * self::OT_HTML: all templates and extension tags
2952 * @param string $text The text to transform
2953 * @param bool|PPFrame $frame Object describing the arguments passed to the
2954 * template. Arguments may also be provided as an associative array, as
2955 * was the usual case before MW1.12. Providing arguments this way may be
2956 * useful for extensions wishing to perform variable replacement
2958 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2959 * double-brace expansion.
2962 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2963 # Is there any text? Also, Prevent too big inclusions!
2964 $textSize = strlen( $text );
2965 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2969 if ( $frame === false ) {
2970 $frame = $this->getPreprocessor()->newFrame();
2971 } elseif ( !( $frame instanceof PPFrame
) ) {
2972 wfDebug( __METHOD__
. " called using plain parameters instead of "
2973 . "a PPFrame instance. Creating custom frame.\n" );
2974 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2977 $dom = $this->preprocessToDom( $text );
2978 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2979 $text = $frame->expand( $dom, $flags );
2985 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2987 * @param array $args
2991 public static function createAssocArgs( $args ) {
2994 foreach ( $args as $arg ) {
2995 $eqpos = strpos( $arg, '=' );
2996 if ( $eqpos === false ) {
2997 $assocArgs[$index++
] = $arg;
2999 $name = trim( substr( $arg, 0, $eqpos ) );
3000 $value = trim( substr( $arg, $eqpos +
1 ) );
3001 if ( $value === false ) {
3004 if ( $name !== false ) {
3005 $assocArgs[$name] = $value;
3014 * Warn the user when a parser limitation is reached
3015 * Will warn at most once the user per limitation type
3017 * The results are shown during preview and run through the Parser (See EditPage.php)
3019 * @param string $limitationType Should be one of:
3020 * 'expensive-parserfunction' (corresponding messages:
3021 * 'expensive-parserfunction-warning',
3022 * 'expensive-parserfunction-category')
3023 * 'post-expand-template-argument' (corresponding messages:
3024 * 'post-expand-template-argument-warning',
3025 * 'post-expand-template-argument-category')
3026 * 'post-expand-template-inclusion' (corresponding messages:
3027 * 'post-expand-template-inclusion-warning',
3028 * 'post-expand-template-inclusion-category')
3029 * 'node-count-exceeded' (corresponding messages:
3030 * 'node-count-exceeded-warning',
3031 * 'node-count-exceeded-category')
3032 * 'expansion-depth-exceeded' (corresponding messages:
3033 * 'expansion-depth-exceeded-warning',
3034 * 'expansion-depth-exceeded-category')
3035 * @param string|int|null $current Current value
3036 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3037 * exceeded, provide the values (optional)
3039 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3040 # does no harm if $current and $max are present but are unnecessary for the message
3041 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3042 # only during preview, and that would split the parser cache unnecessarily.
3043 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3045 $this->mOutput
->addWarning( $warning );
3046 $this->addTrackingCategory( "$limitationType-category" );
3050 * Return the text of a template, after recursively
3051 * replacing any variables or templates within the template.
3053 * @param array $piece The parts of the template
3054 * $piece['title']: the title, i.e. the part before the |
3055 * $piece['parts']: the parameter array
3056 * $piece['lineStart']: whether the brace was at the start of a line
3057 * @param PPFrame $frame The current frame, contains template arguments
3059 * @return string The text of the template
3061 public function braceSubstitution( $piece, $frame ) {
3064 // $text has been filled
3066 // wiki markup in $text should be escaped
3068 // $text is HTML, armour it against wikitext transformation
3070 // Force interwiki transclusion to be done in raw mode not rendered
3071 $forceRawInterwiki = false;
3072 // $text is a DOM node needing expansion in a child frame
3073 $isChildObj = false;
3074 // $text is a DOM node needing expansion in the current frame
3075 $isLocalObj = false;
3077 # Title object, where $text came from
3080 # $part1 is the bit before the first |, and must contain only title characters.
3081 # Various prefixes will be stripped from it later.
3082 $titleWithSpaces = $frame->expand( $piece['title'] );
3083 $part1 = trim( $titleWithSpaces );
3086 # Original title text preserved for various purposes
3087 $originalTitle = $part1;
3089 # $args is a list of argument nodes, starting from index 0, not including $part1
3090 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3091 # below won't work b/c this $args isn't an object
3092 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3094 $profileSection = null; // profile templates
3098 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3100 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3101 # Decide whether to expand template or keep wikitext as-is.
3102 if ( $this->ot
['wiki'] ) {
3103 if ( $substMatch === false ) {
3104 $literal = true; # literal when in PST with no prefix
3106 $literal = false; # expand when in PST with subst: or safesubst:
3109 if ( $substMatch == 'subst' ) {
3110 $literal = true; # literal when not in PST with plain subst:
3112 $literal = false; # expand when not in PST with safesubst: or no prefix
3116 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3123 if ( !$found && $args->getLength() == 0 ) {
3124 $id = $this->mVariables
->matchStartToEnd( $part1 );
3125 if ( $id !== false ) {
3126 $text = $this->getVariableValue( $id, $frame );
3127 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3128 $this->mOutput
->updateCacheExpiry(
3129 $this->magicWordFactory
->getCacheTTL( $id ) );
3135 # MSG, MSGNW and RAW
3138 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3139 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3142 # Remove obsolete MSG:
3143 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3144 $mwMsg->matchStartAndRemove( $part1 );
3148 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3149 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3150 $forceRawInterwiki = true;
3156 $colonPos = strpos( $part1, ':' );
3157 if ( $colonPos !== false ) {
3158 $func = substr( $part1, 0, $colonPos );
3159 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3160 $argsLength = $args->getLength();
3161 for ( $i = 0; $i < $argsLength; $i++
) {
3162 $funcArgs[] = $args->item( $i );
3165 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3167 // Extract any forwarded flags
3168 if ( isset( $result['title'] ) ) {
3169 $title = $result['title'];
3171 if ( isset( $result['found'] ) ) {
3172 $found = $result['found'];
3174 if ( array_key_exists( 'text', $result ) ) {
3176 $text = $result['text'];
3178 if ( isset( $result['nowiki'] ) ) {
3179 $nowiki = $result['nowiki'];
3181 if ( isset( $result['isHTML'] ) ) {
3182 $isHTML = $result['isHTML'];
3184 if ( isset( $result['forceRawInterwiki'] ) ) {
3185 $forceRawInterwiki = $result['forceRawInterwiki'];
3187 if ( isset( $result['isChildObj'] ) ) {
3188 $isChildObj = $result['isChildObj'];
3190 if ( isset( $result['isLocalObj'] ) ) {
3191 $isLocalObj = $result['isLocalObj'];
3196 # Finish mangling title and then check for loops.
3197 # Set $title to a Title object and $titleText to the PDBK
3200 # Split the title into page and subpage
3202 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3203 if ( $part1 !== $relative ) {
3205 $ns = $this->mTitle
->getNamespace();
3207 $title = Title
::newFromText( $part1, $ns );
3209 $titleText = $title->getPrefixedText();
3210 # Check for language variants if the template is not found
3211 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3212 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3214 # Do recursion depth check
3215 $limit = $this->mOptions
->getMaxTemplateDepth();
3216 if ( $frame->depth
>= $limit ) {
3218 $text = '<span class="error">'
3219 . wfMessage( 'parser-template-recursion-depth-warning' )
3220 ->numParams( $limit )->inContentLanguage()->text()
3226 # Load from database
3227 if ( !$found && $title ) {
3228 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3229 if ( !$title->isExternal() ) {
3230 if ( $title->isSpecialPage()
3231 && $this->mOptions
->getAllowSpecialInclusion()
3232 && $this->ot
['html']
3234 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3235 // Pass the template arguments as URL parameters.
3236 // "uselang" will have no effect since the Language object
3237 // is forced to the one defined in ParserOptions.
3239 $argsLength = $args->getLength();
3240 for ( $i = 0; $i < $argsLength; $i++
) {
3241 $bits = $args->item( $i )->splitArg();
3242 if ( strval( $bits['index'] ) === '' ) {
3243 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3244 $value = trim( $frame->expand( $bits['value'] ) );
3245 $pageArgs[$name] = $value;
3249 // Create a new context to execute the special page
3250 $context = new RequestContext
;
3251 $context->setTitle( $title );
3252 $context->setRequest( new FauxRequest( $pageArgs ) );
3253 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3254 $context->setUser( $this->getUser() );
3256 // If this page is cached, then we better not be per user.
3257 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3259 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3260 $ret = SpecialPageFactory
::capturePath(
3261 $title, $context, $this->getLinkRenderer() );
3263 $text = $context->getOutput()->getHTML();
3264 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3267 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3268 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3269 $specialPage->maxIncludeCacheTime()
3273 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3274 $found = false; # access denied
3275 wfDebug( __METHOD__
. ": template inclusion denied for " .
3276 $title->getPrefixedDBkey() . "\n" );
3278 list( $text, $title ) = $this->getTemplateDom( $title );
3279 if ( $text !== false ) {
3285 # If the title is valid but undisplayable, make a link to it
3286 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3287 $text = "[[:$titleText]]";
3290 } elseif ( $title->isTrans() ) {
3291 # Interwiki transclusion
3292 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3293 $text = $this->interwikiTransclude( $title, 'render' );
3296 $text = $this->interwikiTransclude( $title, 'raw' );
3297 # Preprocess it like a template
3298 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3304 # Do infinite loop check
3305 # This has to be done after redirect resolution to avoid infinite loops via redirects
3306 if ( !$frame->loopCheck( $title ) ) {
3308 $text = '<span class="error">'
3309 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3311 $this->addTrackingCategory( 'template-loop-category' );
3312 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3313 wfEscapeWikiText( $titleText ) )->text() );
3314 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3318 # If we haven't found text to substitute by now, we're done
3319 # Recover the source wikitext and return it
3321 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3322 if ( $profileSection ) {
3323 $this->mProfiler
->scopedProfileOut( $profileSection );
3325 return [ 'object' => $text ];
3328 # Expand DOM-style return values in a child frame
3329 if ( $isChildObj ) {
3330 # Clean up argument array
3331 $newFrame = $frame->newChild( $args, $title );
3334 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3335 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3336 # Expansion is eligible for the empty-frame cache
3337 $text = $newFrame->cachedExpand( $titleText, $text );
3339 # Uncached expansion
3340 $text = $newFrame->expand( $text );
3343 if ( $isLocalObj && $nowiki ) {
3344 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3345 $isLocalObj = false;
3348 if ( $profileSection ) {
3349 $this->mProfiler
->scopedProfileOut( $profileSection );
3352 # Replace raw HTML by a placeholder
3354 $text = $this->insertStripItem( $text );
3355 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3356 # Escape nowiki-style return values
3357 $text = wfEscapeWikiText( $text );
3358 } elseif ( is_string( $text )
3359 && !$piece['lineStart']
3360 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3362 # T2529: if the template begins with a table or block-level
3363 # element, it should be treated as beginning a new line.
3364 # This behavior is somewhat controversial.
3365 $text = "\n" . $text;
3368 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3369 # Error, oversize inclusion
3370 if ( $titleText !== false ) {
3371 # Make a working, properly escaped link if possible (T25588)
3372 $text = "[[:$titleText]]";
3374 # This will probably not be a working link, but at least it may
3375 # provide some hint of where the problem is
3376 preg_replace( '/^:/', '', $originalTitle );
3377 $text = "[[:$originalTitle]]";
3379 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3380 . 'post-expand include size too large -->' );
3381 $this->limitationWarn( 'post-expand-template-inclusion' );
3384 if ( $isLocalObj ) {
3385 $ret = [ 'object' => $text ];
3387 $ret = [ 'text' => $text ];
3394 * Call a parser function and return an array with text and flags.
3396 * The returned array will always contain a boolean 'found', indicating
3397 * whether the parser function was found or not. It may also contain the
3399 * text: string|object, resulting wikitext or PP DOM object
3400 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3401 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3402 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3403 * nowiki: bool, wiki markup in $text should be escaped
3406 * @param PPFrame $frame The current frame, contains template arguments
3407 * @param string $function Function name
3408 * @param array $args Arguments to the function
3409 * @throws MWException
3412 public function callParserFunction( $frame, $function, array $args = [] ) {
3413 # Case sensitive functions
3414 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3415 $function = $this->mFunctionSynonyms
[1][$function];
3417 # Case insensitive functions
3418 $function = $this->getContentLanguage()->lc( $function );
3419 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3420 $function = $this->mFunctionSynonyms
[0][$function];
3422 return [ 'found' => false ];
3426 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3428 // Avoid PHP 7.1 warning from passing $this by reference
3431 $allArgs = [ &$parser ];
3432 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3433 # Convert arguments to PPNodes and collect for appending to $allArgs
3435 foreach ( $args as $k => $v ) {
3436 if ( $v instanceof PPNode ||
$k === 0 ) {
3439 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3443 # Add a frame parameter, and pass the arguments as an array
3444 $allArgs[] = $frame;
3445 $allArgs[] = $funcArgs;
3447 # Convert arguments to plain text and append to $allArgs
3448 foreach ( $args as $k => $v ) {
3449 if ( $v instanceof PPNode
) {
3450 $allArgs[] = trim( $frame->expand( $v ) );
3451 } elseif ( is_int( $k ) && $k >= 0 ) {
3452 $allArgs[] = trim( $v );
3454 $allArgs[] = trim( "$k=$v" );
3459 $result = $callback( ...$allArgs );
3461 # The interface for function hooks allows them to return a wikitext
3462 # string or an array containing the string and any flags. This mungs
3463 # things around to match what this method should return.
3464 if ( !is_array( $result ) ) {
3470 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3471 $result['text'] = $result[0];
3473 unset( $result[0] );
3480 $preprocessFlags = 0;
3481 if ( isset( $result['noparse'] ) ) {
3482 $noparse = $result['noparse'];
3484 if ( isset( $result['preprocessFlags'] ) ) {
3485 $preprocessFlags = $result['preprocessFlags'];
3489 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3490 $result['isChildObj'] = true;
3497 * Get the semi-parsed DOM representation of a template with a given title,
3498 * and its redirect destination title. Cached.
3500 * @param Title $title
3504 public function getTemplateDom( $title ) {
3505 $cacheTitle = $title;
3506 $titleText = $title->getPrefixedDBkey();
3508 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3509 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3510 $title = Title
::makeTitle( $ns, $dbk );
3511 $titleText = $title->getPrefixedDBkey();
3513 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3514 return [ $this->mTplDomCache
[$titleText], $title ];
3517 # Cache miss, go to the database
3518 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3520 if ( $text === false ) {
3521 $this->mTplDomCache
[$titleText] = false;
3522 return [ false, $title ];
3525 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3526 $this->mTplDomCache
[$titleText] = $dom;
3528 if ( !$title->equals( $cacheTitle ) ) {
3529 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3530 [ $title->getNamespace(), $title->getDBkey() ];
3533 return [ $dom, $title ];
3537 * Fetch the current revision of a given title. Note that the revision
3538 * (and even the title) may not exist in the database, so everything
3539 * contributing to the output of the parser should use this method
3540 * where possible, rather than getting the revisions themselves. This
3541 * method also caches its results, so using it benefits performance.
3544 * @param Title $title
3547 public function fetchCurrentRevisionOfTitle( $title ) {
3548 $cacheKey = $title->getPrefixedDBkey();
3549 if ( !$this->currentRevisionCache
) {
3550 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3552 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3553 $this->currentRevisionCache
->set( $cacheKey,
3554 // Defaults to Parser::statelessFetchRevision()
3555 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3558 return $this->currentRevisionCache
->get( $cacheKey );
3562 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3563 * without passing them on to it.
3566 * @param Title $title
3567 * @param Parser|bool $parser
3568 * @return Revision|bool False if missing
3570 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3571 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3577 * Fetch the unparsed text of a template and register a reference to it.
3578 * @param Title $title
3579 * @return array ( string or false, Title )
3581 public function fetchTemplateAndTitle( $title ) {
3582 // Defaults to Parser::statelessFetchTemplate()
3583 $templateCb = $this->mOptions
->getTemplateCallback();
3584 $stuff = call_user_func( $templateCb, $title, $this );
3585 // We use U+007F DELETE to distinguish strip markers from regular text.
3586 $text = $stuff['text'];
3587 if ( is_string( $stuff['text'] ) ) {
3588 $text = strtr( $text, "\x7f", "?" );
3590 $finalTitle = $stuff['finalTitle'] ??
$title;
3591 if ( isset( $stuff['deps'] ) ) {
3592 foreach ( $stuff['deps'] as $dep ) {
3593 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3594 if ( $dep['title']->equals( $this->getTitle() ) ) {
3595 // If we transclude ourselves, the final result
3596 // will change based on the new version of the page
3597 $this->mOutput
->setFlag( 'vary-revision' );
3601 return [ $text, $finalTitle ];
3605 * Fetch the unparsed text of a template and register a reference to it.
3606 * @param Title $title
3607 * @return string|bool
3609 public function fetchTemplate( $title ) {
3610 return $this->fetchTemplateAndTitle( $title )[0];
3614 * Static function to get a template
3615 * Can be overridden via ParserOptions::setTemplateCallback().
3617 * @param Title $title
3618 * @param bool|Parser $parser
3622 public static function statelessFetchTemplate( $title, $parser = false ) {
3623 $text = $skip = false;
3624 $finalTitle = $title;
3627 # Loop to fetch the article, with up to 1 redirect
3628 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3629 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3630 # Give extensions a chance to select the revision instead
3631 $id = false; # Assume current
3632 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3633 [ $parser, $title, &$skip, &$id ] );
3639 'page_id' => $title->getArticleID(),
3646 $rev = Revision
::newFromId( $id );
3647 } elseif ( $parser ) {
3648 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3650 $rev = Revision
::newFromTitle( $title );
3652 $rev_id = $rev ?
$rev->getId() : 0;
3653 # If there is no current revision, there is no page
3654 if ( $id === false && !$rev ) {
3655 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3656 $linkCache->addBadLinkObj( $title );
3661 'page_id' => $title->getArticleID(),
3662 'rev_id' => $rev_id ];
3663 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3664 # We fetched a rev from a different title; register it too...
3666 'title' => $rev->getTitle(),
3667 'page_id' => $rev->getPage(),
3668 'rev_id' => $rev_id ];
3672 $content = $rev->getContent();
3673 $text = $content ?
$content->getWikitextForTransclusion() : null;
3675 Hooks
::run( 'ParserFetchTemplate',
3676 [ $parser, $title, $rev, &$text, &$deps ] );
3678 if ( $text === false ||
$text === null ) {
3682 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3683 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3684 lcfirst( $title->getText() ) )->inContentLanguage();
3685 if ( !$message->exists() ) {
3689 $content = $message->content();
3690 $text = $message->plain();
3698 $finalTitle = $title;
3699 $title = $content->getRedirectTarget();
3703 'finalTitle' => $finalTitle,
3708 * Fetch a file and its title and register a reference to it.
3709 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3710 * @param Title $title
3711 * @param array $options Array of options to RepoGroup::findFile
3713 * @deprecated since 1.32, use fetchFileAndTitle instead
3715 public function fetchFile( $title, $options = [] ) {
3716 wfDeprecated( __METHOD__
, '1.32' );
3717 return $this->fetchFileAndTitle( $title, $options )[0];
3721 * Fetch a file and its title and register a reference to it.
3722 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3723 * @param Title $title
3724 * @param array $options Array of options to RepoGroup::findFile
3725 * @return array ( File or false, Title of file )
3727 public function fetchFileAndTitle( $title, $options = [] ) {
3728 $file = $this->fetchFileNoRegister( $title, $options );
3730 $time = $file ?
$file->getTimestamp() : false;
3731 $sha1 = $file ?
$file->getSha1() : false;
3732 # Register the file as a dependency...
3733 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3734 if ( $file && !$title->equals( $file->getTitle() ) ) {
3735 # Update fetched file title
3736 $title = $file->getTitle();
3737 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3739 return [ $file, $title ];
3743 * Helper function for fetchFileAndTitle.
3745 * Also useful if you need to fetch a file but not use it yet,
3746 * for example to get the file's handler.
3748 * @param Title $title
3749 * @param array $options Array of options to RepoGroup::findFile
3752 protected function fetchFileNoRegister( $title, $options = [] ) {
3753 if ( isset( $options['broken'] ) ) {
3754 $file = false; // broken thumbnail forced by hook
3755 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3756 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3757 } else { // get by (name,timestamp)
3758 $file = wfFindFile( $title, $options );
3764 * Transclude an interwiki link.
3766 * @param Title $title
3767 * @param string $action
3771 public function interwikiTransclude( $title, $action ) {
3772 global $wgEnableScaryTranscluding;
3774 if ( !$wgEnableScaryTranscluding ) {
3775 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3778 $url = $title->getFullURL( [ 'action' => $action ] );
3780 if ( strlen( $url ) > 255 ) {
3781 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3783 return $this->fetchScaryTemplateMaybeFromCache( $url );
3787 * @param string $url
3788 * @return mixed|string
3790 public function fetchScaryTemplateMaybeFromCache( $url ) {
3791 global $wgTranscludeCacheExpiry;
3792 $dbr = wfGetDB( DB_REPLICA
);
3793 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3794 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3795 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3797 return $obj->tc_contents
;
3800 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3801 $status = $req->execute(); // Status object
3802 if ( $status->isOK() ) {
3803 $text = $req->getContent();
3804 } elseif ( $req->getStatus() != 200 ) {
3805 // Though we failed to fetch the content, this status is useless.
3806 return wfMessage( 'scarytranscludefailed-httpstatus' )
3807 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3809 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3812 $dbw = wfGetDB( DB_MASTER
);
3813 $dbw->replace( 'transcache', [ 'tc_url' ], [
3815 'tc_time' => $dbw->timestamp( time() ),
3816 'tc_contents' => $text
3822 * Triple brace replacement -- used for template arguments
3825 * @param array $piece
3826 * @param PPFrame $frame
3830 public function argSubstitution( $piece, $frame ) {
3832 $parts = $piece['parts'];
3833 $nameWithSpaces = $frame->expand( $piece['title'] );
3834 $argName = trim( $nameWithSpaces );
3836 $text = $frame->getArgument( $argName );
3837 if ( $text === false && $parts->getLength() > 0
3838 && ( $this->ot
['html']
3840 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3843 # No match in frame, use the supplied default
3844 $object = $parts->item( 0 )->getChildren();
3846 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3847 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3848 $this->limitationWarn( 'post-expand-template-argument' );
3851 if ( $text === false && $object === false ) {
3853 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3855 if ( $error !== false ) {
3858 if ( $object !== false ) {
3859 $ret = [ 'object' => $object ];
3861 $ret = [ 'text' => $text ];
3868 * Return the text to be used for a given extension tag.
3869 * This is the ghost of strip().
3871 * @param array $params Associative array of parameters:
3872 * name PPNode for the tag name
3873 * attr PPNode for unparsed text where tag attributes are thought to be
3874 * attributes Optional associative array of parsed attributes
3875 * inner Contents of extension element
3876 * noClose Original text did not have a close tag
3877 * @param PPFrame $frame
3879 * @throws MWException
3882 public function extensionSubstitution( $params, $frame ) {
3883 static $errorStr = '<span class="error">';
3884 static $errorLen = 20;
3886 $name = $frame->expand( $params['name'] );
3887 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3888 // Probably expansion depth or node count exceeded. Just punt the
3893 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3894 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3899 // We can't safely check if the expansion for $content resulted in an
3900 // error, because the content could happen to be the error string
3902 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3904 $marker = self
::MARKER_PREFIX
. "-$name-"
3905 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3907 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3908 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3909 if ( $isFunctionTag ) {
3910 $markerType = 'none';
3912 $markerType = 'general';
3914 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3915 $name = strtolower( $name );
3916 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3917 if ( isset( $params['attributes'] ) ) {
3918 $attributes = $attributes +
$params['attributes'];
3921 if ( isset( $this->mTagHooks
[$name] ) ) {
3922 $output = call_user_func_array( $this->mTagHooks
[$name],
3923 [ $content, $attributes, $this, $frame ] );
3924 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3925 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3927 // Avoid PHP 7.1 warning from passing $this by reference
3929 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3931 $output = '<span class="error">Invalid tag extension name: ' .
3932 htmlspecialchars( $name ) . '</span>';
3935 if ( is_array( $output ) ) {
3938 $output = $flags[0];
3939 if ( isset( $flags['markerType'] ) ) {
3940 $markerType = $flags['markerType'];
3944 if ( is_null( $attrText ) ) {
3947 if ( isset( $params['attributes'] ) ) {
3948 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3949 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3950 htmlspecialchars( $attrValue ) . '"';
3953 if ( $content === null ) {
3954 $output = "<$name$attrText/>";
3956 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3957 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3961 $output = "<$name$attrText>$content$close";
3965 if ( $markerType === 'none' ) {
3967 } elseif ( $markerType === 'nowiki' ) {
3968 $this->mStripState
->addNoWiki( $marker, $output );
3969 } elseif ( $markerType === 'general' ) {
3970 $this->mStripState
->addGeneral( $marker, $output );
3972 throw new MWException( __METHOD__
. ': invalid marker type' );
3978 * Increment an include size counter
3980 * @param string $type The type of expansion
3981 * @param int $size The size of the text
3982 * @return bool False if this inclusion would take it over the maximum, true otherwise
3984 public function incrementIncludeSize( $type, $size ) {
3985 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3988 $this->mIncludeSizes
[$type] +
= $size;
3994 * Increment the expensive function count
3996 * @return bool False if the limit has been exceeded
3998 public function incrementExpensiveFunctionCount() {
3999 $this->mExpensiveFunctionCount++
;
4000 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4004 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4005 * Fills $this->mDoubleUnderscores, returns the modified text
4007 * @param string $text
4011 public function doDoubleUnderscore( $text ) {
4012 # The position of __TOC__ needs to be recorded
4013 $mw = $this->magicWordFactory
->get( 'toc' );
4014 if ( $mw->match( $text ) ) {
4015 $this->mShowToc
= true;
4016 $this->mForceTocPosition
= true;
4018 # Set a placeholder. At the end we'll fill it in with the TOC.
4019 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4021 # Only keep the first one.
4022 $text = $mw->replace( '', $text );
4025 # Now match and remove the rest of them
4026 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4027 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4029 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4030 $this->mOutput
->mNoGallery
= true;
4032 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4033 $this->mShowToc
= false;
4035 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4036 && $this->mTitle
->getNamespace() == NS_CATEGORY
4038 $this->addTrackingCategory( 'hidden-category-category' );
4040 # (T10068) Allow control over whether robots index a page.
4041 # __INDEX__ always overrides __NOINDEX__, see T16899
4042 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4043 $this->mOutput
->setIndexPolicy( 'noindex' );
4044 $this->addTrackingCategory( 'noindex-category' );
4046 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4047 $this->mOutput
->setIndexPolicy( 'index' );
4048 $this->addTrackingCategory( 'index-category' );
4051 # Cache all double underscores in the database
4052 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4053 $this->mOutput
->setProperty( $key, '' );
4060 * @see ParserOutput::addTrackingCategory()
4061 * @param string $msg Message key
4062 * @return bool Whether the addition was successful
4064 public function addTrackingCategory( $msg ) {
4065 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4069 * This function accomplishes several tasks:
4070 * 1) Auto-number headings if that option is enabled
4071 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4072 * 3) Add a Table of contents on the top for users who have enabled the option
4073 * 4) Auto-anchor headings
4075 * It loops through all headlines, collects the necessary data, then splits up the
4076 * string and re-inserts the newly formatted headlines.
4078 * @param string $text
4079 * @param string $origText Original, untouched wikitext
4080 * @param bool $isMain
4081 * @return mixed|string
4084 public function formatHeadings( $text, $origText, $isMain = true ) {
4085 global $wgMaxTocLevel;
4087 # Inhibit editsection links if requested in the page
4088 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4089 $maybeShowEditLink = false;
4091 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4094 # Get all headlines for numbering them and adding funky stuff like [edit]
4095 # links - this is for later, but we need the number of headlines right now
4096 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4097 # be trimmed here since whitespace in HTML headings is significant.
4099 $numMatches = preg_match_all(
4100 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4105 # if there are fewer than 4 headlines in the article, do not show TOC
4106 # unless it's been explicitly enabled.
4107 $enoughToc = $this->mShowToc
&&
4108 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4110 # Allow user to stipulate that a page should have a "new section"
4111 # link added via __NEWSECTIONLINK__
4112 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4113 $this->mOutput
->setNewSection( true );
4116 # Allow user to remove the "new section"
4117 # link via __NONEWSECTIONLINK__
4118 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4119 $this->mOutput
->hideNewSection( true );
4122 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4123 # override above conditions and always show TOC above first header
4124 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4125 $this->mShowToc
= true;
4133 # Ugh .. the TOC should have neat indentation levels which can be
4134 # passed to the skin functions. These are determined here
4138 $sublevelCount = [];
4144 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4145 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4146 $oldType = $this->mOutputType
;
4147 $this->setOutputType( self
::OT_WIKI
);
4148 $frame = $this->getPreprocessor()->newFrame();
4149 $root = $this->preprocessToDom( $origText );
4150 $node = $root->getFirstChild();
4155 $headlines = $numMatches !== false ?
$matches[3] : [];
4157 foreach ( $headlines as $headline ) {
4158 $isTemplate = false;
4160 $sectionIndex = false;
4162 $markerMatches = [];
4163 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4164 $serial = $markerMatches[1];
4165 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4166 $isTemplate = ( $titleText != $baseTitleText );
4167 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4171 $prevlevel = $level;
4173 $level = $matches[1][$headlineCount];
4175 if ( $level > $prevlevel ) {
4176 # Increase TOC level
4178 $sublevelCount[$toclevel] = 0;
4179 if ( $toclevel < $wgMaxTocLevel ) {
4180 $prevtoclevel = $toclevel;
4181 $toc .= Linker
::tocIndent();
4184 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4185 # Decrease TOC level, find level to jump to
4187 for ( $i = $toclevel; $i > 0; $i-- ) {
4188 if ( $levelCount[$i] == $level ) {
4189 # Found last matching level
4192 } elseif ( $levelCount[$i] < $level ) {
4193 # Found first matching level below current level
4201 if ( $toclevel < $wgMaxTocLevel ) {
4202 if ( $prevtoclevel < $wgMaxTocLevel ) {
4203 # Unindent only if the previous toc level was shown :p
4204 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4205 $prevtoclevel = $toclevel;
4207 $toc .= Linker
::tocLineEnd();
4211 # No change in level, end TOC line
4212 if ( $toclevel < $wgMaxTocLevel ) {
4213 $toc .= Linker
::tocLineEnd();
4217 $levelCount[$toclevel] = $level;
4219 # count number of headlines for each level
4220 $sublevelCount[$toclevel]++
;
4222 for ( $i = 1; $i <= $toclevel; $i++
) {
4223 if ( !empty( $sublevelCount[$i] ) ) {
4227 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4232 # The safe header is a version of the header text safe to use for links
4234 # Remove link placeholders by the link text.
4235 # <!--LINK number-->
4237 # link text with suffix
4238 # Do this before unstrip since link text can contain strip markers
4239 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4241 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4242 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4244 # Remove any <style> or <script> tags (T198618)
4245 $safeHeadline = preg_replace(
4246 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4251 # Strip out HTML (first regex removes any tag not allowed)
4253 # * <sup> and <sub> (T10393)
4257 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4258 # * <s> and <strike> (T35715)
4259 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4260 # to allow setting directionality in toc items.
4261 $tocline = preg_replace(
4263 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4264 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4270 # Strip '<span></span>', which is the result from the above if
4271 # <span id="foo"></span> is used to produce an additional anchor
4273 $tocline = str_replace( '<span></span>', '', $tocline );
4275 $tocline = trim( $tocline );
4277 # For the anchor, strip out HTML-y stuff period
4278 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4279 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4281 # Save headline for section edit hint before it's escaped
4282 $headlineHint = $safeHeadline;
4284 # Decode HTML entities
4285 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4287 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4289 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4290 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4291 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4292 if ( $fallbackHeadline === $safeHeadline ) {
4293 # No reason to have both (in fact, we can't)
4294 $fallbackHeadline = false;
4297 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4298 # @todo FIXME: We may be changing them depending on the current locale.
4299 $arrayKey = strtolower( $safeHeadline );
4300 if ( $fallbackHeadline === false ) {
4301 $fallbackArrayKey = false;
4303 $fallbackArrayKey = strtolower( $fallbackHeadline );
4306 # Create the anchor for linking from the TOC to the section
4307 $anchor = $safeHeadline;
4308 $fallbackAnchor = $fallbackHeadline;
4309 if ( isset( $refers[$arrayKey] ) ) {
4310 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4311 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4313 $linkAnchor .= "_$i";
4314 $refers["${arrayKey}_$i"] = true;
4316 $refers[$arrayKey] = true;
4318 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4319 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4320 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4321 $fallbackAnchor .= "_$i";
4322 $refers["${fallbackArrayKey}_$i"] = true;
4324 $refers[$fallbackArrayKey] = true;
4327 # Don't number the heading if it is the only one (looks silly)
4328 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4329 # the two are different if the line contains a link
4330 $headline = Html
::element(
4332 [ 'class' => 'mw-headline-number' ],
4334 ) . ' ' . $headline;
4337 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4338 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4339 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4342 # Add the section to the section tree
4343 # Find the DOM node for this header
4344 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4345 while ( $node && !$noOffset ) {
4346 if ( $node->getName() === 'h' ) {
4347 $bits = $node->splitHeading();
4348 if ( $bits['i'] == $sectionIndex ) {
4352 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4353 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4354 $node = $node->getNextSibling();
4357 'toclevel' => $toclevel,
4360 'number' => $numbering,
4361 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4362 'fromtitle' => $titleText,
4363 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4364 'anchor' => $anchor,
4367 # give headline the correct <h#> tag
4368 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4369 // Output edit section links as markers with styles that can be customized by skins
4370 if ( $isTemplate ) {
4371 # Put a T flag in the section identifier, to indicate to extractSections()
4372 # that sections inside <includeonly> should be counted.
4373 $editsectionPage = $titleText;
4374 $editsectionSection = "T-$sectionIndex";
4375 $editsectionContent = null;
4377 $editsectionPage = $this->mTitle
->getPrefixedText();
4378 $editsectionSection = $sectionIndex;
4379 $editsectionContent = $headlineHint;
4381 // We use a bit of pesudo-xml for editsection markers. The
4382 // language converter is run later on. Using a UNIQ style marker
4383 // leads to the converter screwing up the tokens when it
4384 // converts stuff. And trying to insert strip tags fails too. At
4385 // this point all real inputted tags have already been escaped,
4386 // so we don't have to worry about a user trying to input one of
4387 // these markers directly. We use a page and section attribute
4388 // to stop the language converter from converting these
4389 // important bits of data, but put the headline hint inside a
4390 // content block because the language converter is supposed to
4391 // be able to convert that piece of data.
4392 // Gets replaced with html in ParserOutput::getText
4393 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4394 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4395 if ( $editsectionContent !== null ) {
4396 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4403 $head[$headlineCount] = Linker
::makeHeadline( $level,
4404 $matches['attrib'][$headlineCount], $anchor, $headline,
4405 $editlink, $fallbackAnchor );
4410 $this->setOutputType( $oldType );
4412 # Never ever show TOC if no headers
4413 if ( $numVisible < 1 ) {
4418 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4419 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4421 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4422 $this->mOutput
->setTOCHTML( $toc );
4423 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4427 $this->mOutput
->setSections( $tocraw );
4430 # split up and insert constructed headlines
4431 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4434 // build an array of document sections
4436 foreach ( $blocks as $block ) {
4437 // $head is zero-based, sections aren't.
4438 if ( empty( $head[$i - 1] ) ) {
4439 $sections[$i] = $block;
4441 $sections[$i] = $head[$i - 1] . $block;
4445 * Send a hook, one per section.
4446 * The idea here is to be able to make section-level DIVs, but to do so in a
4447 * lower-impact, more correct way than r50769
4450 * $section : the section number
4451 * &$sectionContent : ref to the content of the section
4452 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4454 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4459 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4460 // append the TOC at the beginning
4461 // Top anchor now in skin
4462 $sections[0] = $sections[0] . $toc . "\n";
4465 $full .= implode( '', $sections );
4467 if ( $this->mForceTocPosition
) {
4468 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4475 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4476 * conversion, substituting signatures, {{subst:}} templates, etc.
4478 * @param string $text The text to transform
4479 * @param Title $title The Title object for the current article
4480 * @param User $user The User object describing the current user
4481 * @param ParserOptions $options Parsing options
4482 * @param bool $clearState Whether to clear the parser state first
4483 * @return string The altered wiki markup
4485 public function preSaveTransform( $text, Title
$title, User
$user,
4486 ParserOptions
$options, $clearState = true
4488 if ( $clearState ) {
4489 $magicScopeVariable = $this->lock();
4491 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4492 $this->setUser( $user );
4494 // Strip U+0000 NULL (T159174)
4495 $text = str_replace( "\000", '', $text );
4497 // We still normalize line endings for backwards-compatibility
4498 // with other code that just calls PST, but this should already
4499 // be handled in TextContent subclasses
4500 $text = TextContent
::normalizeLineEndings( $text );
4502 if ( $options->getPreSaveTransform() ) {
4503 $text = $this->pstPass2( $text, $user );
4505 $text = $this->mStripState
->unstripBoth( $text );
4507 $this->setUser( null ); # Reset
4513 * Pre-save transform helper function
4515 * @param string $text
4520 private function pstPass2( $text, $user ) {
4521 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4522 # $this->getContentLanguage() here in order to give everyone the same signature and use the
4523 # default one rather than the one selected in each user's preferences. (see also T14815)
4524 $ts = $this->mOptions
->getTimestamp();
4525 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4526 $ts = $timestamp->format( 'YmdHis' );
4527 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4529 $d = $this->getContentLanguage()->timeanddate( $ts, false, false ) . " ($tzMsg)";
4531 # Variable replacement
4532 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4533 $text = $this->replaceVariables( $text );
4535 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4536 # which may corrupt this parser instance via its wfMessage()->text() call-
4539 if ( strpos( $text, '~~~' ) !== false ) {
4540 $sigText = $this->getUserSig( $user );
4541 $text = strtr( $text, [
4543 '~~~~' => "$sigText $d",
4546 # The main two signature forms used above are time-sensitive
4547 $this->mOutput
->setFlag( 'user-signature' );
4550 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4551 $tc = '[' . Title
::legalChars() . ']';
4552 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4554 // [[ns:page (context)|]]
4555 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4556 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4557 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4558 // [[ns:page (context), context|]] (using either single or double-width comma)
4559 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4560 // [[|page]] (reverse pipe trick: add context from page title)
4561 $p2 = "/\[\[\\|($tc+)]]/";
4563 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4564 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4565 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4566 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4568 $t = $this->mTitle
->getText();
4570 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4571 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4572 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4573 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4575 # if there's no context, don't bother duplicating the title
4576 $text = preg_replace( $p2, '[[\\1]]', $text );
4583 * Fetch the user's signature text, if any, and normalize to
4584 * validated, ready-to-insert wikitext.
4585 * If you have pre-fetched the nickname or the fancySig option, you can
4586 * specify them here to save a database query.
4587 * Do not reuse this parser instance after calling getUserSig(),
4588 * as it may have changed if it's the $wgParser.
4590 * @param User &$user
4591 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4592 * @param bool|null $fancySig whether the nicknname is the complete signature
4593 * or null to use default value
4596 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4597 global $wgMaxSigChars;
4599 $username = $user->getName();
4601 # If not given, retrieve from the user object.
4602 if ( $nickname === false ) {
4603 $nickname = $user->getOption( 'nickname' );
4606 if ( is_null( $fancySig ) ) {
4607 $fancySig = $user->getBoolOption( 'fancysig' );
4610 $nickname = $nickname == null ?
$username : $nickname;
4612 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4613 $nickname = $username;
4614 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4615 } elseif ( $fancySig !== false ) {
4616 # Sig. might contain markup; validate this
4617 if ( $this->validateSig( $nickname ) !== false ) {
4618 # Validated; clean up (if needed) and return it
4619 return $this->cleanSig( $nickname, true );
4621 # Failed to validate; fall back to the default
4622 $nickname = $username;
4623 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4627 # Make sure nickname doesnt get a sig in a sig
4628 $nickname = self
::cleanSigInSig( $nickname );
4630 # If we're still here, make it a link to the user page
4631 $userText = wfEscapeWikiText( $username );
4632 $nickText = wfEscapeWikiText( $nickname );
4633 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4635 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4636 ->title( $this->getTitle() )->text();
4640 * Check that the user's signature contains no bad XML
4642 * @param string $text
4643 * @return string|bool An expanded string, or false if invalid.
4645 public function validateSig( $text ) {
4646 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4650 * Clean up signature text
4652 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4653 * 2) Substitute all transclusions
4655 * @param string $text
4656 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4657 * @return string Signature text
4659 public function cleanSig( $text, $parsing = false ) {
4662 $magicScopeVariable = $this->lock();
4663 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4666 # Option to disable this feature
4667 if ( !$this->mOptions
->getCleanSignatures() ) {
4671 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4672 # => Move this logic to braceSubstitution()
4673 $substWord = $this->magicWordFactory
->get( 'subst' );
4674 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4675 $substText = '{{' . $substWord->getSynonym( 0 );
4677 $text = preg_replace( $substRegex, $substText, $text );
4678 $text = self
::cleanSigInSig( $text );
4679 $dom = $this->preprocessToDom( $text );
4680 $frame = $this->getPreprocessor()->newFrame();
4681 $text = $frame->expand( $dom );
4684 $text = $this->mStripState
->unstripBoth( $text );
4691 * Strip 3, 4 or 5 tildes out of signatures.
4693 * @param string $text
4694 * @return string Signature text with /~{3,5}/ removed
4696 public static function cleanSigInSig( $text ) {
4697 $text = preg_replace( '/~{3,5}/', '', $text );
4702 * Set up some variables which are usually set up in parse()
4703 * so that an external function can call some class members with confidence
4705 * @param Title|null $title
4706 * @param ParserOptions $options
4707 * @param int $outputType
4708 * @param bool $clearState
4710 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4711 $outputType, $clearState = true
4713 $this->startParse( $title, $options, $outputType, $clearState );
4717 * @param Title|null $title
4718 * @param ParserOptions $options
4719 * @param int $outputType
4720 * @param bool $clearState
4722 private function startParse( Title
$title = null, ParserOptions
$options,
4723 $outputType, $clearState = true
4725 $this->setTitle( $title );
4726 $this->mOptions
= $options;
4727 $this->setOutputType( $outputType );
4728 if ( $clearState ) {
4729 $this->clearState();
4734 * Wrapper for preprocess()
4736 * @param string $text The text to preprocess
4737 * @param ParserOptions $options
4738 * @param Title|null $title Title object or null to use $wgTitle
4741 public function transformMsg( $text, $options, $title = null ) {
4742 static $executing = false;
4744 # Guard against infinite recursion
4755 $text = $this->preprocess( $text, $title, $options );
4762 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4763 * The callback should have the following form:
4764 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4766 * Transform and return $text. Use $parser for any required context, e.g. use
4767 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4769 * Hooks may return extended information by returning an array, of which the
4770 * first numbered element (index 0) must be the return string, and all other
4771 * entries are extracted into local variables within an internal function
4772 * in the Parser class.
4774 * This interface (introduced r61913) appears to be undocumented, but
4775 * 'markerType' is used by some core tag hooks to override which strip
4776 * array their results are placed in. **Use great caution if attempting
4777 * this interface, as it is not documented and injudicious use could smash
4778 * private variables.**
4780 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4781 * @param callable $callback The callback function (and object) to use for the tag
4782 * @throws MWException
4783 * @return callable|null The old value of the mTagHooks array associated with the hook
4785 public function setHook( $tag, callable
$callback ) {
4786 $tag = strtolower( $tag );
4787 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4788 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4790 $oldVal = $this->mTagHooks
[$tag] ??
null;
4791 $this->mTagHooks
[$tag] = $callback;
4792 if ( !in_array( $tag, $this->mStripList
) ) {
4793 $this->mStripList
[] = $tag;
4800 * As setHook(), but letting the contents be parsed.
4802 * Transparent tag hooks are like regular XML-style tag hooks, except they
4803 * operate late in the transformation sequence, on HTML instead of wikitext.
4805 * This is probably obsoleted by things dealing with parser frames?
4806 * The only extension currently using it is geoserver.
4809 * @todo better document or deprecate this
4811 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4812 * @param callable $callback The callback function (and object) to use for the tag
4813 * @throws MWException
4814 * @return callable|null The old value of the mTagHooks array associated with the hook
4816 public function setTransparentTagHook( $tag, callable
$callback ) {
4817 $tag = strtolower( $tag );
4818 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4819 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4821 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4822 $this->mTransparentTagHooks
[$tag] = $callback;
4828 * Remove all tag hooks
4830 public function clearTagHooks() {
4831 $this->mTagHooks
= [];
4832 $this->mFunctionTagHooks
= [];
4833 $this->mStripList
= $this->mDefaultStripList
;
4837 * Create a function, e.g. {{sum:1|2|3}}
4838 * The callback function should have the form:
4839 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4841 * Or with Parser::SFH_OBJECT_ARGS:
4842 * function myParserFunction( $parser, $frame, $args ) { ... }
4844 * The callback may either return the text result of the function, or an array with the text
4845 * in element 0, and a number of flags in the other elements. The names of the flags are
4846 * specified in the keys. Valid flags are:
4847 * found The text returned is valid, stop processing the template. This
4849 * nowiki Wiki markup in the return value should be escaped
4850 * isHTML The returned text is HTML, armour it against wikitext transformation
4852 * @param string $id The magic word ID
4853 * @param callable $callback The callback function (and object) to use
4854 * @param int $flags A combination of the following flags:
4855 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4857 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4858 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4859 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4860 * the arguments, and to control the way they are expanded.
4862 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4863 * arguments, for instance:
4864 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4866 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4867 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4868 * working if/when this is changed.
4870 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4873 * Please read the documentation in includes/parser/Preprocessor.php for more information
4874 * about the methods available in PPFrame and PPNode.
4876 * @throws MWException
4877 * @return string|callable The old callback function for this name, if any
4879 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4880 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4881 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4883 # Add to function cache
4884 $mw = $this->magicWordFactory
->get( $id );
4886 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4889 $synonyms = $mw->getSynonyms();
4890 $sensitive = intval( $mw->isCaseSensitive() );
4892 foreach ( $synonyms as $syn ) {
4894 if ( !$sensitive ) {
4895 $syn = $this->getContentLanguage()->lc( $syn );
4898 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4901 # Remove trailing colon
4902 if ( substr( $syn, -1, 1 ) === ':' ) {
4903 $syn = substr( $syn, 0, -1 );
4905 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4911 * Get all registered function hook identifiers
4915 public function getFunctionHooks() {
4916 return array_keys( $this->mFunctionHooks
);
4920 * Create a tag function, e.g. "<test>some stuff</test>".
4921 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4922 * Unlike parser functions, their content is not preprocessed.
4923 * @param string $tag
4924 * @param callable $callback
4926 * @throws MWException
4929 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4930 $tag = strtolower( $tag );
4931 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4932 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4934 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4935 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4937 if ( !in_array( $tag, $this->mStripList
) ) {
4938 $this->mStripList
[] = $tag;
4945 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4946 * Placeholders created in Linker::link()
4948 * @param string &$text
4949 * @param int $options
4951 public function replaceLinkHolders( &$text, $options = 0 ) {
4952 $this->mLinkHolders
->replace( $text );
4956 * Replace "<!--LINK-->" link placeholders with plain text of links
4957 * (not HTML-formatted).
4959 * @param string $text
4962 public function replaceLinkHoldersText( $text ) {
4963 return $this->mLinkHolders
->replaceText( $text );
4967 * Renders an image gallery from a text with one line per image.
4968 * text labels may be given by using |-style alternative text. E.g.
4969 * Image:one.jpg|The number "1"
4970 * Image:tree.jpg|A tree
4971 * given as text will return the HTML of a gallery with two images,
4972 * labeled 'The number "1"' and
4975 * @param string $text
4976 * @param array $params
4977 * @return string HTML
4979 public function renderImageGallery( $text, $params ) {
4981 if ( isset( $params['mode'] ) ) {
4982 $mode = $params['mode'];
4986 $ig = ImageGalleryBase
::factory( $mode );
4987 } catch ( Exception
$e ) {
4988 // If invalid type set, fallback to default.
4989 $ig = ImageGalleryBase
::factory( false );
4992 $ig->setContextTitle( $this->mTitle
);
4993 $ig->setShowBytes( false );
4994 $ig->setShowDimensions( false );
4995 $ig->setShowFilename( false );
4996 $ig->setParser( $this );
4997 $ig->setHideBadImages();
4998 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5000 if ( isset( $params['showfilename'] ) ) {
5001 $ig->setShowFilename( true );
5003 $ig->setShowFilename( false );
5005 if ( isset( $params['caption'] ) ) {
5006 $caption = $params['caption'];
5007 $caption = htmlspecialchars( $caption );
5008 $caption = $this->replaceInternalLinks( $caption );
5009 $ig->setCaptionHtml( $caption );
5011 if ( isset( $params['perrow'] ) ) {
5012 $ig->setPerRow( $params['perrow'] );
5014 if ( isset( $params['widths'] ) ) {
5015 $ig->setWidths( $params['widths'] );
5017 if ( isset( $params['heights'] ) ) {
5018 $ig->setHeights( $params['heights'] );
5020 $ig->setAdditionalOptions( $params );
5022 // Avoid PHP 7.1 warning from passing $this by reference
5024 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5026 $lines = StringUtils
::explode( "\n", $text );
5027 foreach ( $lines as $line ) {
5028 # match lines like these:
5029 # Image:someimage.jpg|This is some image
5031 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5033 if ( count( $matches ) == 0 ) {
5037 if ( strpos( $matches[0], '%' ) !== false ) {
5038 $matches[1] = rawurldecode( $matches[1] );
5040 $title = Title
::newFromText( $matches[1], NS_FILE
);
5041 if ( is_null( $title ) ) {
5042 # Bogus title. Ignore these so we don't bomb out later.
5046 # We need to get what handler the file uses, to figure out parameters.
5047 # Note, a hook can overide the file name, and chose an entirely different
5048 # file (which potentially could be of a different type and have different handler).
5051 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5052 [ $this, $title, &$options, &$descQuery ] );
5053 # Don't register it now, as TraditionalImageGallery does that later.
5054 $file = $this->fetchFileNoRegister( $title, $options );
5055 $handler = $file ?
$file->getHandler() : false;
5058 'img_alt' => 'gallery-internal-alt',
5059 'img_link' => 'gallery-internal-link',
5062 $paramMap = $paramMap +
$handler->getParamMap();
5063 // We don't want people to specify per-image widths.
5064 // Additionally the width parameter would need special casing anyhow.
5065 unset( $paramMap['img_width'] );
5068 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5073 $handlerOptions = [];
5074 if ( isset( $matches[3] ) ) {
5075 // look for an |alt= definition while trying not to break existing
5076 // captions with multiple pipes (|) in it, until a more sensible grammar
5077 // is defined for images in galleries
5079 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5080 // splitting on '|' is a bit odd, and different from makeImage.
5081 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5082 // Protect LanguageConverter markup
5083 $parameterMatches = StringUtils
::delimiterExplode(
5084 '-{', '}-', '|', $matches[3], true /* nested */
5087 foreach ( $parameterMatches as $parameterMatch ) {
5088 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5090 $paramName = $paramMap[$magicName];
5092 switch ( $paramName ) {
5093 case 'gallery-internal-alt':
5094 $alt = $this->stripAltText( $match, false );
5096 case 'gallery-internal-link':
5097 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5098 $chars = self
::EXT_LINK_URL_CLASS
;
5099 $addr = self
::EXT_LINK_ADDR
;
5100 $prots = $this->mUrlProtocols
;
5101 // check to see if link matches an absolute url, if not then it must be a wiki link.
5102 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5103 // Result of LanguageConverter::markNoConversion
5104 // invoked on an external link.
5105 $linkValue = substr( $linkValue, 4, -2 );
5107 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5109 $this->mOutput
->addExternalLink( $link );
5111 $localLinkTitle = Title
::newFromText( $linkValue );
5112 if ( $localLinkTitle !== null ) {
5113 $this->mOutput
->addLink( $localLinkTitle );
5114 $link = $localLinkTitle->getLinkURL();
5119 // Must be a handler specific parameter.
5120 if ( $handler->validateParam( $paramName, $match ) ) {
5121 $handlerOptions[$paramName] = $match;
5123 // Guess not, consider it as caption.
5124 wfDebug( "$parameterMatch failed parameter validation\n" );
5125 $label = $parameterMatch;
5131 $label = $parameterMatch;
5136 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5138 $html = $ig->toHTML();
5139 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5144 * @param MediaHandler $handler
5147 public function getImageParams( $handler ) {
5149 $handlerClass = get_class( $handler );
5153 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5154 # Initialise static lists
5155 static $internalParamNames = [
5156 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5157 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5158 'bottom', 'text-bottom' ],
5159 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5160 'upright', 'border', 'link', 'alt', 'class' ],
5162 static $internalParamMap;
5163 if ( !$internalParamMap ) {
5164 $internalParamMap = [];
5165 foreach ( $internalParamNames as $type => $names ) {
5166 foreach ( $names as $name ) {
5167 // For grep: img_left, img_right, img_center, img_none,
5168 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5169 // img_bottom, img_text_bottom,
5170 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5171 // img_border, img_link, img_alt, img_class
5172 $magicName = str_replace( '-', '_', "img_$name" );
5173 $internalParamMap[$magicName] = [ $type, $name ];
5178 # Add handler params
5179 $paramMap = $internalParamMap;
5181 $handlerParamMap = $handler->getParamMap();
5182 foreach ( $handlerParamMap as $magic => $paramName ) {
5183 $paramMap[$magic] = [ 'handler', $paramName ];
5186 $this->mImageParams
[$handlerClass] = $paramMap;
5187 $this->mImageParamsMagicArray
[$handlerClass] =
5188 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5190 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5194 * Parse image options text and use it to make an image
5196 * @param Title $title
5197 * @param string $options
5198 * @param LinkHolderArray|bool $holders
5199 * @return string HTML
5201 public function makeImage( $title, $options, $holders = false ) {
5202 # Check if the options text is of the form "options|alt text"
5204 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5205 # * left no resizing, just left align. label is used for alt= only
5206 # * right same, but right aligned
5207 # * none same, but not aligned
5208 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5209 # * center center the image
5210 # * frame Keep original image size, no magnify-button.
5211 # * framed Same as "frame"
5212 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5213 # * upright reduce width for upright images, rounded to full __0 px
5214 # * border draw a 1px border around the image
5215 # * alt Text for HTML alt attribute (defaults to empty)
5216 # * class Set a class for img node
5217 # * link Set the target of the image link. Can be external, interwiki, or local
5218 # vertical-align values (no % or length right now):
5228 # Protect LanguageConverter markup when splitting into parts
5229 $parts = StringUtils
::delimiterExplode(
5230 '-{', '}-', '|', $options, true /* allow nesting */
5233 # Give extensions a chance to select the file revision for us
5236 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5237 [ $this, $title, &$options, &$descQuery ] );
5238 # Fetch and register the file (file title may be different via hooks)
5239 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5242 $handler = $file ?
$file->getHandler() : false;
5244 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5247 $this->addTrackingCategory( 'broken-file-category' );
5250 # Process the input parameters
5252 $params = [ 'frame' => [], 'handler' => [],
5253 'horizAlign' => [], 'vertAlign' => [] ];
5254 $seenformat = false;
5255 foreach ( $parts as $part ) {
5256 $part = trim( $part );
5257 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5259 if ( isset( $paramMap[$magicName] ) ) {
5260 list( $type, $paramName ) = $paramMap[$magicName];
5262 # Special case; width and height come in one variable together
5263 if ( $type === 'handler' && $paramName === 'width' ) {
5264 $parsedWidthParam = self
::parseWidthParam( $value );
5265 if ( isset( $parsedWidthParam['width'] ) ) {
5266 $width = $parsedWidthParam['width'];
5267 if ( $handler->validateParam( 'width', $width ) ) {
5268 $params[$type]['width'] = $width;
5272 if ( isset( $parsedWidthParam['height'] ) ) {
5273 $height = $parsedWidthParam['height'];
5274 if ( $handler->validateParam( 'height', $height ) ) {
5275 $params[$type]['height'] = $height;
5279 # else no validation -- T15436
5281 if ( $type === 'handler' ) {
5282 # Validate handler parameter
5283 $validated = $handler->validateParam( $paramName, $value );
5285 # Validate internal parameters
5286 switch ( $paramName ) {
5290 # @todo FIXME: Possibly check validity here for
5291 # manualthumb? downstream behavior seems odd with
5292 # missing manual thumbs.
5294 $value = $this->stripAltText( $value, $holders );
5297 $chars = self
::EXT_LINK_URL_CLASS
;
5298 $addr = self
::EXT_LINK_ADDR
;
5299 $prots = $this->mUrlProtocols
;
5300 if ( $value === '' ) {
5301 $paramName = 'no-link';
5304 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5305 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5306 $paramName = 'link-url';
5307 $this->mOutput
->addExternalLink( $value );
5308 if ( $this->mOptions
->getExternalLinkTarget() ) {
5309 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5314 $linkTitle = Title
::newFromText( $value );
5316 $paramName = 'link-title';
5317 $value = $linkTitle;
5318 $this->mOutput
->addLink( $linkTitle );
5326 // use first appearing option, discard others.
5327 $validated = !$seenformat;
5331 # Most other things appear to be empty or numeric...
5332 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5337 $params[$type][$paramName] = $value;
5341 if ( !$validated ) {
5346 # Process alignment parameters
5347 if ( $params['horizAlign'] ) {
5348 $params['frame']['align'] = key( $params['horizAlign'] );
5350 if ( $params['vertAlign'] ) {
5351 $params['frame']['valign'] = key( $params['vertAlign'] );
5354 $params['frame']['caption'] = $caption;
5356 # Will the image be presented in a frame, with the caption below?
5357 $imageIsFramed = isset( $params['frame']['frame'] )
5358 ||
isset( $params['frame']['framed'] )
5359 ||
isset( $params['frame']['thumbnail'] )
5360 ||
isset( $params['frame']['manualthumb'] );
5362 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5363 # came to also set the caption, ordinary text after the image -- which
5364 # makes no sense, because that just repeats the text multiple times in
5365 # screen readers. It *also* came to set the title attribute.
5366 # Now that we have an alt attribute, we should not set the alt text to
5367 # equal the caption: that's worse than useless, it just repeats the
5368 # text. This is the framed/thumbnail case. If there's no caption, we
5369 # use the unnamed parameter for alt text as well, just for the time be-
5370 # ing, if the unnamed param is set and the alt param is not.
5371 # For the future, we need to figure out if we want to tweak this more,
5372 # e.g., introducing a title= parameter for the title; ignoring the un-
5373 # named parameter entirely for images without a caption; adding an ex-
5374 # plicit caption= parameter and preserving the old magic unnamed para-
5376 if ( $imageIsFramed ) { # Framed image
5377 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5378 # No caption or alt text, add the filename as the alt text so
5379 # that screen readers at least get some description of the image
5380 $params['frame']['alt'] = $title->getText();
5382 # Do not set $params['frame']['title'] because tooltips don't make sense
5384 } else { # Inline image
5385 if ( !isset( $params['frame']['alt'] ) ) {
5386 # No alt text, use the "caption" for the alt text
5387 if ( $caption !== '' ) {
5388 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5390 # No caption, fall back to using the filename for the
5392 $params['frame']['alt'] = $title->getText();
5395 # Use the "caption" for the tooltip text
5396 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5399 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5401 # Linker does the rest
5402 $time = $options['time'] ??
false;
5403 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5404 $time, $descQuery, $this->mOptions
->getThumbSize() );
5406 # Give the handler a chance to modify the parser object
5408 $handler->parserTransformHook( $this, $file );
5415 * @param string $caption
5416 * @param LinkHolderArray|bool $holders
5417 * @return mixed|string
5419 protected function stripAltText( $caption, $holders ) {
5420 # Strip bad stuff out of the title (tooltip). We can't just use
5421 # replaceLinkHoldersText() here, because if this function is called
5422 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5424 $tooltip = $holders->replaceText( $caption );
5426 $tooltip = $this->replaceLinkHoldersText( $caption );
5429 # make sure there are no placeholders in thumbnail attributes
5430 # that are later expanded to html- so expand them now and
5432 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5433 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5439 * Set a flag in the output object indicating that the content is dynamic and
5440 * shouldn't be cached.
5441 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5443 public function disableCache() {
5444 wfDebug( "Parser output marked as uncacheable.\n" );
5445 if ( !$this->mOutput
) {
5446 throw new MWException( __METHOD__
.
5447 " can only be called when actually parsing something" );
5449 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5453 * Callback from the Sanitizer for expanding items found in HTML attribute
5454 * values, so they can be safely tested and escaped.
5456 * @param string &$text
5457 * @param bool|PPFrame $frame
5460 public function attributeStripCallback( &$text, $frame = false ) {
5461 $text = $this->replaceVariables( $text, $frame );
5462 $text = $this->mStripState
->unstripBoth( $text );
5471 public function getTags() {
5473 array_keys( $this->mTransparentTagHooks
),
5474 array_keys( $this->mTagHooks
),
5475 array_keys( $this->mFunctionTagHooks
)
5480 * Replace transparent tags in $text with the values given by the callbacks.
5482 * Transparent tag hooks are like regular XML-style tag hooks, except they
5483 * operate late in the transformation sequence, on HTML instead of wikitext.
5485 * @param string $text
5489 public function replaceTransparentTags( $text ) {
5491 $elements = array_keys( $this->mTransparentTagHooks
);
5492 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5495 foreach ( $matches as $marker => $data ) {
5496 list( $element, $content, $params, $tag ) = $data;
5497 $tagName = strtolower( $element );
5498 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5499 $output = call_user_func_array(
5500 $this->mTransparentTagHooks
[$tagName],
5501 [ $content, $params, $this ]
5506 $replacements[$marker] = $output;
5508 return strtr( $text, $replacements );
5512 * Break wikitext input into sections, and either pull or replace
5513 * some particular section's text.
5515 * External callers should use the getSection and replaceSection methods.
5517 * @param string $text Page wikitext
5518 * @param string|int $sectionId A section identifier string of the form:
5519 * "<flag1> - <flag2> - ... - <section number>"
5521 * Currently the only recognised flag is "T", which means the target section number
5522 * was derived during a template inclusion parse, in other words this is a template
5523 * section edit link. If no flags are given, it was an ordinary section edit link.
5524 * This flag is required to avoid a section numbering mismatch when a section is
5525 * enclosed by "<includeonly>" (T8563).
5527 * The section number 0 pulls the text before the first heading; other numbers will
5528 * pull the given section along with its lower-level subsections. If the section is
5529 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5531 * Section 0 is always considered to exist, even if it only contains the empty
5532 * string. If $text is the empty string and section 0 is replaced, $newText is
5535 * @param string $mode One of "get" or "replace"
5536 * @param string $newText Replacement text for section data.
5537 * @return string For "get", the extracted section text.
5538 * for "replace", the whole page with the section replaced.
5540 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5541 global $wgTitle; # not generally used but removes an ugly failure mode
5543 $magicScopeVariable = $this->lock();
5544 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5546 $frame = $this->getPreprocessor()->newFrame();
5548 # Process section extraction flags
5550 $sectionParts = explode( '-', $sectionId );
5551 $sectionIndex = array_pop( $sectionParts );
5552 foreach ( $sectionParts as $part ) {
5553 if ( $part === 'T' ) {
5554 $flags |
= self
::PTD_FOR_INCLUSION
;
5558 # Check for empty input
5559 if ( strval( $text ) === '' ) {
5560 # Only sections 0 and T-0 exist in an empty document
5561 if ( $sectionIndex == 0 ) {
5562 if ( $mode === 'get' ) {
5568 if ( $mode === 'get' ) {
5576 # Preprocess the text
5577 $root = $this->preprocessToDom( $text, $flags );
5579 # <h> nodes indicate section breaks
5580 # They can only occur at the top level, so we can find them by iterating the root's children
5581 $node = $root->getFirstChild();
5583 # Find the target section
5584 if ( $sectionIndex == 0 ) {
5585 # Section zero doesn't nest, level=big
5586 $targetLevel = 1000;
5589 if ( $node->getName() === 'h' ) {
5590 $bits = $node->splitHeading();
5591 if ( $bits['i'] == $sectionIndex ) {
5592 $targetLevel = $bits['level'];
5596 if ( $mode === 'replace' ) {
5597 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5599 $node = $node->getNextSibling();
5605 if ( $mode === 'get' ) {
5612 # Find the end of the section, including nested sections
5614 if ( $node->getName() === 'h' ) {
5615 $bits = $node->splitHeading();
5616 $curLevel = $bits['level'];
5617 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5621 if ( $mode === 'get' ) {
5622 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5624 $node = $node->getNextSibling();
5627 # Write out the remainder (in replace mode only)
5628 if ( $mode === 'replace' ) {
5629 # Output the replacement text
5630 # Add two newlines on -- trailing whitespace in $newText is conventionally
5631 # stripped by the editor, so we need both newlines to restore the paragraph gap
5632 # Only add trailing whitespace if there is newText
5633 if ( $newText != "" ) {
5634 $outText .= $newText . "\n\n";
5638 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5639 $node = $node->getNextSibling();
5643 if ( is_string( $outText ) ) {
5644 # Re-insert stripped tags
5645 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5652 * This function returns the text of a section, specified by a number ($section).
5653 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5654 * the first section before any such heading (section 0).
5656 * If a section contains subsections, these are also returned.
5658 * @param string $text Text to look in
5659 * @param string|int $sectionId Section identifier as a number or string
5660 * (e.g. 0, 1 or 'T-1').
5661 * @param string $defaultText Default to return if section is not found
5663 * @return string Text of the requested section
5665 public function getSection( $text, $sectionId, $defaultText = '' ) {
5666 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5670 * This function returns $oldtext after the content of the section
5671 * specified by $section has been replaced with $text. If the target
5672 * section does not exist, $oldtext is returned unchanged.
5674 * @param string $oldText Former text of the article
5675 * @param string|int $sectionId Section identifier as a number or string
5676 * (e.g. 0, 1 or 'T-1').
5677 * @param string $newText Replacing text
5679 * @return string Modified text
5681 public function replaceSection( $oldText, $sectionId, $newText ) {
5682 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5686 * Get the ID of the revision we are parsing
5690 public function getRevisionId() {
5691 return $this->mRevisionId
;
5695 * Get the revision object for $this->mRevisionId
5697 * @return Revision|null Either a Revision object or null
5698 * @since 1.23 (public since 1.23)
5700 public function getRevisionObject() {
5701 if ( !is_null( $this->mRevisionObject
) ) {
5702 return $this->mRevisionObject
;
5704 if ( is_null( $this->mRevisionId
) ) {
5708 $rev = call_user_func(
5709 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5712 # If the parse is for a new revision, then the callback should have
5713 # already been set to force the object and should match mRevisionId.
5714 # If not, try to fetch by mRevisionId for sanity.
5715 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5716 $rev = Revision
::newFromId( $this->mRevisionId
);
5719 $this->mRevisionObject
= $rev;
5721 return $this->mRevisionObject
;
5725 * Get the timestamp associated with the current revision, adjusted for
5726 * the default server-local timestamp
5729 public function getRevisionTimestamp() {
5730 if ( is_null( $this->mRevisionTimestamp
) ) {
5731 $revObject = $this->getRevisionObject();
5732 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5734 # The cryptic '' timezone parameter tells to use the site-default
5735 # timezone offset instead of the user settings.
5736 # Since this value will be saved into the parser cache, served
5737 # to other users, and potentially even used inside links and such,
5738 # it needs to be consistent for all visitors.
5739 $this->mRevisionTimestamp
= $this->getContentLanguage()->userAdjust( $timestamp, '' );
5742 return $this->mRevisionTimestamp
;
5746 * Get the name of the user that edited the last revision
5748 * @return string User name
5750 public function getRevisionUser() {
5751 if ( is_null( $this->mRevisionUser
) ) {
5752 $revObject = $this->getRevisionObject();
5754 # if this template is subst: the revision id will be blank,
5755 # so just use the current user's name
5757 $this->mRevisionUser
= $revObject->getUserText();
5758 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5759 $this->mRevisionUser
= $this->getUser()->getName();
5762 return $this->mRevisionUser
;
5766 * Get the size of the revision
5768 * @return int|null Revision size
5770 public function getRevisionSize() {
5771 if ( is_null( $this->mRevisionSize
) ) {
5772 $revObject = $this->getRevisionObject();
5774 # if this variable is subst: the revision id will be blank,
5775 # so just use the parser input size, because the own substituation
5776 # will change the size.
5778 $this->mRevisionSize
= $revObject->getSize();
5780 $this->mRevisionSize
= $this->mInputSize
;
5783 return $this->mRevisionSize
;
5787 * Mutator for $mDefaultSort
5789 * @param string $sort New value
5791 public function setDefaultSort( $sort ) {
5792 $this->mDefaultSort
= $sort;
5793 $this->mOutput
->setProperty( 'defaultsort', $sort );
5797 * Accessor for $mDefaultSort
5798 * Will use the empty string if none is set.
5800 * This value is treated as a prefix, so the
5801 * empty string is equivalent to sorting by
5806 public function getDefaultSort() {
5807 if ( $this->mDefaultSort
!== false ) {
5808 return $this->mDefaultSort
;
5815 * Accessor for $mDefaultSort
5816 * Unlike getDefaultSort(), will return false if none is set
5818 * @return string|bool
5820 public function getCustomDefaultSort() {
5821 return $this->mDefaultSort
;
5824 private static function getSectionNameFromStrippedText( $text ) {
5825 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5826 $text = Sanitizer
::decodeCharReferences( $text );
5827 $text = self
::normalizeSectionName( $text );
5831 private static function makeAnchor( $sectionName ) {
5832 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5835 private static function makeLegacyAnchor( $sectionName ) {
5836 global $wgFragmentMode;
5837 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5838 // ForAttribute() and ForLink() are the same for legacy encoding
5839 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5841 $id = Sanitizer
::escapeIdForLink( $sectionName );
5848 * Try to guess the section anchor name based on a wikitext fragment
5849 * presumably extracted from a heading, for example "Header" from
5852 * @param string $text
5853 * @return string Anchor (starting with '#')
5855 public function guessSectionNameFromWikiText( $text ) {
5856 # Strip out wikitext links(they break the anchor)
5857 $text = $this->stripSectionName( $text );
5858 $sectionName = self
::getSectionNameFromStrippedText( $text );
5859 return self
::makeAnchor( $sectionName );
5863 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5864 * instead, if possible. For use in redirects, since various versions
5865 * of Microsoft browsers interpret Location: headers as something other
5866 * than UTF-8, resulting in breakage.
5868 * @param string $text The section name
5869 * @return string Anchor (starting with '#')
5871 public function guessLegacySectionNameFromWikiText( $text ) {
5872 # Strip out wikitext links(they break the anchor)
5873 $text = $this->stripSectionName( $text );
5874 $sectionName = self
::getSectionNameFromStrippedText( $text );
5875 return self
::makeLegacyAnchor( $sectionName );
5879 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5880 * @param string $text Section name (plain text)
5881 * @return string Anchor (starting with '#')
5883 public static function guessSectionNameFromStrippedText( $text ) {
5884 $sectionName = self
::getSectionNameFromStrippedText( $text );
5885 return self
::makeAnchor( $sectionName );
5889 * Apply the same normalization as code making links to this section would
5891 * @param string $text
5894 private static function normalizeSectionName( $text ) {
5895 # T90902: ensure the same normalization is applied for IDs as to links
5896 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5899 $parts = $titleParser->splitTitleString( "#$text" );
5900 } catch ( MalformedTitleException
$ex ) {
5903 return $parts['fragment'];
5907 * Strips a text string of wikitext for use in a section anchor
5909 * Accepts a text string and then removes all wikitext from the
5910 * string and leaves only the resultant text (i.e. the result of
5911 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5912 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5913 * to create valid section anchors by mimicing the output of the
5914 * parser when headings are parsed.
5916 * @param string $text Text string to be stripped of wikitext
5917 * for use in a Section anchor
5918 * @return string Filtered text string
5920 public function stripSectionName( $text ) {
5921 # Strip internal link markup
5922 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5923 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5925 # Strip external link markup
5926 # @todo FIXME: Not tolerant to blank link text
5927 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5928 # on how many empty links there are on the page - need to figure that out.
5929 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5931 # Parse wikitext quotes (italics & bold)
5932 $text = $this->doQuotes( $text );
5935 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5940 * strip/replaceVariables/unstrip for preprocessor regression testing
5942 * @param string $text
5943 * @param Title $title
5944 * @param ParserOptions $options
5945 * @param int $outputType
5949 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5950 $outputType = self
::OT_HTML
5952 $magicScopeVariable = $this->lock();
5953 $this->startParse( $title, $options, $outputType, true );
5955 $text = $this->replaceVariables( $text );
5956 $text = $this->mStripState
->unstripBoth( $text );
5957 $text = Sanitizer
::removeHTMLtags( $text );
5962 * @param string $text
5963 * @param Title $title
5964 * @param ParserOptions $options
5967 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5968 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5972 * @param string $text
5973 * @param Title $title
5974 * @param ParserOptions $options
5977 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5978 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5982 * Call a callback function on all regions of the given text that are not
5983 * inside strip markers, and replace those regions with the return value
5984 * of the callback. For example, with input:
5988 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5989 * two strings will be replaced with the value returned by the callback in
5993 * @param callable $callback
5997 public function markerSkipCallback( $s, $callback ) {
6000 while ( $i < strlen( $s ) ) {
6001 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6002 if ( $markerStart === false ) {
6003 $out .= call_user_func( $callback, substr( $s, $i ) );
6006 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6007 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6008 if ( $markerEnd === false ) {
6009 $out .= substr( $s, $markerStart );
6012 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6013 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6022 * Remove any strip markers found in the given text.
6024 * @param string $text
6027 public function killMarkers( $text ) {
6028 return $this->mStripState
->killMarkers( $text );
6032 * Save the parser state required to convert the given half-parsed text to
6033 * HTML. "Half-parsed" in this context means the output of
6034 * recursiveTagParse() or internalParse(). This output has strip markers
6035 * from replaceVariables (extensionSubstitution() etc.), and link
6036 * placeholders from replaceLinkHolders().
6038 * Returns an array which can be serialized and stored persistently. This
6039 * array can later be loaded into another parser instance with
6040 * unserializeHalfParsedText(). The text can then be safely incorporated into
6041 * the return value of a parser hook.
6043 * @deprecated since 1.31
6044 * @param string $text
6048 public function serializeHalfParsedText( $text ) {
6049 wfDeprecated( __METHOD__
, '1.31' );
6052 'version' => self
::HALF_PARSED_VERSION
,
6053 'stripState' => $this->mStripState
->getSubState( $text ),
6054 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6060 * Load the parser state given in the $data array, which is assumed to
6061 * have been generated by serializeHalfParsedText(). The text contents is
6062 * extracted from the array, and its markers are transformed into markers
6063 * appropriate for the current Parser instance. This transformed text is
6064 * returned, and can be safely included in the return value of a parser
6067 * If the $data array has been stored persistently, the caller should first
6068 * check whether it is still valid, by calling isValidHalfParsedText().
6070 * @deprecated since 1.31
6071 * @param array $data Serialized data
6072 * @throws MWException
6075 public function unserializeHalfParsedText( $data ) {
6076 wfDeprecated( __METHOD__
, '1.31' );
6077 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6078 throw new MWException( __METHOD__
. ': invalid version' );
6081 # First, extract the strip state.
6082 $texts = [ $data['text'] ];
6083 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6085 # Now renumber links
6086 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6088 # Should be good to go.
6093 * Returns true if the given array, presumed to be generated by
6094 * serializeHalfParsedText(), is compatible with the current version of the
6097 * @deprecated since 1.31
6098 * @param array $data
6102 public function isValidHalfParsedText( $data ) {
6103 wfDeprecated( __METHOD__
, '1.31' );
6104 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6108 * Parsed a width param of imagelink like 300px or 200x300px
6110 * @param string $value
6111 * @param bool $parseHeight
6116 public static function parseWidthParam( $value, $parseHeight = true ) {
6117 $parsedWidthParam = [];
6118 if ( $value === '' ) {
6119 return $parsedWidthParam;
6122 # (T15500) In both cases (width/height and width only),
6123 # permit trailing "px" for backward compatibility.
6124 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6125 $width = intval( $m[1] );
6126 $height = intval( $m[2] );
6127 $parsedWidthParam['width'] = $width;
6128 $parsedWidthParam['height'] = $height;
6129 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6130 $width = intval( $value );
6131 $parsedWidthParam['width'] = $width;
6133 return $parsedWidthParam;
6137 * Lock the current instance of the parser.
6139 * This is meant to stop someone from calling the parser
6140 * recursively and messing up all the strip state.
6142 * @throws MWException If parser is in a parse
6143 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6145 protected function lock() {
6146 if ( $this->mInParse
) {
6147 throw new MWException( "Parser state cleared while parsing. "
6148 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6151 // Save the backtrace when locking, so that if some code tries locking again,
6152 // we can print the lock owner's backtrace for easier debugging
6154 $this->mInParse
= $e->getTraceAsString();
6156 $recursiveCheck = new ScopedCallback( function () {
6157 $this->mInParse
= false;
6160 return $recursiveCheck;
6164 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6166 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6167 * or if there is more than one <p/> tag in the input HTML.
6169 * @param string $html
6173 public static function stripOuterParagraph( $html ) {
6175 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6176 if ( strpos( $m[1], '</p>' ) === false ) {
6185 * Return this parser if it is not doing anything, otherwise
6186 * get a fresh parser. You can use this method by doing
6187 * $myParser = $wgParser->getFreshParser(), or more simply
6188 * $wgParser->getFreshParser()->parse( ... );
6189 * if you're unsure if $wgParser is safe to use.
6192 * @return Parser A parser object that is not parsing anything
6194 public function getFreshParser() {
6195 global $wgParserConf;
6196 if ( $this->mInParse
) {
6197 return new $wgParserConf['class']( $wgParserConf );
6204 * Set's up the PHP implementation of OOUI for use in this request
6205 * and instructs OutputPage to enable OOUI for itself.
6209 public function enableOOUI() {
6210 OutputPage
::setupOOUI();
6211 $this->mOutput
->setEnableOOUI( true );