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
57 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
60 * $wgNamespacesWithSubpages
62 * @par Settings only within ParserOptions:
63 * $wgAllowExternalImages
64 * $wgAllowSpecialInclusion
72 * Update this version number when the ParserOutput format
73 * changes in an incompatible way, so the parser cache
74 * can automatically discard old data.
76 const VERSION
= '1.6.4';
79 * Update this version number when the output of serialiseHalfParsedText()
80 * changes in an incompatible way
82 const HALF_PARSED_VERSION
= 2;
84 # Flags for Parser::setFunctionHook
85 const SFH_NO_HASH
= 1;
86 const SFH_OBJECT_ARGS
= 2;
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
92 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
93 # uses to replace invalid HTML characters.
94 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
95 # Simplified expression to match an IPv4 or IPv6 address, or
96 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
97 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
98 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
99 // phpcs:ignore Generic.Files.LineLength
100 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
101 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
103 # Regular expression for a non-newline space
104 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
118 * @var string Prefix and suffix for temporary replacement strings
119 * for the multipass parser.
121 * \x7f should never appear in input as it's disallowed in XML.
122 * Using it at the front also gives us a little extra robustness
123 * since it shouldn't match when butted up against identifier-like
126 * Must not consist of all title characters, or else it will change
127 * the behavior of <nowiki> in a link.
129 * Must have a character that needs escaping in attributes, otherwise
130 * someone could put a strip marker in an attribute, to get around
131 * escaping quote marks, and break out of the attribute. Thus we add
134 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
135 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
137 # Markers used for wrapping the table of contents
138 const TOC_START
= '<mw:toc>';
139 const TOC_END
= '</mw:toc>';
141 /** @var int Assume that no output will later be saved this many seconds after parsing */
145 public $mTagHooks = [];
146 public $mTransparentTagHooks = [];
147 public $mFunctionHooks = [];
148 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
149 public $mFunctionTagHooks = [];
150 public $mStripList = [];
151 public $mDefaultStripList = [];
152 public $mVarCache = [];
153 public $mImageParams = [];
154 public $mImageParamsMagicArray = [];
155 public $mMarkerIndex = 0;
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 if ( $this->mFirstCall
) {
358 $this->firstCallInit();
360 $this->mOutput
= new ParserOutput
;
361 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
362 $this->mAutonumber
= 0;
363 $this->mIncludeCount
= [];
364 $this->mLinkHolders
= new LinkHolderArray( $this );
366 $this->mRevisionObject
= $this->mRevisionTimestamp
=
367 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
368 $this->mVarCache
= [];
370 $this->mLangLinkLanguages
= [];
371 $this->currentRevisionCache
= null;
373 $this->mStripState
= new StripState( $this );
375 # Clear these on every parse, T6549
376 $this->mTplRedirCache
= $this->mTplDomCache
= [];
378 $this->mShowToc
= true;
379 $this->mForceTocPosition
= false;
380 $this->mIncludeSizes
= [
384 $this->mPPNodeCount
= 0;
385 $this->mGeneratedPPNodeCount
= 0;
386 $this->mHighestExpansionDepth
= 0;
387 $this->mDefaultSort
= false;
388 $this->mHeadings
= [];
389 $this->mDoubleUnderscores
= [];
390 $this->mExpensiveFunctionCount
= 0;
393 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
394 $this->mPreprocessor
= null;
397 $this->mProfiler
= new SectionProfiler();
399 // Avoid PHP 7.1 warning from passing $this by reference
401 Hooks
::run( 'ParserClearState', [ &$parser ] );
405 * Convert wikitext to HTML
406 * Do not call this function recursively.
408 * @param string $text Text we want to parse
409 * @param Title $title
410 * @param ParserOptions $options
411 * @param bool $linestart
412 * @param bool $clearState
413 * @param int|null $revid Number to pass in {{REVISIONID}}
414 * @return ParserOutput A ParserOutput
416 public function parse(
417 $text, Title
$title, ParserOptions
$options,
418 $linestart = true, $clearState = true, $revid = null
421 // We use U+007F DELETE to construct strip markers, so we have to make
422 // sure that this character does not occur in the input text.
423 $text = strtr( $text, "\x7f", "?" );
424 $magicScopeVariable = $this->lock();
426 // Strip U+0000 NULL (T159174)
427 $text = str_replace( "\000", '', $text );
429 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
431 $this->currentRevisionCache
= null;
432 $this->mInputSize
= strlen( $text );
433 if ( $this->mOptions
->getEnableLimitReport() ) {
434 $this->mOutput
->resetParseStartTime();
437 $oldRevisionId = $this->mRevisionId
;
438 $oldRevisionObject = $this->mRevisionObject
;
439 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
440 $oldRevisionUser = $this->mRevisionUser
;
441 $oldRevisionSize = $this->mRevisionSize
;
442 if ( $revid !== null ) {
443 $this->mRevisionId
= $revid;
444 $this->mRevisionObject
= null;
445 $this->mRevisionTimestamp
= null;
446 $this->mRevisionUser
= null;
447 $this->mRevisionSize
= null;
450 // Avoid PHP 7.1 warning from passing $this by reference
452 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
454 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
455 $text = $this->internalParse( $text );
456 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
458 $text = $this->internalParseHalfParsed( $text, true, $linestart );
461 * A converted title will be provided in the output object if title and
462 * content conversion are enabled, the article text does not contain
463 * a conversion-suppressing double-underscore tag, and no
464 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
465 * automatic link conversion.
467 if ( !( $options->getDisableTitleConversion()
468 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
469 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
470 ||
$this->mOutput
->getDisplayTitle() !== false )
472 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
473 if ( $convruletitle ) {
474 $this->mOutput
->setTitleText( $convruletitle );
476 $titleText = $this->getTargetLanguage()->convertTitle( $title );
477 $this->mOutput
->setTitleText( $titleText );
481 # Compute runtime adaptive expiry if set
482 $this->mOutput
->finalizeAdaptiveCacheExpiry();
484 # Warn if too many heavyweight parser functions were used
485 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
486 $this->limitationWarn( 'expensive-parserfunction',
487 $this->mExpensiveFunctionCount
,
488 $this->mOptions
->getExpensiveParserFunctionLimit()
492 # Information on limits, for the benefit of users who try to skirt them
493 if ( $this->mOptions
->getEnableLimitReport() ) {
494 $text .= $this->makeLimitReport();
497 # Wrap non-interface parser output in a <div> so it can be targeted
499 $class = $this->mOptions
->getWrapOutputClass();
500 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
501 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
504 $this->mOutput
->setText( $text );
506 $this->mRevisionId
= $oldRevisionId;
507 $this->mRevisionObject
= $oldRevisionObject;
508 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
509 $this->mRevisionUser
= $oldRevisionUser;
510 $this->mRevisionSize
= $oldRevisionSize;
511 $this->mInputSize
= false;
512 $this->currentRevisionCache
= null;
514 return $this->mOutput
;
518 * Set the limit report data in the current ParserOutput, and return the
519 * limit report HTML comment.
523 protected function makeLimitReport() {
524 global $wgShowHostnames;
526 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
528 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
529 if ( $cpuTime !== null ) {
530 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
531 sprintf( "%.3f", $cpuTime )
535 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
536 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
537 sprintf( "%.3f", $wallTime )
540 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
541 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
543 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
544 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
546 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
547 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
549 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
550 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
552 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
553 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
555 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
556 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
559 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
560 $this->mOutput
->setLimitReportData( $key, $value );
563 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
565 $limitReport = "NewPP limit report\n";
566 if ( $wgShowHostnames ) {
567 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
569 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
570 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
571 $limitReport .= 'Dynamic content: ' .
572 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
575 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
576 if ( Hooks
::run( 'ParserLimitReportFormat',
577 [ $key, &$value, &$limitReport, false, false ]
579 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
580 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
581 ->inLanguage( 'en' )->useDatabase( false );
582 if ( !$valueMsg->exists() ) {
583 $valueMsg = new RawMessage( '$1' );
585 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
586 $valueMsg->params( $value );
587 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
591 // Since we're not really outputting HTML, decode the entities and
592 // then re-encode the things that need hiding inside HTML comments.
593 $limitReport = htmlspecialchars_decode( $limitReport );
594 // Run deprecated hook
595 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
597 // Sanitize for comment. Note '‐' in the replacement is U+2010,
598 // which looks much like the problematic '-'.
599 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
600 $text = "\n<!-- \n$limitReport-->\n";
602 // Add on template profiling data in human/machine readable way
603 $dataByFunc = $this->mProfiler
->getFunctionStats();
604 uasort( $dataByFunc, function ( $a, $b ) {
605 return $b['real'] <=> $a['real']; // descending order
608 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
609 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
610 $item['%real'], $item['real'], $item['calls'],
611 htmlspecialchars( $item['name'] ) );
613 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
614 $text .= implode( "\n", $profileReport ) . "\n-->\n";
616 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
618 // Add other cache related metadata
619 if ( $wgShowHostnames ) {
620 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
622 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
623 $this->mOutput
->getCacheTime() );
624 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
625 $this->mOutput
->getCacheExpiry() );
626 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
627 $this->mOutput
->hasDynamicContent() );
629 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
630 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
631 $this->mTitle
->getPrefixedDBkey() );
637 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
638 * can be called from an extension tag hook.
640 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
641 * instead, which means that lists and links have not been fully parsed yet,
642 * and strip markers are still present.
644 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
646 * Use this function if you're a parser tag hook and you want to parse
647 * wikitext before or after applying additional transformations, and you
648 * intend to *return the result as hook output*, which will cause it to go
649 * through the rest of parsing process automatically.
651 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
652 * $text are not expanded
654 * @param string $text Text extension wants to have parsed
655 * @param bool|PPFrame $frame The frame to use for expanding any template variables
656 * @return string UNSAFE half-parsed HTML
658 public function recursiveTagParse( $text, $frame = false ) {
659 // Avoid PHP 7.1 warning from passing $this by reference
661 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
662 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
663 $text = $this->internalParse( $text, false, $frame );
668 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
669 * point can be called from an extension tag hook.
671 * The output of this function is fully-parsed HTML that is safe for output.
672 * If you're a parser tag hook, you might want to use recursiveTagParse()
675 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
676 * $text are not expanded
680 * @param string $text Text extension wants to have parsed
681 * @param bool|PPFrame $frame The frame to use for expanding any template variables
682 * @return string Fully parsed HTML
684 public function recursiveTagParseFully( $text, $frame = false ) {
685 $text = $this->recursiveTagParse( $text, $frame );
686 $text = $this->internalParseHalfParsed( $text, false );
691 * Expand templates and variables in the text, producing valid, static wikitext.
692 * Also removes comments.
693 * Do not call this function recursively.
694 * @param string $text
695 * @param Title|null $title
696 * @param ParserOptions $options
697 * @param int|null $revid
698 * @param bool|PPFrame $frame
699 * @return mixed|string
701 public function preprocess( $text, Title
$title = null,
702 ParserOptions
$options, $revid = null, $frame = false
704 $magicScopeVariable = $this->lock();
705 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
706 if ( $revid !== null ) {
707 $this->mRevisionId
= $revid;
709 // Avoid PHP 7.1 warning from passing $this by reference
711 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
712 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
713 $text = $this->replaceVariables( $text, $frame );
714 $text = $this->mStripState
->unstripBoth( $text );
719 * Recursive parser entry point that can be called from an extension tag
722 * @param string $text Text to be expanded
723 * @param bool|PPFrame $frame The frame to use for expanding any template variables
727 public function recursivePreprocess( $text, $frame = false ) {
728 $text = $this->replaceVariables( $text, $frame );
729 $text = $this->mStripState
->unstripBoth( $text );
734 * Process the wikitext for the "?preload=" feature. (T7210)
736 * "<noinclude>", "<includeonly>" etc. are parsed as for template
737 * transclusion, comments, templates, arguments, tags hooks and parser
738 * functions are untouched.
740 * @param string $text
741 * @param Title $title
742 * @param ParserOptions $options
743 * @param array $params
746 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
747 $msg = new RawMessage( $text );
748 $text = $msg->params( $params )->plain();
750 # Parser (re)initialisation
751 $magicScopeVariable = $this->lock();
752 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
754 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
755 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
756 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
757 $text = $this->mStripState
->unstripBoth( $text );
762 * Set the current user.
763 * Should only be used when doing pre-save transform.
765 * @param User|null $user User object or null (to reset)
767 public function setUser( $user ) {
768 $this->mUser
= $user;
772 * Set the context title
776 public function setTitle( $t ) {
778 $t = Title
::newFromText( 'NO TITLE' );
781 if ( $t->hasFragment() ) {
782 # Strip the fragment to avoid various odd effects
783 $this->mTitle
= $t->createFragmentTarget( '' );
790 * Accessor for the Title object
794 public function getTitle() {
795 return $this->mTitle
;
799 * Accessor/mutator for the Title object
801 * @param Title|null $x Title object or null to just get the current one
804 public function Title( $x = null ) {
805 return wfSetVar( $this->mTitle
, $x );
809 * Set the output type
811 * @param int $ot New value
813 public function setOutputType( $ot ) {
814 $this->mOutputType
= $ot;
817 'html' => $ot == self
::OT_HTML
,
818 'wiki' => $ot == self
::OT_WIKI
,
819 'pre' => $ot == self
::OT_PREPROCESS
,
820 'plain' => $ot == self
::OT_PLAIN
,
825 * Accessor/mutator for the output type
827 * @param int|null $x New value or null to just get the current one
830 public function OutputType( $x = null ) {
831 return wfSetVar( $this->mOutputType
, $x );
835 * Get the ParserOutput object
837 * @return ParserOutput
839 public function getOutput() {
840 return $this->mOutput
;
844 * Get the ParserOptions object
846 * @return ParserOptions
848 public function getOptions() {
849 return $this->mOptions
;
853 * Accessor/mutator for the ParserOptions object
855 * @param ParserOptions|null $x New value or null to just get the current one
856 * @return ParserOptions Current ParserOptions object
858 public function Options( $x = null ) {
859 return wfSetVar( $this->mOptions
, $x );
865 public function nextLinkID() {
866 return $this->mLinkID++
;
872 public function setLinkID( $id ) {
873 $this->mLinkID
= $id;
877 * Get a language object for use in parser functions such as {{FORMATNUM:}}
880 public function getFunctionLang() {
881 return $this->getTargetLanguage();
885 * Get the target language for the content being parsed. This is usually the
886 * language that the content is in.
890 * @throws MWException
893 public function getTargetLanguage() {
894 $target = $this->mOptions
->getTargetLanguage();
896 if ( $target !== null ) {
898 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
899 return $this->mOptions
->getUserLangObj();
900 } elseif ( is_null( $this->mTitle
) ) {
901 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
904 return $this->mTitle
->getPageLanguage();
908 * Get the language object for language conversion
909 * @deprecated since 1.32, just use getTargetLanguage()
910 * @return Language|null
912 public function getConverterLanguage() {
913 return $this->getTargetLanguage();
917 * Get a User object either from $this->mUser, if set, or from the
918 * ParserOptions object otherwise
922 public function getUser() {
923 if ( !is_null( $this->mUser
) ) {
926 return $this->mOptions
->getUser();
930 * Get a preprocessor object
932 * @return Preprocessor
934 public function getPreprocessor() {
935 if ( !isset( $this->mPreprocessor
) ) {
936 $class = $this->mPreprocessorClass
;
937 $this->mPreprocessor
= new $class( $this );
939 return $this->mPreprocessor
;
943 * Get a LinkRenderer instance to make links with
946 * @return LinkRenderer
948 public function getLinkRenderer() {
949 if ( !$this->mLinkRenderer
) {
950 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
951 ->getLinkRendererFactory()->create();
952 $this->mLinkRenderer
->setStubThreshold(
953 $this->getOptions()->getStubThreshold()
957 return $this->mLinkRenderer
;
961 * Replaces all occurrences of HTML-style comments and the given tags
962 * in the text with a random marker and returns the next text. The output
963 * parameter $matches will be an associative array filled with data in
970 * [ 'param' => 'x' ],
971 * '<element param="x">tag content</element>' ]
974 * @param array $elements List of element names. Comments are always extracted.
975 * @param string $text Source text string.
976 * @param array &$matches Out parameter, Array: extracted tags
977 * @return string Stripped text
979 public static function extractTagsAndParams( $elements, $text, &$matches ) {
984 $taglist = implode( '|', $elements );
985 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
987 while ( $text != '' ) {
988 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
990 if ( count( $p ) < 5 ) {
993 if ( count( $p ) > 5 ) {
1002 $attributes = $p[2];
1007 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1008 $stripped .= $marker;
1010 if ( $close === '/>' ) {
1011 # Empty element tag, <tag />
1016 if ( $element === '!--' ) {
1019 $end = "/(<\\/$element\\s*>)/i";
1021 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1023 if ( count( $q ) < 3 ) {
1024 # No end tag -- let it run out to the end of the text.
1033 $matches[$marker] = [ $element,
1035 Sanitizer
::decodeTagAttributes( $attributes ),
1036 "<$element$attributes$close$content$tail" ];
1042 * Get a list of strippable XML-like elements
1046 public function getStripList() {
1047 return $this->mStripList
;
1051 * Add an item to the strip state
1052 * Returns the unique tag which must be inserted into the stripped text
1053 * The tag will be replaced with the original text in unstrip()
1055 * @param string $text
1059 public function insertStripItem( $text ) {
1060 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1061 $this->mMarkerIndex++
;
1062 $this->mStripState
->addGeneral( $marker, $text );
1067 * parse the wiki syntax used to render tables
1070 * @param string $text
1073 public function doTableStuff( $text ) {
1074 $lines = StringUtils
::explode( "\n", $text );
1076 $td_history = []; # Is currently a td tag open?
1077 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1078 $tr_history = []; # Is currently a tr tag open?
1079 $tr_attributes = []; # history of tr attributes
1080 $has_opened_tr = []; # Did this table open a <tr> element?
1081 $indent_level = 0; # indent level of the table
1083 foreach ( $lines as $outLine ) {
1084 $line = trim( $outLine );
1086 if ( $line === '' ) { # empty line, go to next line
1087 $out .= $outLine . "\n";
1091 $first_character = $line[0];
1092 $first_two = substr( $line, 0, 2 );
1095 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1096 # First check if we are starting a new table
1097 $indent_level = strlen( $matches[1] );
1099 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1100 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1102 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1103 array_push( $td_history, false );
1104 array_push( $last_tag_history, '' );
1105 array_push( $tr_history, false );
1106 array_push( $tr_attributes, '' );
1107 array_push( $has_opened_tr, false );
1108 } elseif ( count( $td_history ) == 0 ) {
1109 # Don't do any of the following
1110 $out .= $outLine . "\n";
1112 } elseif ( $first_two === '|}' ) {
1113 # We are ending a table
1114 $line = '</table>' . substr( $line, 2 );
1115 $last_tag = array_pop( $last_tag_history );
1117 if ( !array_pop( $has_opened_tr ) ) {
1118 $line = "<tr><td></td></tr>{$line}";
1121 if ( array_pop( $tr_history ) ) {
1122 $line = "</tr>{$line}";
1125 if ( array_pop( $td_history ) ) {
1126 $line = "</{$last_tag}>{$line}";
1128 array_pop( $tr_attributes );
1129 if ( $indent_level > 0 ) {
1130 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1134 } elseif ( $first_two === '|-' ) {
1135 # Now we have a table row
1136 $line = preg_replace( '#^\|-+#', '', $line );
1138 # Whats after the tag is now only attributes
1139 $attributes = $this->mStripState
->unstripBoth( $line );
1140 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1141 array_pop( $tr_attributes );
1142 array_push( $tr_attributes, $attributes );
1145 $last_tag = array_pop( $last_tag_history );
1146 array_pop( $has_opened_tr );
1147 array_push( $has_opened_tr, true );
1149 if ( array_pop( $tr_history ) ) {
1153 if ( array_pop( $td_history ) ) {
1154 $line = "</{$last_tag}>{$line}";
1158 array_push( $tr_history, false );
1159 array_push( $td_history, false );
1160 array_push( $last_tag_history, '' );
1161 } elseif ( $first_character === '|'
1162 ||
$first_character === '!'
1163 ||
$first_two === '|+'
1165 # This might be cell elements, td, th or captions
1166 if ( $first_two === '|+' ) {
1167 $first_character = '+';
1168 $line = substr( $line, 2 );
1170 $line = substr( $line, 1 );
1173 // Implies both are valid for table headings.
1174 if ( $first_character === '!' ) {
1175 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1178 # Split up multiple cells on the same line.
1179 # FIXME : This can result in improper nesting of tags processed
1180 # by earlier parser steps.
1181 $cells = explode( '||', $line );
1185 # Loop through each table cell
1186 foreach ( $cells as $cell ) {
1188 if ( $first_character !== '+' ) {
1189 $tr_after = array_pop( $tr_attributes );
1190 if ( !array_pop( $tr_history ) ) {
1191 $previous = "<tr{$tr_after}>\n";
1193 array_push( $tr_history, true );
1194 array_push( $tr_attributes, '' );
1195 array_pop( $has_opened_tr );
1196 array_push( $has_opened_tr, true );
1199 $last_tag = array_pop( $last_tag_history );
1201 if ( array_pop( $td_history ) ) {
1202 $previous = "</{$last_tag}>\n{$previous}";
1205 if ( $first_character === '|' ) {
1207 } elseif ( $first_character === '!' ) {
1209 } elseif ( $first_character === '+' ) {
1210 $last_tag = 'caption';
1215 array_push( $last_tag_history, $last_tag );
1217 # A cell could contain both parameters and data
1218 $cell_data = explode( '|', $cell, 2 );
1220 # T2553: Note that a '|' inside an invalid link should not
1221 # be mistaken as delimiting cell parameters
1222 # Bug T153140: Neither should language converter markup.
1223 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1224 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1225 } elseif ( count( $cell_data ) == 1 ) {
1226 // Whitespace in cells is trimmed
1227 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1229 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1230 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1231 // Whitespace in cells is trimmed
1232 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1236 array_push( $td_history, true );
1239 $out .= $outLine . "\n";
1242 # Closing open td, tr && table
1243 while ( count( $td_history ) > 0 ) {
1244 if ( array_pop( $td_history ) ) {
1247 if ( array_pop( $tr_history ) ) {
1250 if ( !array_pop( $has_opened_tr ) ) {
1251 $out .= "<tr><td></td></tr>\n";
1254 $out .= "</table>\n";
1257 # Remove trailing line-ending (b/c)
1258 if ( substr( $out, -1 ) === "\n" ) {
1259 $out = substr( $out, 0, -1 );
1262 # special case: don't return empty table
1263 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1271 * Helper function for parse() that transforms wiki markup into half-parsed
1272 * HTML. Only called for $mOutputType == self::OT_HTML.
1276 * @param string $text The text to parse
1277 * @param bool $isMain Whether this is being called from the main parse() function
1278 * @param PPFrame|bool $frame A pre-processor frame
1282 public function internalParse( $text, $isMain = true, $frame = false ) {
1285 // Avoid PHP 7.1 warning from passing $this by reference
1288 # Hook to suspend the parser in this state
1289 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1293 # if $frame is provided, then use $frame for replacing any variables
1295 # use frame depth to infer how include/noinclude tags should be handled
1296 # depth=0 means this is the top-level document; otherwise it's an included document
1297 if ( !$frame->depth
) {
1300 $flag = self
::PTD_FOR_INCLUSION
;
1302 $dom = $this->preprocessToDom( $text, $flag );
1303 $text = $frame->expand( $dom );
1305 # if $frame is not provided, then use old-style replaceVariables
1306 $text = $this->replaceVariables( $text );
1309 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1310 $text = Sanitizer
::removeHTMLtags(
1312 [ $this, 'attributeStripCallback' ],
1314 array_keys( $this->mTransparentTagHooks
),
1316 [ $this, 'addTrackingCategory' ]
1318 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1320 # Tables need to come after variable replacement for things to work
1321 # properly; putting them before other transformations should keep
1322 # exciting things like link expansions from showing up in surprising
1324 $text = $this->doTableStuff( $text );
1326 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1328 $text = $this->doDoubleUnderscore( $text );
1330 $text = $this->doHeadings( $text );
1331 $text = $this->replaceInternalLinks( $text );
1332 $text = $this->doAllQuotes( $text );
1333 $text = $this->replaceExternalLinks( $text );
1335 # replaceInternalLinks may sometimes leave behind
1336 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1337 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1339 $text = $this->doMagicLinks( $text );
1340 $text = $this->formatHeadings( $text, $origText, $isMain );
1346 * Helper function for parse() that transforms half-parsed HTML into fully
1349 * @param string $text
1350 * @param bool $isMain
1351 * @param bool $linestart
1354 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1355 $text = $this->mStripState
->unstripGeneral( $text );
1357 // Avoid PHP 7.1 warning from passing $this by reference
1361 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1364 # Clean up special characters, only run once, next-to-last before doBlockLevels
1365 $text = Sanitizer
::armorFrenchSpaces( $text );
1367 $text = $this->doBlockLevels( $text, $linestart );
1369 $this->replaceLinkHolders( $text );
1372 * The input doesn't get language converted if
1374 * b) Content isn't converted
1375 * c) It's a conversion table
1376 * d) it is an interface message (which is in the user language)
1378 if ( !( $this->mOptions
->getDisableContentConversion()
1379 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1381 if ( !$this->mOptions
->getInterfaceMessage() ) {
1382 # The position of the convert() call should not be changed. it
1383 # assumes that the links are all replaced and the only thing left
1384 # is the <nowiki> mark.
1385 $text = $this->getTargetLanguage()->convert( $text );
1389 $text = $this->mStripState
->unstripNoWiki( $text );
1392 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1395 $text = $this->replaceTransparentTags( $text );
1396 $text = $this->mStripState
->unstripGeneral( $text );
1398 $text = Sanitizer
::normalizeCharReferences( $text );
1400 if ( MWTidy
::isEnabled() ) {
1401 if ( $this->mOptions
->getTidy() ) {
1402 $text = MWTidy
::tidy( $text );
1405 # attempt to sanitize at least some nesting problems
1406 # (T4702 and quite a few others)
1408 # ''Something [http://www.cool.com cool''] -->
1409 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1410 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1411 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1412 # fix up an anchor inside another anchor, only
1413 # at least for a single single nested link (T5695)
1414 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1415 '\\1\\2</a>\\3</a>\\1\\4</a>',
1416 # fix div inside inline elements- doBlockLevels won't wrap a line which
1417 # contains a div, so fix it up here; replace
1418 # div with escaped text
1419 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1420 '\\1\\3<div\\5>\\6</div>\\8\\9',
1421 # remove empty italic or bold tag pairs, some
1422 # introduced by rules above
1423 '/<([bi])><\/\\1>/' => '',
1426 $text = preg_replace(
1427 array_keys( $tidyregs ),
1428 array_values( $tidyregs ),
1433 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1440 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1441 * magic external links.
1446 * @param string $text
1450 public function doMagicLinks( $text ) {
1451 $prots = wfUrlProtocolsWithoutProtRel();
1452 $urlChar = self
::EXT_LINK_URL_CLASS
;
1453 $addr = self
::EXT_LINK_ADDR
;
1454 $space = self
::SPACE_NOT_NL
; # non-newline space
1455 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1456 $spaces = "$space++"; # possessive match of 1 or more spaces
1457 $text = preg_replace_callback(
1459 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1460 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1461 (\b # m[3]: Free external links
1463 ($addr$urlChar*) # m[4]: Post-protocol path
1465 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1467 \bISBN $spaces ( # m[6]: ISBN, capture number
1468 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1469 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1470 [0-9Xx] # check digit
1472 )!xu", [ $this, 'magicLinkCallback' ], $text );
1477 * @throws MWException
1479 * @return string HTML
1481 public function magicLinkCallback( $m ) {
1482 if ( isset( $m[1] ) && $m[1] !== '' ) {
1485 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1488 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1489 # Free external link
1490 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1491 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1493 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1494 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1499 $cssClass = 'mw-magiclink-rfc';
1500 $trackingCat = 'magiclink-tracking-rfc';
1502 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1503 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1507 $urlmsg = 'pubmedurl';
1508 $cssClass = 'mw-magiclink-pmid';
1509 $trackingCat = 'magiclink-tracking-pmid';
1512 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1513 substr( $m[0], 0, 20 ) . '"' );
1515 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1516 $this->addTrackingCategory( $trackingCat );
1517 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1518 } elseif ( isset( $m[6] ) && $m[6] !== ''
1519 && $this->mOptions
->getMagicISBNLinks()
1523 $space = self
::SPACE_NOT_NL
; # non-newline space
1524 $isbn = preg_replace( "/$space/", ' ', $isbn );
1525 $num = strtr( $isbn, [
1530 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1531 return $this->getLinkRenderer()->makeKnownLink(
1532 SpecialPage
::getTitleFor( 'Booksources', $num ),
1535 'class' => 'internal mw-magiclink-isbn',
1536 'title' => false // suppress title attribute
1545 * Make a free external link, given a user-supplied URL
1547 * @param string $url
1548 * @param int $numPostProto
1549 * The number of characters after the protocol.
1550 * @return string HTML
1553 public function makeFreeExternalLink( $url, $numPostProto ) {
1556 # The characters '<' and '>' (which were escaped by
1557 # removeHTMLtags()) should not be included in
1558 # URLs, per RFC 2396.
1559 # Make terminate a URL as well (bug T84937)
1562 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1567 $trail = substr( $url, $m2[0][1] ) . $trail;
1568 $url = substr( $url, 0, $m2[0][1] );
1571 # Move trailing punctuation to $trail
1573 # If there is no left bracket, then consider right brackets fair game too
1574 if ( strpos( $url, '(' ) === false ) {
1578 $urlRev = strrev( $url );
1579 $numSepChars = strspn( $urlRev, $sep );
1580 # Don't break a trailing HTML entity by moving the ; into $trail
1581 # This is in hot code, so use substr_compare to avoid having to
1582 # create a new string object for the comparison
1583 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1584 # more optimization: instead of running preg_match with a $
1585 # anchor, which can be slow, do the match on the reversed
1586 # string starting at the desired offset.
1587 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1588 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1592 if ( $numSepChars ) {
1593 $trail = substr( $url, -$numSepChars ) . $trail;
1594 $url = substr( $url, 0, -$numSepChars );
1597 # Verify that we still have a real URL after trail removal, and
1598 # not just lone protocol
1599 if ( strlen( $trail ) >= $numPostProto ) {
1600 return $url . $trail;
1603 $url = Sanitizer
::cleanUrl( $url );
1605 # Is this an external image?
1606 $text = $this->maybeMakeExternalImage( $url );
1607 if ( $text === false ) {
1608 # Not an image, make a link
1609 $text = Linker
::makeExternalLink( $url,
1610 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1612 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1613 # Register it in the output object...
1614 $this->mOutput
->addExternalLink( $url );
1616 return $text . $trail;
1620 * Parse headers and return html
1624 * @param string $text
1628 public function doHeadings( $text ) {
1629 for ( $i = 6; $i >= 1; --$i ) {
1630 $h = str_repeat( '=', $i );
1631 // Trim non-newline whitespace from headings
1632 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1633 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1639 * Replace single quotes with HTML markup
1642 * @param string $text
1644 * @return string The altered text
1646 public function doAllQuotes( $text ) {
1648 $lines = StringUtils
::explode( "\n", $text );
1649 foreach ( $lines as $line ) {
1650 $outtext .= $this->doQuotes( $line ) . "\n";
1652 $outtext = substr( $outtext, 0, -1 );
1657 * Helper function for doAllQuotes()
1659 * @param string $text
1663 public function doQuotes( $text ) {
1664 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1665 $countarr = count( $arr );
1666 if ( $countarr == 1 ) {
1670 // First, do some preliminary work. This may shift some apostrophes from
1671 // being mark-up to being text. It also counts the number of occurrences
1672 // of bold and italics mark-ups.
1675 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1676 $thislen = strlen( $arr[$i] );
1677 // If there are ever four apostrophes, assume the first is supposed to
1678 // be text, and the remaining three constitute mark-up for bold text.
1679 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1680 if ( $thislen == 4 ) {
1681 $arr[$i - 1] .= "'";
1684 } elseif ( $thislen > 5 ) {
1685 // If there are more than 5 apostrophes in a row, assume they're all
1686 // text except for the last 5.
1687 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1688 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1692 // Count the number of occurrences of bold and italics mark-ups.
1693 if ( $thislen == 2 ) {
1695 } elseif ( $thislen == 3 ) {
1697 } elseif ( $thislen == 5 ) {
1703 // If there is an odd number of both bold and italics, it is likely
1704 // that one of the bold ones was meant to be an apostrophe followed
1705 // by italics. Which one we cannot know for certain, but it is more
1706 // likely to be one that has a single-letter word before it.
1707 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1708 $firstsingleletterword = -1;
1709 $firstmultiletterword = -1;
1711 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1712 if ( strlen( $arr[$i] ) == 3 ) {
1713 $x1 = substr( $arr[$i - 1], -1 );
1714 $x2 = substr( $arr[$i - 1], -2, 1 );
1715 if ( $x1 === ' ' ) {
1716 if ( $firstspace == -1 ) {
1719 } elseif ( $x2 === ' ' ) {
1720 $firstsingleletterword = $i;
1721 // if $firstsingleletterword is set, we don't
1722 // look at the other options, so we can bail early.
1725 if ( $firstmultiletterword == -1 ) {
1726 $firstmultiletterword = $i;
1732 // If there is a single-letter word, use it!
1733 if ( $firstsingleletterword > -1 ) {
1734 $arr[$firstsingleletterword] = "''";
1735 $arr[$firstsingleletterword - 1] .= "'";
1736 } elseif ( $firstmultiletterword > -1 ) {
1737 // If not, but there's a multi-letter word, use that one.
1738 $arr[$firstmultiletterword] = "''";
1739 $arr[$firstmultiletterword - 1] .= "'";
1740 } elseif ( $firstspace > -1 ) {
1741 // ... otherwise use the first one that has neither.
1742 // (notice that it is possible for all three to be -1 if, for example,
1743 // there is only one pentuple-apostrophe in the line)
1744 $arr[$firstspace] = "''";
1745 $arr[$firstspace - 1] .= "'";
1749 // Now let's actually convert our apostrophic mush to HTML!
1754 foreach ( $arr as $r ) {
1755 if ( ( $i %
2 ) == 0 ) {
1756 if ( $state === 'both' ) {
1762 $thislen = strlen( $r );
1763 if ( $thislen == 2 ) {
1764 if ( $state === 'i' ) {
1767 } elseif ( $state === 'bi' ) {
1770 } elseif ( $state === 'ib' ) {
1771 $output .= '</b></i><b>';
1773 } elseif ( $state === 'both' ) {
1774 $output .= '<b><i>' . $buffer . '</i>';
1776 } else { // $state can be 'b' or ''
1780 } elseif ( $thislen == 3 ) {
1781 if ( $state === 'b' ) {
1784 } elseif ( $state === 'bi' ) {
1785 $output .= '</i></b><i>';
1787 } elseif ( $state === 'ib' ) {
1790 } elseif ( $state === 'both' ) {
1791 $output .= '<i><b>' . $buffer . '</b>';
1793 } else { // $state can be 'i' or ''
1797 } elseif ( $thislen == 5 ) {
1798 if ( $state === 'b' ) {
1799 $output .= '</b><i>';
1801 } elseif ( $state === 'i' ) {
1802 $output .= '</i><b>';
1804 } elseif ( $state === 'bi' ) {
1805 $output .= '</i></b>';
1807 } elseif ( $state === 'ib' ) {
1808 $output .= '</b></i>';
1810 } elseif ( $state === 'both' ) {
1811 $output .= '<i><b>' . $buffer . '</b></i>';
1813 } else { // ($state == '')
1821 // Now close all remaining tags. Notice that the order is important.
1822 if ( $state === 'b' ||
$state === 'ib' ) {
1825 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1828 if ( $state === 'bi' ) {
1831 // There might be lonely ''''', so make sure we have a buffer
1832 if ( $state === 'both' && $buffer ) {
1833 $output .= '<b><i>' . $buffer . '</i></b>';
1839 * Replace external links (REL)
1841 * Note: this is all very hackish and the order of execution matters a lot.
1842 * Make sure to run tests/parser/parserTests.php if you change this code.
1846 * @param string $text
1848 * @throws MWException
1851 public function replaceExternalLinks( $text ) {
1852 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1853 if ( $bits === false ) {
1854 throw new MWException( "PCRE needs to be compiled with "
1855 . "--enable-unicode-properties in order for MediaWiki to function" );
1857 $s = array_shift( $bits );
1860 while ( $i < count( $bits ) ) {
1863 $text = $bits[$i++
];
1864 $trail = $bits[$i++
];
1866 # The characters '<' and '>' (which were escaped by
1867 # removeHTMLtags()) should not be included in
1868 # URLs, per RFC 2396.
1870 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1871 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1872 $url = substr( $url, 0, $m2[0][1] );
1875 # If the link text is an image URL, replace it with an <img> tag
1876 # This happened by accident in the original parser, but some people used it extensively
1877 $img = $this->maybeMakeExternalImage( $text );
1878 if ( $img !== false ) {
1884 # Set linktype for CSS
1887 # No link text, e.g. [http://domain.tld/some.link]
1888 if ( $text == '' ) {
1890 $langObj = $this->getTargetLanguage();
1891 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1892 $linktype = 'autonumber';
1894 # Have link text, e.g. [http://domain.tld/some.link text]s
1896 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1899 // Excluding protocol-relative URLs may avoid many false positives.
1900 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1901 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1904 $url = Sanitizer
::cleanUrl( $url );
1906 # Use the encoded URL
1907 # This means that users can paste URLs directly into the text
1908 # Funny characters like ö aren't valid in URLs anyway
1909 # This was changed in August 2004
1910 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1911 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1913 # Register link in the output object.
1914 $this->mOutput
->addExternalLink( $url );
1921 * Get the rel attribute for a particular external link.
1924 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1925 * nofollow if appropriate
1926 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1927 * @return string|null Rel attribute for $url
1929 public static function getExternalLinkRel( $url = false, $title = null ) {
1930 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1931 $ns = $title ?
$title->getNamespace() : false;
1932 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1933 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1941 * Get an associative array of additional HTML attributes appropriate for a
1942 * particular external link. This currently may include rel => nofollow
1943 * (depending on configuration, namespace, and the URL's domain) and/or a
1944 * target attribute (depending on configuration).
1946 * @param string $url URL to extract the domain from for rel =>
1947 * nofollow if appropriate
1948 * @return array Associative array of HTML attributes
1950 public function getExternalLinkAttribs( $url ) {
1952 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1954 $target = $this->mOptions
->getExternalLinkTarget();
1956 $attribs['target'] = $target;
1957 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1958 // T133507. New windows can navigate parent cross-origin.
1959 // Including noreferrer due to lacking browser
1960 // support of noopener. Eventually noreferrer should be removed.
1961 if ( $rel !== '' ) {
1964 $rel .= 'noreferrer noopener';
1967 $attribs['rel'] = $rel;
1972 * Replace unusual escape codes in a URL with their equivalent characters
1974 * This generally follows the syntax defined in RFC 3986, with special
1975 * consideration for HTTP query strings.
1977 * @param string $url
1980 public static function normalizeLinkUrl( $url ) {
1981 # First, make sure unsafe characters are encoded
1982 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1984 return rawurlencode( $m[0] );
1990 $end = strlen( $url );
1992 # Fragment part - 'fragment'
1993 $start = strpos( $url, '#' );
1994 if ( $start !== false && $start < $end ) {
1995 $ret = self
::normalizeUrlComponent(
1996 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2000 # Query part - 'query' minus &=+;
2001 $start = strpos( $url, '?' );
2002 if ( $start !== false && $start < $end ) {
2003 $ret = self
::normalizeUrlComponent(
2004 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2008 # Scheme and path part - 'pchar'
2009 # (we assume no userinfo or encoded colons in the host)
2010 $ret = self
::normalizeUrlComponent(
2011 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2016 private static function normalizeUrlComponent( $component, $unsafe ) {
2017 $callback = function ( $matches ) use ( $unsafe ) {
2018 $char = urldecode( $matches[0] );
2019 $ord = ord( $char );
2020 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2024 # Leave it escaped, but use uppercase for a-f
2025 return strtoupper( $matches[0] );
2028 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2032 * make an image if it's allowed, either through the global
2033 * option, through the exception, or through the on-wiki whitelist
2035 * @param string $url
2039 private function maybeMakeExternalImage( $url ) {
2040 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2041 $imagesexception = !empty( $imagesfrom );
2043 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2044 if ( $imagesexception && is_array( $imagesfrom ) ) {
2045 $imagematch = false;
2046 foreach ( $imagesfrom as $match ) {
2047 if ( strpos( $url, $match ) === 0 ) {
2052 } elseif ( $imagesexception ) {
2053 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2055 $imagematch = false;
2058 if ( $this->mOptions
->getAllowExternalImages()
2059 ||
( $imagesexception && $imagematch )
2061 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2063 $text = Linker
::makeExternalImage( $url );
2066 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2067 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2069 $whitelist = explode(
2071 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2074 foreach ( $whitelist as $entry ) {
2075 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2076 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2079 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2080 # Image matches a whitelist entry
2081 $text = Linker
::makeExternalImage( $url );
2090 * Process [[ ]] wikilinks
2094 * @return string Processed text
2098 public function replaceInternalLinks( $s ) {
2099 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2104 * Process [[ ]] wikilinks (RIL)
2106 * @throws MWException
2107 * @return LinkHolderArray
2111 public function replaceInternalLinks2( &$s ) {
2112 global $wgExtraInterlanguageLinkPrefixes;
2114 static $tc = false, $e1, $e1_img;
2115 # the % is needed to support urlencoded titles as well
2117 $tc = Title
::legalChars() . '#%';
2118 # Match a link having the form [[namespace:link|alternate]]trail
2119 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2120 # Match cases where there is no "]]", which might still be images
2121 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2124 $holders = new LinkHolderArray( $this );
2126 # split the entire text string on occurrences of [[
2127 $a = StringUtils
::explode( '[[', ' ' . $s );
2128 # get the first element (all text up to first [[), and remove the space we added
2131 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2132 $s = substr( $s, 1 );
2134 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2136 if ( $useLinkPrefixExtension ) {
2137 # Match the end of a line for a word that's not followed by whitespace,
2138 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2140 $charset = $wgContLang->linkPrefixCharset();
2141 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2144 if ( is_null( $this->mTitle
) ) {
2145 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2147 $nottalk = !$this->mTitle
->isTalkPage();
2149 if ( $useLinkPrefixExtension ) {
2151 if ( preg_match( $e2, $s, $m ) ) {
2152 $first_prefix = $m[2];
2154 $first_prefix = false;
2160 $useSubpages = $this->areSubpagesAllowed();
2162 # Loop for each link
2163 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2164 # Check for excessive memory usage
2165 if ( $holders->isBig() ) {
2167 # Do the existence check, replace the link holders and clear the array
2168 $holders->replace( $s );
2172 if ( $useLinkPrefixExtension ) {
2173 if ( preg_match( $e2, $s, $m ) ) {
2180 if ( $first_prefix ) {
2181 $prefix = $first_prefix;
2182 $first_prefix = false;
2186 $might_be_img = false;
2188 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2190 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2191 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2192 # the real problem is with the $e1 regex
2194 # Still some problems for cases where the ] is meant to be outside punctuation,
2195 # and no image is in sight. See T4095.
2197 && substr( $m[3], 0, 1 ) === ']'
2198 && strpos( $text, '[' ) !== false
2200 $text .= ']'; # so that replaceExternalLinks($text) works later
2201 $m[3] = substr( $m[3], 1 );
2203 # fix up urlencoded title texts
2204 if ( strpos( $m[1], '%' ) !== false ) {
2205 # Should anchors '#' also be rejected?
2206 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2209 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2210 # Invalid, but might be an image with a link in its caption
2211 $might_be_img = true;
2213 if ( strpos( $m[1], '%' ) !== false ) {
2214 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2217 } else { # Invalid form; output directly
2218 $s .= $prefix . '[[' . $line;
2222 $origLink = ltrim( $m[1], ' ' );
2224 # Don't allow internal links to pages containing
2225 # PROTO: where PROTO is a valid URL protocol; these
2226 # should be external links.
2227 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2228 $s .= $prefix . '[[' . $line;
2232 # Make subpage if necessary
2233 if ( $useSubpages ) {
2234 $link = $this->maybeDoSubpageLink( $origLink, $text );
2239 // \x7f isn't a default legal title char, so most likely strip
2240 // markers will force us into the "invalid form" path above. But,
2241 // just in case, let's assert that xmlish tags aren't valid in
2242 // the title position.
2243 $unstrip = $this->mStripState
->killMarkers( $link );
2244 $noMarkers = ( $unstrip === $link );
2246 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2247 if ( $nt === null ) {
2248 $s .= $prefix . '[[' . $line;
2252 $ns = $nt->getNamespace();
2253 $iw = $nt->getInterwiki();
2255 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2257 if ( $might_be_img ) { # if this is actually an invalid link
2258 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2261 # look at the next 'line' to see if we can close it there
2263 $next_line = $a->current();
2264 if ( $next_line === false ||
$next_line === null ) {
2267 $m = explode( ']]', $next_line, 3 );
2268 if ( count( $m ) == 3 ) {
2269 # the first ]] closes the inner link, the second the image
2271 $text .= "[[{$m[0]}]]{$m[1]}";
2274 } elseif ( count( $m ) == 2 ) {
2275 # if there's exactly one ]] that's fine, we'll keep looking
2276 $text .= "[[{$m[0]}]]{$m[1]}";
2278 # if $next_line is invalid too, we need look no further
2279 $text .= '[[' . $next_line;
2284 # we couldn't find the end of this imageLink, so output it raw
2285 # but don't ignore what might be perfectly normal links in the text we've examined
2286 $holders->merge( $this->replaceInternalLinks2( $text ) );
2287 $s .= "{$prefix}[[$link|$text";
2288 # note: no $trail, because without an end, there *is* no trail
2291 } else { # it's not an image, so output it raw
2292 $s .= "{$prefix}[[$link|$text";
2293 # note: no $trail, because without an end, there *is* no trail
2298 $wasblank = ( $text == '' );
2302 # Strip off leading ':'
2303 $text = substr( $text, 1 );
2306 # T6598 madness. Handle the quotes only if they come from the alternate part
2307 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2308 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2309 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2310 $text = $this->doQuotes( $text );
2313 # Link not escaped by : , create the various objects
2314 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2317 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2318 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2319 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2322 # T26502: filter duplicates
2323 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2324 $this->mLangLinkLanguages
[$iw] = true;
2325 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2329 * Strip the whitespace interwiki links produce, see T10897
2331 $s = rtrim( $s . $prefix ) . $trail; # T175416
2335 if ( $ns == NS_FILE
) {
2336 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2338 # if no parameters were passed, $text
2339 # becomes something like "File:Foo.png",
2340 # which we don't want to pass on to the
2344 # recursively parse links inside the image caption
2345 # actually, this will parse them in any other parameters, too,
2346 # but it might be hard to fix that, and it doesn't matter ATM
2347 $text = $this->replaceExternalLinks( $text );
2348 $holders->merge( $this->replaceInternalLinks2( $text ) );
2350 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2351 $s .= $prefix . $this->armorLinks(
2352 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2355 } elseif ( $ns == NS_CATEGORY
) {
2357 * Strip the whitespace Category links produce, see T2087
2359 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2362 $sortkey = $this->getDefaultSort();
2366 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2367 $sortkey = str_replace( "\n", '', $sortkey );
2368 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2369 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2375 # Self-link checking. For some languages, variants of the title are checked in
2376 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2377 # for linking to a different variant.
2378 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2379 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2383 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2384 # @todo FIXME: Should do batch file existence checks, see comment below
2385 if ( $ns == NS_MEDIA
) {
2386 # Give extensions a chance to select the file revision for us
2389 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2390 [ $this, $nt, &$options, &$descQuery ] );
2391 # Fetch and register the file (file title may be different via hooks)
2392 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2393 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2394 $s .= $prefix . $this->armorLinks(
2395 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2399 # Some titles, such as valid special pages or files in foreign repos, should
2400 # be shown as bluelinks even though they're not included in the page table
2401 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2402 # batch file existence checks for NS_FILE and NS_MEDIA
2403 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2404 $this->mOutput
->addLink( $nt );
2405 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2407 # Links will be added to the output link list after checking
2408 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2415 * Render a forced-blue link inline; protect against double expansion of
2416 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2417 * Since this little disaster has to split off the trail text to avoid
2418 * breaking URLs in the following text without breaking trails on the
2419 * wiki links, it's been made into a horrible function.
2422 * @param string $text
2423 * @param string $trail
2424 * @param string $prefix
2425 * @return string HTML-wikitext mix oh yuck
2427 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2428 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2430 if ( $text == '' ) {
2431 $text = htmlspecialchars( $nt->getPrefixedText() );
2434 $link = $this->getLinkRenderer()->makeKnownLink(
2435 $nt, new HtmlArmor( "$prefix$text$inside" )
2438 return $this->armorLinks( $link ) . $trail;
2442 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2443 * going to go through further parsing steps before inline URL expansion.
2445 * Not needed quite as much as it used to be since free links are a bit
2446 * more sensible these days. But bracketed links are still an issue.
2448 * @param string $text More-or-less HTML
2449 * @return string Less-or-more HTML with NOPARSE bits
2451 public function armorLinks( $text ) {
2452 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2453 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2457 * Return true if subpage links should be expanded on this page.
2460 public function areSubpagesAllowed() {
2461 # Some namespaces don't allow subpages
2462 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2466 * Handle link to subpage if necessary
2468 * @param string $target The source of the link
2469 * @param string &$text The link text, modified as necessary
2470 * @return string The full name of the link
2473 public function maybeDoSubpageLink( $target, &$text ) {
2474 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2478 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2480 * @param string $text
2481 * @param bool $linestart Whether or not this is at the start of a line.
2483 * @return string The lists rendered as HTML
2485 public function doBlockLevels( $text, $linestart ) {
2486 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2490 * Return value of a magic variable (like PAGENAME)
2494 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2495 * @param bool|PPFrame $frame
2497 * @throws MWException
2500 public function getVariableValue( $index, $frame = false ) {
2501 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2502 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2504 if ( is_null( $this->mTitle
) ) {
2505 // If no title set, bad things are going to happen
2506 // later. Title should always be set since this
2507 // should only be called in the middle of a parse
2508 // operation (but the unit-tests do funky stuff)
2509 throw new MWException( __METHOD__
. ' Should only be '
2510 . ' called while parsing (no title set)' );
2513 // Avoid PHP 7.1 warning from passing $this by reference
2517 * Some of these require message or data lookups and can be
2518 * expensive to check many times.
2520 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2521 if ( isset( $this->mVarCache
[$index] ) ) {
2522 return $this->mVarCache
[$index];
2526 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2527 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2529 $pageLang = $this->getFunctionLang();
2535 case 'currentmonth':
2536 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2538 case 'currentmonth1':
2539 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2541 case 'currentmonthname':
2542 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2544 case 'currentmonthnamegen':
2545 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2547 case 'currentmonthabbrev':
2548 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2551 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2554 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2557 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2560 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2562 case 'localmonthname':
2563 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2565 case 'localmonthnamegen':
2566 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2568 case 'localmonthabbrev':
2569 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2572 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2575 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2578 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2581 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2583 case 'fullpagename':
2584 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2586 case 'fullpagenamee':
2587 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2590 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2592 case 'subpagenamee':
2593 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2595 case 'rootpagename':
2596 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2598 case 'rootpagenamee':
2599 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2602 $this->mTitle
->getRootText()
2605 case 'basepagename':
2606 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2608 case 'basepagenamee':
2609 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2612 $this->mTitle
->getBaseText()
2615 case 'talkpagename':
2616 if ( $this->mTitle
->canHaveTalkPage() ) {
2617 $talkPage = $this->mTitle
->getTalkPage();
2618 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2623 case 'talkpagenamee':
2624 if ( $this->mTitle
->canHaveTalkPage() ) {
2625 $talkPage = $this->mTitle
->getTalkPage();
2626 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2631 case 'subjectpagename':
2632 $subjPage = $this->mTitle
->getSubjectPage();
2633 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2635 case 'subjectpagenamee':
2636 $subjPage = $this->mTitle
->getSubjectPage();
2637 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2639 case 'pageid': // requested in T25427
2640 $pageid = $this->getTitle()->getArticleID();
2641 if ( $pageid == 0 ) {
2642 # 0 means the page doesn't exist in the database,
2643 # which means the user is previewing a new page.
2644 # The vary-revision flag must be set, because the magic word
2645 # will have a different value once the page is saved.
2646 $this->mOutput
->setFlag( 'vary-revision' );
2647 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2649 $value = $pageid ?
: null;
2652 # Let the edit saving system know we should parse the page
2653 # *after* a revision ID has been assigned.
2654 $this->mOutput
->setFlag( 'vary-revision-id' );
2655 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2656 $value = $this->mRevisionId
;
2657 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2658 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2659 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2663 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2665 case 'revisionday2':
2666 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2668 case 'revisionmonth':
2669 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2671 case 'revisionmonth1':
2672 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2674 case 'revisionyear':
2675 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2677 case 'revisiontimestamp':
2678 # Let the edit saving system know we should parse the page
2679 # *after* a revision ID has been assigned. This is for null edits.
2680 $this->mOutput
->setFlag( 'vary-revision' );
2681 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2682 $value = $this->getRevisionTimestamp();
2684 case 'revisionuser':
2685 # Let the edit saving system know we should parse the page
2686 # *after* a revision ID has been assigned for null edits.
2687 $this->mOutput
->setFlag( 'vary-user' );
2688 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2689 $value = $this->getRevisionUser();
2691 case 'revisionsize':
2692 $value = $this->getRevisionSize();
2695 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2698 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2700 case 'namespacenumber':
2701 $value = $this->mTitle
->getNamespace();
2704 $value = $this->mTitle
->canHaveTalkPage()
2705 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2709 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2711 case 'subjectspace':
2712 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2714 case 'subjectspacee':
2715 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2717 case 'currentdayname':
2718 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2721 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2724 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2727 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2730 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2731 # int to remove the padding
2732 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2735 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2737 case 'localdayname':
2738 $value = $pageLang->getWeekdayName(
2739 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2743 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2746 $value = $pageLang->time(
2747 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2753 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2756 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2757 # int to remove the padding
2758 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2761 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2763 case 'numberofarticles':
2764 $value = $pageLang->formatNum( SiteStats
::articles() );
2766 case 'numberoffiles':
2767 $value = $pageLang->formatNum( SiteStats
::images() );
2769 case 'numberofusers':
2770 $value = $pageLang->formatNum( SiteStats
::users() );
2772 case 'numberofactiveusers':
2773 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2775 case 'numberofpages':
2776 $value = $pageLang->formatNum( SiteStats
::pages() );
2778 case 'numberofadmins':
2779 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2781 case 'numberofedits':
2782 $value = $pageLang->formatNum( SiteStats
::edits() );
2784 case 'currenttimestamp':
2785 $value = wfTimestamp( TS_MW
, $ts );
2787 case 'localtimestamp':
2788 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2790 case 'currentversion':
2791 $value = SpecialVersion
::getVersion();
2794 return $wgArticlePath;
2800 return $wgServerName;
2802 return $wgScriptPath;
2804 return $wgStylePath;
2805 case 'directionmark':
2806 return $pageLang->getDirMark();
2807 case 'contentlanguage':
2808 global $wgLanguageCode;
2809 return $wgLanguageCode;
2810 case 'pagelanguage':
2811 $value = $pageLang->getCode();
2813 case 'cascadingsources':
2814 $value = CoreParserFunctions
::cascadingsources( $this );
2819 'ParserGetVariableValueSwitch',
2820 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2827 $this->mVarCache
[$index] = $value;
2836 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2837 * @param string $variable Parser variable name
2840 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2843 # Get the timezone-adjusted timestamp to be used for this revision
2844 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2845 # Possibly set vary-revision if there is not yet an associated revision
2846 if ( !$this->getRevisionObject() ) {
2847 # Get the timezone-adjusted timestamp $mtts seconds in the future
2849 $wgContLang->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2854 if ( $resNow !== $resThen ) {
2855 # Let the edit saving system know we should parse the page
2856 # *after* a revision ID has been assigned. This is for null edits.
2857 $this->mOutput
->setFlag( 'vary-revision' );
2858 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2866 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2870 public function initialiseVariables() {
2871 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2872 $substIDs = $this->magicWordFactory
->getSubstIDs();
2874 $this->mVariables
= new MagicWordArray( $variableIDs );
2875 $this->mSubstWords
= new MagicWordArray( $substIDs );
2879 * Preprocess some wikitext and return the document tree.
2880 * This is the ghost of replace_variables().
2882 * @param string $text The text to parse
2883 * @param int $flags Bitwise combination of:
2884 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2885 * included. Default is to assume a direct page view.
2887 * The generated DOM tree must depend only on the input text and the flags.
2888 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2890 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2891 * change in the DOM tree for a given text, must be passed through the section identifier
2892 * in the section edit link and thus back to extractSections().
2894 * The output of this function is currently only cached in process memory, but a persistent
2895 * cache may be implemented at a later date which takes further advantage of these strict
2896 * dependency requirements.
2900 public function preprocessToDom( $text, $flags = 0 ) {
2901 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2906 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2912 public static function splitWhitespace( $s ) {
2913 $ltrimmed = ltrim( $s );
2914 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2915 $trimmed = rtrim( $ltrimmed );
2916 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2918 $w2 = substr( $ltrimmed, -$diff );
2922 return [ $w1, $trimmed, $w2 ];
2926 * Replace magic variables, templates, and template arguments
2927 * with the appropriate text. Templates are substituted recursively,
2928 * taking care to avoid infinite loops.
2930 * Note that the substitution depends on value of $mOutputType:
2931 * self::OT_WIKI: only {{subst:}} templates
2932 * self::OT_PREPROCESS: templates but not extension tags
2933 * self::OT_HTML: all templates and extension tags
2935 * @param string $text The text to transform
2936 * @param bool|PPFrame $frame Object describing the arguments passed to the
2937 * template. Arguments may also be provided as an associative array, as
2938 * was the usual case before MW1.12. Providing arguments this way may be
2939 * useful for extensions wishing to perform variable replacement
2941 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2942 * double-brace expansion.
2945 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2946 # Is there any text? Also, Prevent too big inclusions!
2947 $textSize = strlen( $text );
2948 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2952 if ( $frame === false ) {
2953 $frame = $this->getPreprocessor()->newFrame();
2954 } elseif ( !( $frame instanceof PPFrame
) ) {
2955 wfDebug( __METHOD__
. " called using plain parameters instead of "
2956 . "a PPFrame instance. Creating custom frame.\n" );
2957 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2960 $dom = $this->preprocessToDom( $text );
2961 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2962 $text = $frame->expand( $dom, $flags );
2968 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2970 * @param array $args
2974 public static function createAssocArgs( $args ) {
2977 foreach ( $args as $arg ) {
2978 $eqpos = strpos( $arg, '=' );
2979 if ( $eqpos === false ) {
2980 $assocArgs[$index++
] = $arg;
2982 $name = trim( substr( $arg, 0, $eqpos ) );
2983 $value = trim( substr( $arg, $eqpos +
1 ) );
2984 if ( $value === false ) {
2987 if ( $name !== false ) {
2988 $assocArgs[$name] = $value;
2997 * Warn the user when a parser limitation is reached
2998 * Will warn at most once the user per limitation type
3000 * The results are shown during preview and run through the Parser (See EditPage.php)
3002 * @param string $limitationType Should be one of:
3003 * 'expensive-parserfunction' (corresponding messages:
3004 * 'expensive-parserfunction-warning',
3005 * 'expensive-parserfunction-category')
3006 * 'post-expand-template-argument' (corresponding messages:
3007 * 'post-expand-template-argument-warning',
3008 * 'post-expand-template-argument-category')
3009 * 'post-expand-template-inclusion' (corresponding messages:
3010 * 'post-expand-template-inclusion-warning',
3011 * 'post-expand-template-inclusion-category')
3012 * 'node-count-exceeded' (corresponding messages:
3013 * 'node-count-exceeded-warning',
3014 * 'node-count-exceeded-category')
3015 * 'expansion-depth-exceeded' (corresponding messages:
3016 * 'expansion-depth-exceeded-warning',
3017 * 'expansion-depth-exceeded-category')
3018 * @param string|int|null $current Current value
3019 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3020 * exceeded, provide the values (optional)
3022 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3023 # does no harm if $current and $max are present but are unnecessary for the message
3024 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3025 # only during preview, and that would split the parser cache unnecessarily.
3026 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3028 $this->mOutput
->addWarning( $warning );
3029 $this->addTrackingCategory( "$limitationType-category" );
3033 * Return the text of a template, after recursively
3034 * replacing any variables or templates within the template.
3036 * @param array $piece The parts of the template
3037 * $piece['title']: the title, i.e. the part before the |
3038 * $piece['parts']: the parameter array
3039 * $piece['lineStart']: whether the brace was at the start of a line
3040 * @param PPFrame $frame The current frame, contains template arguments
3042 * @return string The text of the template
3044 public function braceSubstitution( $piece, $frame ) {
3047 // $text has been filled
3049 // wiki markup in $text should be escaped
3051 // $text is HTML, armour it against wikitext transformation
3053 // Force interwiki transclusion to be done in raw mode not rendered
3054 $forceRawInterwiki = false;
3055 // $text is a DOM node needing expansion in a child frame
3056 $isChildObj = false;
3057 // $text is a DOM node needing expansion in the current frame
3058 $isLocalObj = false;
3060 # Title object, where $text came from
3063 # $part1 is the bit before the first |, and must contain only title characters.
3064 # Various prefixes will be stripped from it later.
3065 $titleWithSpaces = $frame->expand( $piece['title'] );
3066 $part1 = trim( $titleWithSpaces );
3069 # Original title text preserved for various purposes
3070 $originalTitle = $part1;
3072 # $args is a list of argument nodes, starting from index 0, not including $part1
3073 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3074 # below won't work b/c this $args isn't an object
3075 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3077 $profileSection = null; // profile templates
3081 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3083 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3084 # Decide whether to expand template or keep wikitext as-is.
3085 if ( $this->ot
['wiki'] ) {
3086 if ( $substMatch === false ) {
3087 $literal = true; # literal when in PST with no prefix
3089 $literal = false; # expand when in PST with subst: or safesubst:
3092 if ( $substMatch == 'subst' ) {
3093 $literal = true; # literal when not in PST with plain subst:
3095 $literal = false; # expand when not in PST with safesubst: or no prefix
3099 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3106 if ( !$found && $args->getLength() == 0 ) {
3107 $id = $this->mVariables
->matchStartToEnd( $part1 );
3108 if ( $id !== false ) {
3109 $text = $this->getVariableValue( $id, $frame );
3110 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3111 $this->mOutput
->updateCacheExpiry(
3112 $this->magicWordFactory
->getCacheTTL( $id ) );
3118 # MSG, MSGNW and RAW
3121 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3122 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3125 # Remove obsolete MSG:
3126 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3127 $mwMsg->matchStartAndRemove( $part1 );
3131 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3132 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3133 $forceRawInterwiki = true;
3139 $colonPos = strpos( $part1, ':' );
3140 if ( $colonPos !== false ) {
3141 $func = substr( $part1, 0, $colonPos );
3142 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3143 $argsLength = $args->getLength();
3144 for ( $i = 0; $i < $argsLength; $i++
) {
3145 $funcArgs[] = $args->item( $i );
3148 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3150 // Extract any forwarded flags
3151 if ( isset( $result['title'] ) ) {
3152 $title = $result['title'];
3154 if ( isset( $result['found'] ) ) {
3155 $found = $result['found'];
3157 if ( array_key_exists( 'text', $result ) ) {
3159 $text = $result['text'];
3161 if ( isset( $result['nowiki'] ) ) {
3162 $nowiki = $result['nowiki'];
3164 if ( isset( $result['isHTML'] ) ) {
3165 $isHTML = $result['isHTML'];
3167 if ( isset( $result['forceRawInterwiki'] ) ) {
3168 $forceRawInterwiki = $result['forceRawInterwiki'];
3170 if ( isset( $result['isChildObj'] ) ) {
3171 $isChildObj = $result['isChildObj'];
3173 if ( isset( $result['isLocalObj'] ) ) {
3174 $isLocalObj = $result['isLocalObj'];
3179 # Finish mangling title and then check for loops.
3180 # Set $title to a Title object and $titleText to the PDBK
3183 # Split the title into page and subpage
3185 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3186 if ( $part1 !== $relative ) {
3188 $ns = $this->mTitle
->getNamespace();
3190 $title = Title
::newFromText( $part1, $ns );
3192 $titleText = $title->getPrefixedText();
3193 # Check for language variants if the template is not found
3194 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3195 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3197 # Do recursion depth check
3198 $limit = $this->mOptions
->getMaxTemplateDepth();
3199 if ( $frame->depth
>= $limit ) {
3201 $text = '<span class="error">'
3202 . wfMessage( 'parser-template-recursion-depth-warning' )
3203 ->numParams( $limit )->inContentLanguage()->text()
3209 # Load from database
3210 if ( !$found && $title ) {
3211 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3212 if ( !$title->isExternal() ) {
3213 if ( $title->isSpecialPage()
3214 && $this->mOptions
->getAllowSpecialInclusion()
3215 && $this->ot
['html']
3217 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3218 // Pass the template arguments as URL parameters.
3219 // "uselang" will have no effect since the Language object
3220 // is forced to the one defined in ParserOptions.
3222 $argsLength = $args->getLength();
3223 for ( $i = 0; $i < $argsLength; $i++
) {
3224 $bits = $args->item( $i )->splitArg();
3225 if ( strval( $bits['index'] ) === '' ) {
3226 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3227 $value = trim( $frame->expand( $bits['value'] ) );
3228 $pageArgs[$name] = $value;
3232 // Create a new context to execute the special page
3233 $context = new RequestContext
;
3234 $context->setTitle( $title );
3235 $context->setRequest( new FauxRequest( $pageArgs ) );
3236 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3237 $context->setUser( $this->getUser() );
3239 // If this page is cached, then we better not be per user.
3240 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3242 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3243 $ret = SpecialPageFactory
::capturePath(
3244 $title, $context, $this->getLinkRenderer() );
3246 $text = $context->getOutput()->getHTML();
3247 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3250 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3251 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3252 $specialPage->maxIncludeCacheTime()
3256 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3257 $found = false; # access denied
3258 wfDebug( __METHOD__
. ": template inclusion denied for " .
3259 $title->getPrefixedDBkey() . "\n" );
3261 list( $text, $title ) = $this->getTemplateDom( $title );
3262 if ( $text !== false ) {
3268 # If the title is valid but undisplayable, make a link to it
3269 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3270 $text = "[[:$titleText]]";
3273 } elseif ( $title->isTrans() ) {
3274 # Interwiki transclusion
3275 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3276 $text = $this->interwikiTransclude( $title, 'render' );
3279 $text = $this->interwikiTransclude( $title, 'raw' );
3280 # Preprocess it like a template
3281 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3287 # Do infinite loop check
3288 # This has to be done after redirect resolution to avoid infinite loops via redirects
3289 if ( !$frame->loopCheck( $title ) ) {
3291 $text = '<span class="error">'
3292 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3294 $this->addTrackingCategory( 'template-loop-category' );
3295 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3296 wfEscapeWikiText( $titleText ) )->text() );
3297 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3301 # If we haven't found text to substitute by now, we're done
3302 # Recover the source wikitext and return it
3304 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3305 if ( $profileSection ) {
3306 $this->mProfiler
->scopedProfileOut( $profileSection );
3308 return [ 'object' => $text ];
3311 # Expand DOM-style return values in a child frame
3312 if ( $isChildObj ) {
3313 # Clean up argument array
3314 $newFrame = $frame->newChild( $args, $title );
3317 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3318 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3319 # Expansion is eligible for the empty-frame cache
3320 $text = $newFrame->cachedExpand( $titleText, $text );
3322 # Uncached expansion
3323 $text = $newFrame->expand( $text );
3326 if ( $isLocalObj && $nowiki ) {
3327 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3328 $isLocalObj = false;
3331 if ( $profileSection ) {
3332 $this->mProfiler
->scopedProfileOut( $profileSection );
3335 # Replace raw HTML by a placeholder
3337 $text = $this->insertStripItem( $text );
3338 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3339 # Escape nowiki-style return values
3340 $text = wfEscapeWikiText( $text );
3341 } elseif ( is_string( $text )
3342 && !$piece['lineStart']
3343 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3345 # T2529: if the template begins with a table or block-level
3346 # element, it should be treated as beginning a new line.
3347 # This behavior is somewhat controversial.
3348 $text = "\n" . $text;
3351 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3352 # Error, oversize inclusion
3353 if ( $titleText !== false ) {
3354 # Make a working, properly escaped link if possible (T25588)
3355 $text = "[[:$titleText]]";
3357 # This will probably not be a working link, but at least it may
3358 # provide some hint of where the problem is
3359 preg_replace( '/^:/', '', $originalTitle );
3360 $text = "[[:$originalTitle]]";
3362 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3363 . 'post-expand include size too large -->' );
3364 $this->limitationWarn( 'post-expand-template-inclusion' );
3367 if ( $isLocalObj ) {
3368 $ret = [ 'object' => $text ];
3370 $ret = [ 'text' => $text ];
3377 * Call a parser function and return an array with text and flags.
3379 * The returned array will always contain a boolean 'found', indicating
3380 * whether the parser function was found or not. It may also contain the
3382 * text: string|object, resulting wikitext or PP DOM object
3383 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3384 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3385 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3386 * nowiki: bool, wiki markup in $text should be escaped
3389 * @param PPFrame $frame The current frame, contains template arguments
3390 * @param string $function Function name
3391 * @param array $args Arguments to the function
3392 * @throws MWException
3395 public function callParserFunction( $frame, $function, array $args = [] ) {
3398 # Case sensitive functions
3399 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3400 $function = $this->mFunctionSynonyms
[1][$function];
3402 # Case insensitive functions
3403 $function = $wgContLang->lc( $function );
3404 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3405 $function = $this->mFunctionSynonyms
[0][$function];
3407 return [ 'found' => false ];
3411 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3413 // Avoid PHP 7.1 warning from passing $this by reference
3416 $allArgs = [ &$parser ];
3417 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3418 # Convert arguments to PPNodes and collect for appending to $allArgs
3420 foreach ( $args as $k => $v ) {
3421 if ( $v instanceof PPNode ||
$k === 0 ) {
3424 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3428 # Add a frame parameter, and pass the arguments as an array
3429 $allArgs[] = $frame;
3430 $allArgs[] = $funcArgs;
3432 # Convert arguments to plain text and append to $allArgs
3433 foreach ( $args as $k => $v ) {
3434 if ( $v instanceof PPNode
) {
3435 $allArgs[] = trim( $frame->expand( $v ) );
3436 } elseif ( is_int( $k ) && $k >= 0 ) {
3437 $allArgs[] = trim( $v );
3439 $allArgs[] = trim( "$k=$v" );
3444 $result = $callback( ...$allArgs );
3446 # The interface for function hooks allows them to return a wikitext
3447 # string or an array containing the string and any flags. This mungs
3448 # things around to match what this method should return.
3449 if ( !is_array( $result ) ) {
3455 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3456 $result['text'] = $result[0];
3458 unset( $result[0] );
3465 $preprocessFlags = 0;
3466 if ( isset( $result['noparse'] ) ) {
3467 $noparse = $result['noparse'];
3469 if ( isset( $result['preprocessFlags'] ) ) {
3470 $preprocessFlags = $result['preprocessFlags'];
3474 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3475 $result['isChildObj'] = true;
3482 * Get the semi-parsed DOM representation of a template with a given title,
3483 * and its redirect destination title. Cached.
3485 * @param Title $title
3489 public function getTemplateDom( $title ) {
3490 $cacheTitle = $title;
3491 $titleText = $title->getPrefixedDBkey();
3493 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3494 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3495 $title = Title
::makeTitle( $ns, $dbk );
3496 $titleText = $title->getPrefixedDBkey();
3498 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3499 return [ $this->mTplDomCache
[$titleText], $title ];
3502 # Cache miss, go to the database
3503 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3505 if ( $text === false ) {
3506 $this->mTplDomCache
[$titleText] = false;
3507 return [ false, $title ];
3510 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3511 $this->mTplDomCache
[$titleText] = $dom;
3513 if ( !$title->equals( $cacheTitle ) ) {
3514 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3515 [ $title->getNamespace(), $title->getDBkey() ];
3518 return [ $dom, $title ];
3522 * Fetch the current revision of a given title. Note that the revision
3523 * (and even the title) may not exist in the database, so everything
3524 * contributing to the output of the parser should use this method
3525 * where possible, rather than getting the revisions themselves. This
3526 * method also caches its results, so using it benefits performance.
3529 * @param Title $title
3532 public function fetchCurrentRevisionOfTitle( $title ) {
3533 $cacheKey = $title->getPrefixedDBkey();
3534 if ( !$this->currentRevisionCache
) {
3535 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3537 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3538 $this->currentRevisionCache
->set( $cacheKey,
3539 // Defaults to Parser::statelessFetchRevision()
3540 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3543 return $this->currentRevisionCache
->get( $cacheKey );
3547 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3548 * without passing them on to it.
3551 * @param Title $title
3552 * @param Parser|bool $parser
3553 * @return Revision|bool False if missing
3555 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3556 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3562 * Fetch the unparsed text of a template and register a reference to it.
3563 * @param Title $title
3564 * @return array ( string or false, Title )
3566 public function fetchTemplateAndTitle( $title ) {
3567 // Defaults to Parser::statelessFetchTemplate()
3568 $templateCb = $this->mOptions
->getTemplateCallback();
3569 $stuff = call_user_func( $templateCb, $title, $this );
3570 // We use U+007F DELETE to distinguish strip markers from regular text.
3571 $text = $stuff['text'];
3572 if ( is_string( $stuff['text'] ) ) {
3573 $text = strtr( $text, "\x7f", "?" );
3575 $finalTitle = $stuff['finalTitle'] ??
$title;
3576 if ( isset( $stuff['deps'] ) ) {
3577 foreach ( $stuff['deps'] as $dep ) {
3578 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3579 if ( $dep['title']->equals( $this->getTitle() ) ) {
3580 // If we transclude ourselves, the final result
3581 // will change based on the new version of the page
3582 $this->mOutput
->setFlag( 'vary-revision' );
3586 return [ $text, $finalTitle ];
3590 * Fetch the unparsed text of a template and register a reference to it.
3591 * @param Title $title
3592 * @return string|bool
3594 public function fetchTemplate( $title ) {
3595 return $this->fetchTemplateAndTitle( $title )[0];
3599 * Static function to get a template
3600 * Can be overridden via ParserOptions::setTemplateCallback().
3602 * @param Title $title
3603 * @param bool|Parser $parser
3607 public static function statelessFetchTemplate( $title, $parser = false ) {
3608 $text = $skip = false;
3609 $finalTitle = $title;
3612 # Loop to fetch the article, with up to 1 redirect
3613 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3614 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3615 # Give extensions a chance to select the revision instead
3616 $id = false; # Assume current
3617 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3618 [ $parser, $title, &$skip, &$id ] );
3624 'page_id' => $title->getArticleID(),
3631 $rev = Revision
::newFromId( $id );
3632 } elseif ( $parser ) {
3633 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3635 $rev = Revision
::newFromTitle( $title );
3637 $rev_id = $rev ?
$rev->getId() : 0;
3638 # If there is no current revision, there is no page
3639 if ( $id === false && !$rev ) {
3640 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3641 $linkCache->addBadLinkObj( $title );
3646 'page_id' => $title->getArticleID(),
3647 'rev_id' => $rev_id ];
3648 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3649 # We fetched a rev from a different title; register it too...
3651 'title' => $rev->getTitle(),
3652 'page_id' => $rev->getPage(),
3653 'rev_id' => $rev_id ];
3657 $content = $rev->getContent();
3658 $text = $content ?
$content->getWikitextForTransclusion() : null;
3660 Hooks
::run( 'ParserFetchTemplate',
3661 [ $parser, $title, $rev, &$text, &$deps ] );
3663 if ( $text === false ||
$text === null ) {
3667 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3669 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3670 if ( !$message->exists() ) {
3674 $content = $message->content();
3675 $text = $message->plain();
3683 $finalTitle = $title;
3684 $title = $content->getRedirectTarget();
3688 'finalTitle' => $finalTitle,
3693 * Fetch a file and its title and register a reference to it.
3694 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3695 * @param Title $title
3696 * @param array $options Array of options to RepoGroup::findFile
3698 * @deprecated since 1.32, use fetchFileAndTitle instead
3700 public function fetchFile( $title, $options = [] ) {
3701 wfDeprecated( __METHOD__
, '1.32' );
3702 return $this->fetchFileAndTitle( $title, $options )[0];
3706 * Fetch a file and its title and register a reference to it.
3707 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3708 * @param Title $title
3709 * @param array $options Array of options to RepoGroup::findFile
3710 * @return array ( File or false, Title of file )
3712 public function fetchFileAndTitle( $title, $options = [] ) {
3713 $file = $this->fetchFileNoRegister( $title, $options );
3715 $time = $file ?
$file->getTimestamp() : false;
3716 $sha1 = $file ?
$file->getSha1() : false;
3717 # Register the file as a dependency...
3718 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3719 if ( $file && !$title->equals( $file->getTitle() ) ) {
3720 # Update fetched file title
3721 $title = $file->getTitle();
3722 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3724 return [ $file, $title ];
3728 * Helper function for fetchFileAndTitle.
3730 * Also useful if you need to fetch a file but not use it yet,
3731 * for example to get the file's handler.
3733 * @param Title $title
3734 * @param array $options Array of options to RepoGroup::findFile
3737 protected function fetchFileNoRegister( $title, $options = [] ) {
3738 if ( isset( $options['broken'] ) ) {
3739 $file = false; // broken thumbnail forced by hook
3740 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3741 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3742 } else { // get by (name,timestamp)
3743 $file = wfFindFile( $title, $options );
3749 * Transclude an interwiki link.
3751 * @param Title $title
3752 * @param string $action
3756 public function interwikiTransclude( $title, $action ) {
3757 global $wgEnableScaryTranscluding;
3759 if ( !$wgEnableScaryTranscluding ) {
3760 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3763 $url = $title->getFullURL( [ 'action' => $action ] );
3765 if ( strlen( $url ) > 255 ) {
3766 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3768 return $this->fetchScaryTemplateMaybeFromCache( $url );
3772 * @param string $url
3773 * @return mixed|string
3775 public function fetchScaryTemplateMaybeFromCache( $url ) {
3776 global $wgTranscludeCacheExpiry;
3777 $dbr = wfGetDB( DB_REPLICA
);
3778 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3779 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3780 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3782 return $obj->tc_contents
;
3785 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3786 $status = $req->execute(); // Status object
3787 if ( $status->isOK() ) {
3788 $text = $req->getContent();
3789 } elseif ( $req->getStatus() != 200 ) {
3790 // Though we failed to fetch the content, this status is useless.
3791 return wfMessage( 'scarytranscludefailed-httpstatus' )
3792 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3794 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3797 $dbw = wfGetDB( DB_MASTER
);
3798 $dbw->replace( 'transcache', [ 'tc_url' ], [
3800 'tc_time' => $dbw->timestamp( time() ),
3801 'tc_contents' => $text
3807 * Triple brace replacement -- used for template arguments
3810 * @param array $piece
3811 * @param PPFrame $frame
3815 public function argSubstitution( $piece, $frame ) {
3817 $parts = $piece['parts'];
3818 $nameWithSpaces = $frame->expand( $piece['title'] );
3819 $argName = trim( $nameWithSpaces );
3821 $text = $frame->getArgument( $argName );
3822 if ( $text === false && $parts->getLength() > 0
3823 && ( $this->ot
['html']
3825 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3828 # No match in frame, use the supplied default
3829 $object = $parts->item( 0 )->getChildren();
3831 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3832 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3833 $this->limitationWarn( 'post-expand-template-argument' );
3836 if ( $text === false && $object === false ) {
3838 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3840 if ( $error !== false ) {
3843 if ( $object !== false ) {
3844 $ret = [ 'object' => $object ];
3846 $ret = [ 'text' => $text ];
3853 * Return the text to be used for a given extension tag.
3854 * This is the ghost of strip().
3856 * @param array $params Associative array of parameters:
3857 * name PPNode for the tag name
3858 * attr PPNode for unparsed text where tag attributes are thought to be
3859 * attributes Optional associative array of parsed attributes
3860 * inner Contents of extension element
3861 * noClose Original text did not have a close tag
3862 * @param PPFrame $frame
3864 * @throws MWException
3867 public function extensionSubstitution( $params, $frame ) {
3868 static $errorStr = '<span class="error">';
3869 static $errorLen = 20;
3871 $name = $frame->expand( $params['name'] );
3872 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3873 // Probably expansion depth or node count exceeded. Just punt the
3878 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3879 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3884 // We can't safely check if the expansion for $content resulted in an
3885 // error, because the content could happen to be the error string
3887 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3889 $marker = self
::MARKER_PREFIX
. "-$name-"
3890 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3892 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3893 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3894 if ( $isFunctionTag ) {
3895 $markerType = 'none';
3897 $markerType = 'general';
3899 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3900 $name = strtolower( $name );
3901 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3902 if ( isset( $params['attributes'] ) ) {
3903 $attributes = $attributes +
$params['attributes'];
3906 if ( isset( $this->mTagHooks
[$name] ) ) {
3907 $output = call_user_func_array( $this->mTagHooks
[$name],
3908 [ $content, $attributes, $this, $frame ] );
3909 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3910 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3912 // Avoid PHP 7.1 warning from passing $this by reference
3914 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3916 $output = '<span class="error">Invalid tag extension name: ' .
3917 htmlspecialchars( $name ) . '</span>';
3920 if ( is_array( $output ) ) {
3923 $output = $flags[0];
3924 if ( isset( $flags['markerType'] ) ) {
3925 $markerType = $flags['markerType'];
3929 if ( is_null( $attrText ) ) {
3932 if ( isset( $params['attributes'] ) ) {
3933 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3934 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3935 htmlspecialchars( $attrValue ) . '"';
3938 if ( $content === null ) {
3939 $output = "<$name$attrText/>";
3941 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3942 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3946 $output = "<$name$attrText>$content$close";
3950 if ( $markerType === 'none' ) {
3952 } elseif ( $markerType === 'nowiki' ) {
3953 $this->mStripState
->addNoWiki( $marker, $output );
3954 } elseif ( $markerType === 'general' ) {
3955 $this->mStripState
->addGeneral( $marker, $output );
3957 throw new MWException( __METHOD__
. ': invalid marker type' );
3963 * Increment an include size counter
3965 * @param string $type The type of expansion
3966 * @param int $size The size of the text
3967 * @return bool False if this inclusion would take it over the maximum, true otherwise
3969 public function incrementIncludeSize( $type, $size ) {
3970 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3973 $this->mIncludeSizes
[$type] +
= $size;
3979 * Increment the expensive function count
3981 * @return bool False if the limit has been exceeded
3983 public function incrementExpensiveFunctionCount() {
3984 $this->mExpensiveFunctionCount++
;
3985 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3989 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3990 * Fills $this->mDoubleUnderscores, returns the modified text
3992 * @param string $text
3996 public function doDoubleUnderscore( $text ) {
3997 # The position of __TOC__ needs to be recorded
3998 $mw = $this->magicWordFactory
->get( 'toc' );
3999 if ( $mw->match( $text ) ) {
4000 $this->mShowToc
= true;
4001 $this->mForceTocPosition
= true;
4003 # Set a placeholder. At the end we'll fill it in with the TOC.
4004 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4006 # Only keep the first one.
4007 $text = $mw->replace( '', $text );
4010 # Now match and remove the rest of them
4011 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4012 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4014 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4015 $this->mOutput
->mNoGallery
= true;
4017 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4018 $this->mShowToc
= false;
4020 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4021 && $this->mTitle
->getNamespace() == NS_CATEGORY
4023 $this->addTrackingCategory( 'hidden-category-category' );
4025 # (T10068) Allow control over whether robots index a page.
4026 # __INDEX__ always overrides __NOINDEX__, see T16899
4027 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4028 $this->mOutput
->setIndexPolicy( 'noindex' );
4029 $this->addTrackingCategory( 'noindex-category' );
4031 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4032 $this->mOutput
->setIndexPolicy( 'index' );
4033 $this->addTrackingCategory( 'index-category' );
4036 # Cache all double underscores in the database
4037 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4038 $this->mOutput
->setProperty( $key, '' );
4045 * @see ParserOutput::addTrackingCategory()
4046 * @param string $msg Message key
4047 * @return bool Whether the addition was successful
4049 public function addTrackingCategory( $msg ) {
4050 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4054 * This function accomplishes several tasks:
4055 * 1) Auto-number headings if that option is enabled
4056 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4057 * 3) Add a Table of contents on the top for users who have enabled the option
4058 * 4) Auto-anchor headings
4060 * It loops through all headlines, collects the necessary data, then splits up the
4061 * string and re-inserts the newly formatted headlines.
4063 * @param string $text
4064 * @param string $origText Original, untouched wikitext
4065 * @param bool $isMain
4066 * @return mixed|string
4069 public function formatHeadings( $text, $origText, $isMain = true ) {
4070 global $wgMaxTocLevel;
4072 # Inhibit editsection links if requested in the page
4073 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4074 $maybeShowEditLink = false;
4076 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4079 # Get all headlines for numbering them and adding funky stuff like [edit]
4080 # links - this is for later, but we need the number of headlines right now
4081 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4082 # be trimmed here since whitespace in HTML headings is significant.
4084 $numMatches = preg_match_all(
4085 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4090 # if there are fewer than 4 headlines in the article, do not show TOC
4091 # unless it's been explicitly enabled.
4092 $enoughToc = $this->mShowToc
&&
4093 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4095 # Allow user to stipulate that a page should have a "new section"
4096 # link added via __NEWSECTIONLINK__
4097 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4098 $this->mOutput
->setNewSection( true );
4101 # Allow user to remove the "new section"
4102 # link via __NONEWSECTIONLINK__
4103 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4104 $this->mOutput
->hideNewSection( true );
4107 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4108 # override above conditions and always show TOC above first header
4109 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4110 $this->mShowToc
= true;
4118 # Ugh .. the TOC should have neat indentation levels which can be
4119 # passed to the skin functions. These are determined here
4123 $sublevelCount = [];
4129 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4130 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4131 $oldType = $this->mOutputType
;
4132 $this->setOutputType( self
::OT_WIKI
);
4133 $frame = $this->getPreprocessor()->newFrame();
4134 $root = $this->preprocessToDom( $origText );
4135 $node = $root->getFirstChild();
4140 $headlines = $numMatches !== false ?
$matches[3] : [];
4142 foreach ( $headlines as $headline ) {
4143 $isTemplate = false;
4145 $sectionIndex = false;
4147 $markerMatches = [];
4148 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4149 $serial = $markerMatches[1];
4150 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4151 $isTemplate = ( $titleText != $baseTitleText );
4152 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4156 $prevlevel = $level;
4158 $level = $matches[1][$headlineCount];
4160 if ( $level > $prevlevel ) {
4161 # Increase TOC level
4163 $sublevelCount[$toclevel] = 0;
4164 if ( $toclevel < $wgMaxTocLevel ) {
4165 $prevtoclevel = $toclevel;
4166 $toc .= Linker
::tocIndent();
4169 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4170 # Decrease TOC level, find level to jump to
4172 for ( $i = $toclevel; $i > 0; $i-- ) {
4173 if ( $levelCount[$i] == $level ) {
4174 # Found last matching level
4177 } elseif ( $levelCount[$i] < $level ) {
4178 # Found first matching level below current level
4186 if ( $toclevel < $wgMaxTocLevel ) {
4187 if ( $prevtoclevel < $wgMaxTocLevel ) {
4188 # Unindent only if the previous toc level was shown :p
4189 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4190 $prevtoclevel = $toclevel;
4192 $toc .= Linker
::tocLineEnd();
4196 # No change in level, end TOC line
4197 if ( $toclevel < $wgMaxTocLevel ) {
4198 $toc .= Linker
::tocLineEnd();
4202 $levelCount[$toclevel] = $level;
4204 # count number of headlines for each level
4205 $sublevelCount[$toclevel]++
;
4207 for ( $i = 1; $i <= $toclevel; $i++
) {
4208 if ( !empty( $sublevelCount[$i] ) ) {
4212 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4217 # The safe header is a version of the header text safe to use for links
4219 # Remove link placeholders by the link text.
4220 # <!--LINK number-->
4222 # link text with suffix
4223 # Do this before unstrip since link text can contain strip markers
4224 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4226 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4227 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4229 # Remove any <style> or <script> tags (T198618)
4230 $safeHeadline = preg_replace(
4231 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4236 # Strip out HTML (first regex removes any tag not allowed)
4238 # * <sup> and <sub> (T10393)
4242 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4243 # * <s> and <strike> (T35715)
4244 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4245 # to allow setting directionality in toc items.
4246 $tocline = preg_replace(
4248 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4249 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4255 # Strip '<span></span>', which is the result from the above if
4256 # <span id="foo"></span> is used to produce an additional anchor
4258 $tocline = str_replace( '<span></span>', '', $tocline );
4260 $tocline = trim( $tocline );
4262 # For the anchor, strip out HTML-y stuff period
4263 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4264 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4266 # Save headline for section edit hint before it's escaped
4267 $headlineHint = $safeHeadline;
4269 # Decode HTML entities
4270 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4272 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4274 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4275 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4276 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4277 if ( $fallbackHeadline === $safeHeadline ) {
4278 # No reason to have both (in fact, we can't)
4279 $fallbackHeadline = false;
4282 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4283 # @todo FIXME: We may be changing them depending on the current locale.
4284 $arrayKey = strtolower( $safeHeadline );
4285 if ( $fallbackHeadline === false ) {
4286 $fallbackArrayKey = false;
4288 $fallbackArrayKey = strtolower( $fallbackHeadline );
4291 # Create the anchor for linking from the TOC to the section
4292 $anchor = $safeHeadline;
4293 $fallbackAnchor = $fallbackHeadline;
4294 if ( isset( $refers[$arrayKey] ) ) {
4295 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4296 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4298 $linkAnchor .= "_$i";
4299 $refers["${arrayKey}_$i"] = true;
4301 $refers[$arrayKey] = true;
4303 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4304 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4305 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4306 $fallbackAnchor .= "_$i";
4307 $refers["${fallbackArrayKey}_$i"] = true;
4309 $refers[$fallbackArrayKey] = true;
4312 # Don't number the heading if it is the only one (looks silly)
4313 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4314 # the two are different if the line contains a link
4315 $headline = Html
::element(
4317 [ 'class' => 'mw-headline-number' ],
4319 ) . ' ' . $headline;
4322 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4323 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4324 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4327 # Add the section to the section tree
4328 # Find the DOM node for this header
4329 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4330 while ( $node && !$noOffset ) {
4331 if ( $node->getName() === 'h' ) {
4332 $bits = $node->splitHeading();
4333 if ( $bits['i'] == $sectionIndex ) {
4337 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4338 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4339 $node = $node->getNextSibling();
4342 'toclevel' => $toclevel,
4345 'number' => $numbering,
4346 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4347 'fromtitle' => $titleText,
4348 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4349 'anchor' => $anchor,
4352 # give headline the correct <h#> tag
4353 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4354 // Output edit section links as markers with styles that can be customized by skins
4355 if ( $isTemplate ) {
4356 # Put a T flag in the section identifier, to indicate to extractSections()
4357 # that sections inside <includeonly> should be counted.
4358 $editsectionPage = $titleText;
4359 $editsectionSection = "T-$sectionIndex";
4360 $editsectionContent = null;
4362 $editsectionPage = $this->mTitle
->getPrefixedText();
4363 $editsectionSection = $sectionIndex;
4364 $editsectionContent = $headlineHint;
4366 // We use a bit of pesudo-xml for editsection markers. The
4367 // language converter is run later on. Using a UNIQ style marker
4368 // leads to the converter screwing up the tokens when it
4369 // converts stuff. And trying to insert strip tags fails too. At
4370 // this point all real inputted tags have already been escaped,
4371 // so we don't have to worry about a user trying to input one of
4372 // these markers directly. We use a page and section attribute
4373 // to stop the language converter from converting these
4374 // important bits of data, but put the headline hint inside a
4375 // content block because the language converter is supposed to
4376 // be able to convert that piece of data.
4377 // Gets replaced with html in ParserOutput::getText
4378 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4379 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4380 if ( $editsectionContent !== null ) {
4381 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4388 $head[$headlineCount] = Linker
::makeHeadline( $level,
4389 $matches['attrib'][$headlineCount], $anchor, $headline,
4390 $editlink, $fallbackAnchor );
4395 $this->setOutputType( $oldType );
4397 # Never ever show TOC if no headers
4398 if ( $numVisible < 1 ) {
4403 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4404 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4406 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4407 $this->mOutput
->setTOCHTML( $toc );
4408 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4412 $this->mOutput
->setSections( $tocraw );
4415 # split up and insert constructed headlines
4416 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4419 // build an array of document sections
4421 foreach ( $blocks as $block ) {
4422 // $head is zero-based, sections aren't.
4423 if ( empty( $head[$i - 1] ) ) {
4424 $sections[$i] = $block;
4426 $sections[$i] = $head[$i - 1] . $block;
4430 * Send a hook, one per section.
4431 * The idea here is to be able to make section-level DIVs, but to do so in a
4432 * lower-impact, more correct way than r50769
4435 * $section : the section number
4436 * &$sectionContent : ref to the content of the section
4437 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4439 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4444 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4445 // append the TOC at the beginning
4446 // Top anchor now in skin
4447 $sections[0] = $sections[0] . $toc . "\n";
4450 $full .= implode( '', $sections );
4452 if ( $this->mForceTocPosition
) {
4453 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4460 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4461 * conversion, substituting signatures, {{subst:}} templates, etc.
4463 * @param string $text The text to transform
4464 * @param Title $title The Title object for the current article
4465 * @param User $user The User object describing the current user
4466 * @param ParserOptions $options Parsing options
4467 * @param bool $clearState Whether to clear the parser state first
4468 * @return string The altered wiki markup
4470 public function preSaveTransform( $text, Title
$title, User
$user,
4471 ParserOptions
$options, $clearState = true
4473 if ( $clearState ) {
4474 $magicScopeVariable = $this->lock();
4476 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4477 $this->setUser( $user );
4479 // Strip U+0000 NULL (T159174)
4480 $text = str_replace( "\000", '', $text );
4482 // We still normalize line endings for backwards-compatibility
4483 // with other code that just calls PST, but this should already
4484 // be handled in TextContent subclasses
4485 $text = TextContent
::normalizeLineEndings( $text );
4487 if ( $options->getPreSaveTransform() ) {
4488 $text = $this->pstPass2( $text, $user );
4490 $text = $this->mStripState
->unstripBoth( $text );
4492 $this->setUser( null ); # Reset
4498 * Pre-save transform helper function
4500 * @param string $text
4505 private function pstPass2( $text, $user ) {
4508 # Note: This is the timestamp saved as hardcoded wikitext to
4509 # the database, we use $wgContLang here in order to give
4510 # everyone the same signature and use the default one rather
4511 # than the one selected in each user's preferences.
4513 $ts = $this->mOptions
->getTimestamp();
4514 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4515 $ts = $timestamp->format( 'YmdHis' );
4516 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4518 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4520 # Variable replacement
4521 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4522 $text = $this->replaceVariables( $text );
4524 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4525 # which may corrupt this parser instance via its wfMessage()->text() call-
4528 if ( strpos( $text, '~~~' ) !== false ) {
4529 $sigText = $this->getUserSig( $user );
4530 $text = strtr( $text, [
4532 '~~~~' => "$sigText $d",
4535 # The main two signature forms used above are time-sensitive
4536 $this->mOutput
->setFlag( 'user-signature' );
4539 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4540 $tc = '[' . Title
::legalChars() . ']';
4541 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4543 // [[ns:page (context)|]]
4544 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4545 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4546 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4547 // [[ns:page (context), context|]] (using either single or double-width comma)
4548 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4549 // [[|page]] (reverse pipe trick: add context from page title)
4550 $p2 = "/\[\[\\|($tc+)]]/";
4552 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4553 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4554 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4555 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4557 $t = $this->mTitle
->getText();
4559 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4560 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4561 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4562 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4564 # if there's no context, don't bother duplicating the title
4565 $text = preg_replace( $p2, '[[\\1]]', $text );
4572 * Fetch the user's signature text, if any, and normalize to
4573 * validated, ready-to-insert wikitext.
4574 * If you have pre-fetched the nickname or the fancySig option, you can
4575 * specify them here to save a database query.
4576 * Do not reuse this parser instance after calling getUserSig(),
4577 * as it may have changed if it's the $wgParser.
4579 * @param User &$user
4580 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4581 * @param bool|null $fancySig whether the nicknname is the complete signature
4582 * or null to use default value
4585 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4586 global $wgMaxSigChars;
4588 $username = $user->getName();
4590 # If not given, retrieve from the user object.
4591 if ( $nickname === false ) {
4592 $nickname = $user->getOption( 'nickname' );
4595 if ( is_null( $fancySig ) ) {
4596 $fancySig = $user->getBoolOption( 'fancysig' );
4599 $nickname = $nickname == null ?
$username : $nickname;
4601 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4602 $nickname = $username;
4603 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4604 } elseif ( $fancySig !== false ) {
4605 # Sig. might contain markup; validate this
4606 if ( $this->validateSig( $nickname ) !== false ) {
4607 # Validated; clean up (if needed) and return it
4608 return $this->cleanSig( $nickname, true );
4610 # Failed to validate; fall back to the default
4611 $nickname = $username;
4612 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4616 # Make sure nickname doesnt get a sig in a sig
4617 $nickname = self
::cleanSigInSig( $nickname );
4619 # If we're still here, make it a link to the user page
4620 $userText = wfEscapeWikiText( $username );
4621 $nickText = wfEscapeWikiText( $nickname );
4622 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4624 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4625 ->title( $this->getTitle() )->text();
4629 * Check that the user's signature contains no bad XML
4631 * @param string $text
4632 * @return string|bool An expanded string, or false if invalid.
4634 public function validateSig( $text ) {
4635 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4639 * Clean up signature text
4641 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4642 * 2) Substitute all transclusions
4644 * @param string $text
4645 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4646 * @return string Signature text
4648 public function cleanSig( $text, $parsing = false ) {
4651 $magicScopeVariable = $this->lock();
4652 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4655 # Option to disable this feature
4656 if ( !$this->mOptions
->getCleanSignatures() ) {
4660 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4661 # => Move this logic to braceSubstitution()
4662 $substWord = $this->magicWordFactory
->get( 'subst' );
4663 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4664 $substText = '{{' . $substWord->getSynonym( 0 );
4666 $text = preg_replace( $substRegex, $substText, $text );
4667 $text = self
::cleanSigInSig( $text );
4668 $dom = $this->preprocessToDom( $text );
4669 $frame = $this->getPreprocessor()->newFrame();
4670 $text = $frame->expand( $dom );
4673 $text = $this->mStripState
->unstripBoth( $text );
4680 * Strip 3, 4 or 5 tildes out of signatures.
4682 * @param string $text
4683 * @return string Signature text with /~{3,5}/ removed
4685 public static function cleanSigInSig( $text ) {
4686 $text = preg_replace( '/~{3,5}/', '', $text );
4691 * Set up some variables which are usually set up in parse()
4692 * so that an external function can call some class members with confidence
4694 * @param Title|null $title
4695 * @param ParserOptions $options
4696 * @param int $outputType
4697 * @param bool $clearState
4699 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4700 $outputType, $clearState = true
4702 $this->startParse( $title, $options, $outputType, $clearState );
4706 * @param Title|null $title
4707 * @param ParserOptions $options
4708 * @param int $outputType
4709 * @param bool $clearState
4711 private function startParse( Title
$title = null, ParserOptions
$options,
4712 $outputType, $clearState = true
4714 $this->setTitle( $title );
4715 $this->mOptions
= $options;
4716 $this->setOutputType( $outputType );
4717 if ( $clearState ) {
4718 $this->clearState();
4723 * Wrapper for preprocess()
4725 * @param string $text The text to preprocess
4726 * @param ParserOptions $options
4727 * @param Title|null $title Title object or null to use $wgTitle
4730 public function transformMsg( $text, $options, $title = null ) {
4731 static $executing = false;
4733 # Guard against infinite recursion
4744 $text = $this->preprocess( $text, $title, $options );
4751 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4752 * The callback should have the following form:
4753 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4755 * Transform and return $text. Use $parser for any required context, e.g. use
4756 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4758 * Hooks may return extended information by returning an array, of which the
4759 * first numbered element (index 0) must be the return string, and all other
4760 * entries are extracted into local variables within an internal function
4761 * in the Parser class.
4763 * This interface (introduced r61913) appears to be undocumented, but
4764 * 'markerType' is used by some core tag hooks to override which strip
4765 * array their results are placed in. **Use great caution if attempting
4766 * this interface, as it is not documented and injudicious use could smash
4767 * private variables.**
4769 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4770 * @param callable $callback The callback function (and object) to use for the tag
4771 * @throws MWException
4772 * @return callable|null The old value of the mTagHooks array associated with the hook
4774 public function setHook( $tag, callable
$callback ) {
4775 $tag = strtolower( $tag );
4776 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4777 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4779 $oldVal = $this->mTagHooks
[$tag] ??
null;
4780 $this->mTagHooks
[$tag] = $callback;
4781 if ( !in_array( $tag, $this->mStripList
) ) {
4782 $this->mStripList
[] = $tag;
4789 * As setHook(), but letting the contents be parsed.
4791 * Transparent tag hooks are like regular XML-style tag hooks, except they
4792 * operate late in the transformation sequence, on HTML instead of wikitext.
4794 * This is probably obsoleted by things dealing with parser frames?
4795 * The only extension currently using it is geoserver.
4798 * @todo better document or deprecate this
4800 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4801 * @param callable $callback The callback function (and object) to use for the tag
4802 * @throws MWException
4803 * @return callable|null The old value of the mTagHooks array associated with the hook
4805 public function setTransparentTagHook( $tag, callable
$callback ) {
4806 $tag = strtolower( $tag );
4807 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4808 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4810 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4811 $this->mTransparentTagHooks
[$tag] = $callback;
4817 * Remove all tag hooks
4819 public function clearTagHooks() {
4820 $this->mTagHooks
= [];
4821 $this->mFunctionTagHooks
= [];
4822 $this->mStripList
= $this->mDefaultStripList
;
4826 * Create a function, e.g. {{sum:1|2|3}}
4827 * The callback function should have the form:
4828 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4830 * Or with Parser::SFH_OBJECT_ARGS:
4831 * function myParserFunction( $parser, $frame, $args ) { ... }
4833 * The callback may either return the text result of the function, or an array with the text
4834 * in element 0, and a number of flags in the other elements. The names of the flags are
4835 * specified in the keys. Valid flags are:
4836 * found The text returned is valid, stop processing the template. This
4838 * nowiki Wiki markup in the return value should be escaped
4839 * isHTML The returned text is HTML, armour it against wikitext transformation
4841 * @param string $id The magic word ID
4842 * @param callable $callback The callback function (and object) to use
4843 * @param int $flags A combination of the following flags:
4844 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4846 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4847 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4848 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4849 * the arguments, and to control the way they are expanded.
4851 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4852 * arguments, for instance:
4853 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4855 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4856 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4857 * working if/when this is changed.
4859 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4862 * Please read the documentation in includes/parser/Preprocessor.php for more information
4863 * about the methods available in PPFrame and PPNode.
4865 * @throws MWException
4866 * @return string|callable The old callback function for this name, if any
4868 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4871 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4872 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4874 # Add to function cache
4875 $mw = $this->magicWordFactory
->get( $id );
4877 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4880 $synonyms = $mw->getSynonyms();
4881 $sensitive = intval( $mw->isCaseSensitive() );
4883 foreach ( $synonyms as $syn ) {
4885 if ( !$sensitive ) {
4886 $syn = $wgContLang->lc( $syn );
4889 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4892 # Remove trailing colon
4893 if ( substr( $syn, -1, 1 ) === ':' ) {
4894 $syn = substr( $syn, 0, -1 );
4896 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4902 * Get all registered function hook identifiers
4906 public function getFunctionHooks() {
4907 return array_keys( $this->mFunctionHooks
);
4911 * Create a tag function, e.g. "<test>some stuff</test>".
4912 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4913 * Unlike parser functions, their content is not preprocessed.
4914 * @param string $tag
4915 * @param callable $callback
4917 * @throws MWException
4920 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4921 $tag = strtolower( $tag );
4922 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4923 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4925 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4926 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4928 if ( !in_array( $tag, $this->mStripList
) ) {
4929 $this->mStripList
[] = $tag;
4936 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4937 * Placeholders created in Linker::link()
4939 * @param string &$text
4940 * @param int $options
4942 public function replaceLinkHolders( &$text, $options = 0 ) {
4943 $this->mLinkHolders
->replace( $text );
4947 * Replace "<!--LINK-->" link placeholders with plain text of links
4948 * (not HTML-formatted).
4950 * @param string $text
4953 public function replaceLinkHoldersText( $text ) {
4954 return $this->mLinkHolders
->replaceText( $text );
4958 * Renders an image gallery from a text with one line per image.
4959 * text labels may be given by using |-style alternative text. E.g.
4960 * Image:one.jpg|The number "1"
4961 * Image:tree.jpg|A tree
4962 * given as text will return the HTML of a gallery with two images,
4963 * labeled 'The number "1"' and
4966 * @param string $text
4967 * @param array $params
4968 * @return string HTML
4970 public function renderImageGallery( $text, $params ) {
4972 if ( isset( $params['mode'] ) ) {
4973 $mode = $params['mode'];
4977 $ig = ImageGalleryBase
::factory( $mode );
4978 } catch ( Exception
$e ) {
4979 // If invalid type set, fallback to default.
4980 $ig = ImageGalleryBase
::factory( false );
4983 $ig->setContextTitle( $this->mTitle
);
4984 $ig->setShowBytes( false );
4985 $ig->setShowDimensions( false );
4986 $ig->setShowFilename( false );
4987 $ig->setParser( $this );
4988 $ig->setHideBadImages();
4989 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
4991 if ( isset( $params['showfilename'] ) ) {
4992 $ig->setShowFilename( true );
4994 $ig->setShowFilename( false );
4996 if ( isset( $params['caption'] ) ) {
4997 $caption = $params['caption'];
4998 $caption = htmlspecialchars( $caption );
4999 $caption = $this->replaceInternalLinks( $caption );
5000 $ig->setCaptionHtml( $caption );
5002 if ( isset( $params['perrow'] ) ) {
5003 $ig->setPerRow( $params['perrow'] );
5005 if ( isset( $params['widths'] ) ) {
5006 $ig->setWidths( $params['widths'] );
5008 if ( isset( $params['heights'] ) ) {
5009 $ig->setHeights( $params['heights'] );
5011 $ig->setAdditionalOptions( $params );
5013 // Avoid PHP 7.1 warning from passing $this by reference
5015 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5017 $lines = StringUtils
::explode( "\n", $text );
5018 foreach ( $lines as $line ) {
5019 # match lines like these:
5020 # Image:someimage.jpg|This is some image
5022 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5024 if ( count( $matches ) == 0 ) {
5028 if ( strpos( $matches[0], '%' ) !== false ) {
5029 $matches[1] = rawurldecode( $matches[1] );
5031 $title = Title
::newFromText( $matches[1], NS_FILE
);
5032 if ( is_null( $title ) ) {
5033 # Bogus title. Ignore these so we don't bomb out later.
5037 # We need to get what handler the file uses, to figure out parameters.
5038 # Note, a hook can overide the file name, and chose an entirely different
5039 # file (which potentially could be of a different type and have different handler).
5042 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5043 [ $this, $title, &$options, &$descQuery ] );
5044 # Don't register it now, as TraditionalImageGallery does that later.
5045 $file = $this->fetchFileNoRegister( $title, $options );
5046 $handler = $file ?
$file->getHandler() : false;
5049 'img_alt' => 'gallery-internal-alt',
5050 'img_link' => 'gallery-internal-link',
5053 $paramMap = $paramMap +
$handler->getParamMap();
5054 // We don't want people to specify per-image widths.
5055 // Additionally the width parameter would need special casing anyhow.
5056 unset( $paramMap['img_width'] );
5059 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5064 $handlerOptions = [];
5065 if ( isset( $matches[3] ) ) {
5066 // look for an |alt= definition while trying not to break existing
5067 // captions with multiple pipes (|) in it, until a more sensible grammar
5068 // is defined for images in galleries
5070 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5071 // splitting on '|' is a bit odd, and different from makeImage.
5072 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5073 // Protect LanguageConverter markup
5074 $parameterMatches = StringUtils
::delimiterExplode(
5075 '-{', '}-', '|', $matches[3], true /* nested */
5078 foreach ( $parameterMatches as $parameterMatch ) {
5079 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5081 $paramName = $paramMap[$magicName];
5083 switch ( $paramName ) {
5084 case 'gallery-internal-alt':
5085 $alt = $this->stripAltText( $match, false );
5087 case 'gallery-internal-link':
5088 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5089 $chars = self
::EXT_LINK_URL_CLASS
;
5090 $addr = self
::EXT_LINK_ADDR
;
5091 $prots = $this->mUrlProtocols
;
5092 // check to see if link matches an absolute url, if not then it must be a wiki link.
5093 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5094 // Result of LanguageConverter::markNoConversion
5095 // invoked on an external link.
5096 $linkValue = substr( $linkValue, 4, -2 );
5098 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5100 $this->mOutput
->addExternalLink( $link );
5102 $localLinkTitle = Title
::newFromText( $linkValue );
5103 if ( $localLinkTitle !== null ) {
5104 $this->mOutput
->addLink( $localLinkTitle );
5105 $link = $localLinkTitle->getLinkURL();
5110 // Must be a handler specific parameter.
5111 if ( $handler->validateParam( $paramName, $match ) ) {
5112 $handlerOptions[$paramName] = $match;
5114 // Guess not, consider it as caption.
5115 wfDebug( "$parameterMatch failed parameter validation\n" );
5116 $label = $parameterMatch;
5122 $label = $parameterMatch;
5127 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5129 $html = $ig->toHTML();
5130 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5135 * @param MediaHandler $handler
5138 public function getImageParams( $handler ) {
5140 $handlerClass = get_class( $handler );
5144 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5145 # Initialise static lists
5146 static $internalParamNames = [
5147 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5148 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5149 'bottom', 'text-bottom' ],
5150 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5151 'upright', 'border', 'link', 'alt', 'class' ],
5153 static $internalParamMap;
5154 if ( !$internalParamMap ) {
5155 $internalParamMap = [];
5156 foreach ( $internalParamNames as $type => $names ) {
5157 foreach ( $names as $name ) {
5158 // For grep: img_left, img_right, img_center, img_none,
5159 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5160 // img_bottom, img_text_bottom,
5161 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5162 // img_border, img_link, img_alt, img_class
5163 $magicName = str_replace( '-', '_', "img_$name" );
5164 $internalParamMap[$magicName] = [ $type, $name ];
5169 # Add handler params
5170 $paramMap = $internalParamMap;
5172 $handlerParamMap = $handler->getParamMap();
5173 foreach ( $handlerParamMap as $magic => $paramName ) {
5174 $paramMap[$magic] = [ 'handler', $paramName ];
5177 $this->mImageParams
[$handlerClass] = $paramMap;
5178 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5180 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5184 * Parse image options text and use it to make an image
5186 * @param Title $title
5187 * @param string $options
5188 * @param LinkHolderArray|bool $holders
5189 * @return string HTML
5191 public function makeImage( $title, $options, $holders = false ) {
5192 # Check if the options text is of the form "options|alt text"
5194 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5195 # * left no resizing, just left align. label is used for alt= only
5196 # * right same, but right aligned
5197 # * none same, but not aligned
5198 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5199 # * center center the image
5200 # * frame Keep original image size, no magnify-button.
5201 # * framed Same as "frame"
5202 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5203 # * upright reduce width for upright images, rounded to full __0 px
5204 # * border draw a 1px border around the image
5205 # * alt Text for HTML alt attribute (defaults to empty)
5206 # * class Set a class for img node
5207 # * link Set the target of the image link. Can be external, interwiki, or local
5208 # vertical-align values (no % or length right now):
5218 # Protect LanguageConverter markup when splitting into parts
5219 $parts = StringUtils
::delimiterExplode(
5220 '-{', '}-', '|', $options, true /* allow nesting */
5223 # Give extensions a chance to select the file revision for us
5226 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5227 [ $this, $title, &$options, &$descQuery ] );
5228 # Fetch and register the file (file title may be different via hooks)
5229 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5232 $handler = $file ?
$file->getHandler() : false;
5234 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5237 $this->addTrackingCategory( 'broken-file-category' );
5240 # Process the input parameters
5242 $params = [ 'frame' => [], 'handler' => [],
5243 'horizAlign' => [], 'vertAlign' => [] ];
5244 $seenformat = false;
5245 foreach ( $parts as $part ) {
5246 $part = trim( $part );
5247 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5249 if ( isset( $paramMap[$magicName] ) ) {
5250 list( $type, $paramName ) = $paramMap[$magicName];
5252 # Special case; width and height come in one variable together
5253 if ( $type === 'handler' && $paramName === 'width' ) {
5254 $parsedWidthParam = self
::parseWidthParam( $value );
5255 if ( isset( $parsedWidthParam['width'] ) ) {
5256 $width = $parsedWidthParam['width'];
5257 if ( $handler->validateParam( 'width', $width ) ) {
5258 $params[$type]['width'] = $width;
5262 if ( isset( $parsedWidthParam['height'] ) ) {
5263 $height = $parsedWidthParam['height'];
5264 if ( $handler->validateParam( 'height', $height ) ) {
5265 $params[$type]['height'] = $height;
5269 # else no validation -- T15436
5271 if ( $type === 'handler' ) {
5272 # Validate handler parameter
5273 $validated = $handler->validateParam( $paramName, $value );
5275 # Validate internal parameters
5276 switch ( $paramName ) {
5280 # @todo FIXME: Possibly check validity here for
5281 # manualthumb? downstream behavior seems odd with
5282 # missing manual thumbs.
5284 $value = $this->stripAltText( $value, $holders );
5287 $chars = self
::EXT_LINK_URL_CLASS
;
5288 $addr = self
::EXT_LINK_ADDR
;
5289 $prots = $this->mUrlProtocols
;
5290 if ( $value === '' ) {
5291 $paramName = 'no-link';
5294 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5295 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5296 $paramName = 'link-url';
5297 $this->mOutput
->addExternalLink( $value );
5298 if ( $this->mOptions
->getExternalLinkTarget() ) {
5299 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5304 $linkTitle = Title
::newFromText( $value );
5306 $paramName = 'link-title';
5307 $value = $linkTitle;
5308 $this->mOutput
->addLink( $linkTitle );
5316 // use first appearing option, discard others.
5317 $validated = !$seenformat;
5321 # Most other things appear to be empty or numeric...
5322 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5327 $params[$type][$paramName] = $value;
5331 if ( !$validated ) {
5336 # Process alignment parameters
5337 if ( $params['horizAlign'] ) {
5338 $params['frame']['align'] = key( $params['horizAlign'] );
5340 if ( $params['vertAlign'] ) {
5341 $params['frame']['valign'] = key( $params['vertAlign'] );
5344 $params['frame']['caption'] = $caption;
5346 # Will the image be presented in a frame, with the caption below?
5347 $imageIsFramed = isset( $params['frame']['frame'] )
5348 ||
isset( $params['frame']['framed'] )
5349 ||
isset( $params['frame']['thumbnail'] )
5350 ||
isset( $params['frame']['manualthumb'] );
5352 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5353 # came to also set the caption, ordinary text after the image -- which
5354 # makes no sense, because that just repeats the text multiple times in
5355 # screen readers. It *also* came to set the title attribute.
5356 # Now that we have an alt attribute, we should not set the alt text to
5357 # equal the caption: that's worse than useless, it just repeats the
5358 # text. This is the framed/thumbnail case. If there's no caption, we
5359 # use the unnamed parameter for alt text as well, just for the time be-
5360 # ing, if the unnamed param is set and the alt param is not.
5361 # For the future, we need to figure out if we want to tweak this more,
5362 # e.g., introducing a title= parameter for the title; ignoring the un-
5363 # named parameter entirely for images without a caption; adding an ex-
5364 # plicit caption= parameter and preserving the old magic unnamed para-
5366 if ( $imageIsFramed ) { # Framed image
5367 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5368 # No caption or alt text, add the filename as the alt text so
5369 # that screen readers at least get some description of the image
5370 $params['frame']['alt'] = $title->getText();
5372 # Do not set $params['frame']['title'] because tooltips don't make sense
5374 } else { # Inline image
5375 if ( !isset( $params['frame']['alt'] ) ) {
5376 # No alt text, use the "caption" for the alt text
5377 if ( $caption !== '' ) {
5378 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5380 # No caption, fall back to using the filename for the
5382 $params['frame']['alt'] = $title->getText();
5385 # Use the "caption" for the tooltip text
5386 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5389 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5391 # Linker does the rest
5392 $time = $options['time'] ??
false;
5393 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5394 $time, $descQuery, $this->mOptions
->getThumbSize() );
5396 # Give the handler a chance to modify the parser object
5398 $handler->parserTransformHook( $this, $file );
5405 * @param string $caption
5406 * @param LinkHolderArray|bool $holders
5407 * @return mixed|string
5409 protected function stripAltText( $caption, $holders ) {
5410 # Strip bad stuff out of the title (tooltip). We can't just use
5411 # replaceLinkHoldersText() here, because if this function is called
5412 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5414 $tooltip = $holders->replaceText( $caption );
5416 $tooltip = $this->replaceLinkHoldersText( $caption );
5419 # make sure there are no placeholders in thumbnail attributes
5420 # that are later expanded to html- so expand them now and
5422 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5423 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5429 * Set a flag in the output object indicating that the content is dynamic and
5430 * shouldn't be cached.
5431 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5433 public function disableCache() {
5434 wfDebug( "Parser output marked as uncacheable.\n" );
5435 if ( !$this->mOutput
) {
5436 throw new MWException( __METHOD__
.
5437 " can only be called when actually parsing something" );
5439 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5443 * Callback from the Sanitizer for expanding items found in HTML attribute
5444 * values, so they can be safely tested and escaped.
5446 * @param string &$text
5447 * @param bool|PPFrame $frame
5450 public function attributeStripCallback( &$text, $frame = false ) {
5451 $text = $this->replaceVariables( $text, $frame );
5452 $text = $this->mStripState
->unstripBoth( $text );
5461 public function getTags() {
5463 array_keys( $this->mTransparentTagHooks
),
5464 array_keys( $this->mTagHooks
),
5465 array_keys( $this->mFunctionTagHooks
)
5470 * Replace transparent tags in $text with the values given by the callbacks.
5472 * Transparent tag hooks are like regular XML-style tag hooks, except they
5473 * operate late in the transformation sequence, on HTML instead of wikitext.
5475 * @param string $text
5479 public function replaceTransparentTags( $text ) {
5481 $elements = array_keys( $this->mTransparentTagHooks
);
5482 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5485 foreach ( $matches as $marker => $data ) {
5486 list( $element, $content, $params, $tag ) = $data;
5487 $tagName = strtolower( $element );
5488 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5489 $output = call_user_func_array(
5490 $this->mTransparentTagHooks
[$tagName],
5491 [ $content, $params, $this ]
5496 $replacements[$marker] = $output;
5498 return strtr( $text, $replacements );
5502 * Break wikitext input into sections, and either pull or replace
5503 * some particular section's text.
5505 * External callers should use the getSection and replaceSection methods.
5507 * @param string $text Page wikitext
5508 * @param string|int $sectionId A section identifier string of the form:
5509 * "<flag1> - <flag2> - ... - <section number>"
5511 * Currently the only recognised flag is "T", which means the target section number
5512 * was derived during a template inclusion parse, in other words this is a template
5513 * section edit link. If no flags are given, it was an ordinary section edit link.
5514 * This flag is required to avoid a section numbering mismatch when a section is
5515 * enclosed by "<includeonly>" (T8563).
5517 * The section number 0 pulls the text before the first heading; other numbers will
5518 * pull the given section along with its lower-level subsections. If the section is
5519 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5521 * Section 0 is always considered to exist, even if it only contains the empty
5522 * string. If $text is the empty string and section 0 is replaced, $newText is
5525 * @param string $mode One of "get" or "replace"
5526 * @param string $newText Replacement text for section data.
5527 * @return string For "get", the extracted section text.
5528 * for "replace", the whole page with the section replaced.
5530 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5531 global $wgTitle; # not generally used but removes an ugly failure mode
5533 $magicScopeVariable = $this->lock();
5534 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5536 $frame = $this->getPreprocessor()->newFrame();
5538 # Process section extraction flags
5540 $sectionParts = explode( '-', $sectionId );
5541 $sectionIndex = array_pop( $sectionParts );
5542 foreach ( $sectionParts as $part ) {
5543 if ( $part === 'T' ) {
5544 $flags |
= self
::PTD_FOR_INCLUSION
;
5548 # Check for empty input
5549 if ( strval( $text ) === '' ) {
5550 # Only sections 0 and T-0 exist in an empty document
5551 if ( $sectionIndex == 0 ) {
5552 if ( $mode === 'get' ) {
5558 if ( $mode === 'get' ) {
5566 # Preprocess the text
5567 $root = $this->preprocessToDom( $text, $flags );
5569 # <h> nodes indicate section breaks
5570 # They can only occur at the top level, so we can find them by iterating the root's children
5571 $node = $root->getFirstChild();
5573 # Find the target section
5574 if ( $sectionIndex == 0 ) {
5575 # Section zero doesn't nest, level=big
5576 $targetLevel = 1000;
5579 if ( $node->getName() === 'h' ) {
5580 $bits = $node->splitHeading();
5581 if ( $bits['i'] == $sectionIndex ) {
5582 $targetLevel = $bits['level'];
5586 if ( $mode === 'replace' ) {
5587 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5589 $node = $node->getNextSibling();
5595 if ( $mode === 'get' ) {
5602 # Find the end of the section, including nested sections
5604 if ( $node->getName() === 'h' ) {
5605 $bits = $node->splitHeading();
5606 $curLevel = $bits['level'];
5607 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5611 if ( $mode === 'get' ) {
5612 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5614 $node = $node->getNextSibling();
5617 # Write out the remainder (in replace mode only)
5618 if ( $mode === 'replace' ) {
5619 # Output the replacement text
5620 # Add two newlines on -- trailing whitespace in $newText is conventionally
5621 # stripped by the editor, so we need both newlines to restore the paragraph gap
5622 # Only add trailing whitespace if there is newText
5623 if ( $newText != "" ) {
5624 $outText .= $newText . "\n\n";
5628 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5629 $node = $node->getNextSibling();
5633 if ( is_string( $outText ) ) {
5634 # Re-insert stripped tags
5635 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5642 * This function returns the text of a section, specified by a number ($section).
5643 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5644 * the first section before any such heading (section 0).
5646 * If a section contains subsections, these are also returned.
5648 * @param string $text Text to look in
5649 * @param string|int $sectionId Section identifier as a number or string
5650 * (e.g. 0, 1 or 'T-1').
5651 * @param string $defaultText Default to return if section is not found
5653 * @return string Text of the requested section
5655 public function getSection( $text, $sectionId, $defaultText = '' ) {
5656 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5660 * This function returns $oldtext after the content of the section
5661 * specified by $section has been replaced with $text. If the target
5662 * section does not exist, $oldtext is returned unchanged.
5664 * @param string $oldText Former text of the article
5665 * @param string|int $sectionId Section identifier as a number or string
5666 * (e.g. 0, 1 or 'T-1').
5667 * @param string $newText Replacing text
5669 * @return string Modified text
5671 public function replaceSection( $oldText, $sectionId, $newText ) {
5672 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5676 * Get the ID of the revision we are parsing
5680 public function getRevisionId() {
5681 return $this->mRevisionId
;
5685 * Get the revision object for $this->mRevisionId
5687 * @return Revision|null Either a Revision object or null
5688 * @since 1.23 (public since 1.23)
5690 public function getRevisionObject() {
5691 if ( !is_null( $this->mRevisionObject
) ) {
5692 return $this->mRevisionObject
;
5694 if ( is_null( $this->mRevisionId
) ) {
5698 $rev = call_user_func(
5699 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5702 # If the parse is for a new revision, then the callback should have
5703 # already been set to force the object and should match mRevisionId.
5704 # If not, try to fetch by mRevisionId for sanity.
5705 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5706 $rev = Revision
::newFromId( $this->mRevisionId
);
5709 $this->mRevisionObject
= $rev;
5711 return $this->mRevisionObject
;
5715 * Get the timestamp associated with the current revision, adjusted for
5716 * the default server-local timestamp
5719 public function getRevisionTimestamp() {
5720 if ( is_null( $this->mRevisionTimestamp
) ) {
5723 $revObject = $this->getRevisionObject();
5724 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5726 # The cryptic '' timezone parameter tells to use the site-default
5727 # timezone offset instead of the user settings.
5728 # Since this value will be saved into the parser cache, served
5729 # to other users, and potentially even used inside links and such,
5730 # it needs to be consistent for all visitors.
5731 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5734 return $this->mRevisionTimestamp
;
5738 * Get the name of the user that edited the last revision
5740 * @return string User name
5742 public function getRevisionUser() {
5743 if ( is_null( $this->mRevisionUser
) ) {
5744 $revObject = $this->getRevisionObject();
5746 # if this template is subst: the revision id will be blank,
5747 # so just use the current user's name
5749 $this->mRevisionUser
= $revObject->getUserText();
5750 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5751 $this->mRevisionUser
= $this->getUser()->getName();
5754 return $this->mRevisionUser
;
5758 * Get the size of the revision
5760 * @return int|null Revision size
5762 public function getRevisionSize() {
5763 if ( is_null( $this->mRevisionSize
) ) {
5764 $revObject = $this->getRevisionObject();
5766 # if this variable is subst: the revision id will be blank,
5767 # so just use the parser input size, because the own substituation
5768 # will change the size.
5770 $this->mRevisionSize
= $revObject->getSize();
5772 $this->mRevisionSize
= $this->mInputSize
;
5775 return $this->mRevisionSize
;
5779 * Mutator for $mDefaultSort
5781 * @param string $sort New value
5783 public function setDefaultSort( $sort ) {
5784 $this->mDefaultSort
= $sort;
5785 $this->mOutput
->setProperty( 'defaultsort', $sort );
5789 * Accessor for $mDefaultSort
5790 * Will use the empty string if none is set.
5792 * This value is treated as a prefix, so the
5793 * empty string is equivalent to sorting by
5798 public function getDefaultSort() {
5799 if ( $this->mDefaultSort
!== false ) {
5800 return $this->mDefaultSort
;
5807 * Accessor for $mDefaultSort
5808 * Unlike getDefaultSort(), will return false if none is set
5810 * @return string|bool
5812 public function getCustomDefaultSort() {
5813 return $this->mDefaultSort
;
5816 private static function getSectionNameFromStrippedText( $text ) {
5817 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5818 $text = Sanitizer
::decodeCharReferences( $text );
5819 $text = self
::normalizeSectionName( $text );
5823 private static function makeAnchor( $sectionName ) {
5824 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5827 private static function makeLegacyAnchor( $sectionName ) {
5828 global $wgFragmentMode;
5829 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5830 // ForAttribute() and ForLink() are the same for legacy encoding
5831 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5833 $id = Sanitizer
::escapeIdForLink( $sectionName );
5840 * Try to guess the section anchor name based on a wikitext fragment
5841 * presumably extracted from a heading, for example "Header" from
5844 * @param string $text
5845 * @return string Anchor (starting with '#')
5847 public function guessSectionNameFromWikiText( $text ) {
5848 # Strip out wikitext links(they break the anchor)
5849 $text = $this->stripSectionName( $text );
5850 $sectionName = self
::getSectionNameFromStrippedText( $text );
5851 return self
::makeAnchor( $sectionName );
5855 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5856 * instead, if possible. For use in redirects, since various versions
5857 * of Microsoft browsers interpret Location: headers as something other
5858 * than UTF-8, resulting in breakage.
5860 * @param string $text The section name
5861 * @return string Anchor (starting with '#')
5863 public function guessLegacySectionNameFromWikiText( $text ) {
5864 # Strip out wikitext links(they break the anchor)
5865 $text = $this->stripSectionName( $text );
5866 $sectionName = self
::getSectionNameFromStrippedText( $text );
5867 return self
::makeLegacyAnchor( $sectionName );
5871 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5872 * @param string $text Section name (plain text)
5873 * @return string Anchor (starting with '#')
5875 public static function guessSectionNameFromStrippedText( $text ) {
5876 $sectionName = self
::getSectionNameFromStrippedText( $text );
5877 return self
::makeAnchor( $sectionName );
5881 * Apply the same normalization as code making links to this section would
5883 * @param string $text
5886 private static function normalizeSectionName( $text ) {
5887 # T90902: ensure the same normalization is applied for IDs as to links
5888 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5891 $parts = $titleParser->splitTitleString( "#$text" );
5892 } catch ( MalformedTitleException
$ex ) {
5895 return $parts['fragment'];
5899 * Strips a text string of wikitext for use in a section anchor
5901 * Accepts a text string and then removes all wikitext from the
5902 * string and leaves only the resultant text (i.e. the result of
5903 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5904 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5905 * to create valid section anchors by mimicing the output of the
5906 * parser when headings are parsed.
5908 * @param string $text Text string to be stripped of wikitext
5909 * for use in a Section anchor
5910 * @return string Filtered text string
5912 public function stripSectionName( $text ) {
5913 # Strip internal link markup
5914 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5915 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5917 # Strip external link markup
5918 # @todo FIXME: Not tolerant to blank link text
5919 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5920 # on how many empty links there are on the page - need to figure that out.
5921 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5923 # Parse wikitext quotes (italics & bold)
5924 $text = $this->doQuotes( $text );
5927 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5932 * strip/replaceVariables/unstrip for preprocessor regression testing
5934 * @param string $text
5935 * @param Title $title
5936 * @param ParserOptions $options
5937 * @param int $outputType
5941 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5942 $outputType = self
::OT_HTML
5944 $magicScopeVariable = $this->lock();
5945 $this->startParse( $title, $options, $outputType, true );
5947 $text = $this->replaceVariables( $text );
5948 $text = $this->mStripState
->unstripBoth( $text );
5949 $text = Sanitizer
::removeHTMLtags( $text );
5954 * @param string $text
5955 * @param Title $title
5956 * @param ParserOptions $options
5959 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5960 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5964 * @param string $text
5965 * @param Title $title
5966 * @param ParserOptions $options
5969 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5970 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5974 * Call a callback function on all regions of the given text that are not
5975 * inside strip markers, and replace those regions with the return value
5976 * of the callback. For example, with input:
5980 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5981 * two strings will be replaced with the value returned by the callback in
5985 * @param callable $callback
5989 public function markerSkipCallback( $s, $callback ) {
5992 while ( $i < strlen( $s ) ) {
5993 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
5994 if ( $markerStart === false ) {
5995 $out .= call_user_func( $callback, substr( $s, $i ) );
5998 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5999 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6000 if ( $markerEnd === false ) {
6001 $out .= substr( $s, $markerStart );
6004 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6005 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6014 * Remove any strip markers found in the given text.
6016 * @param string $text
6019 public function killMarkers( $text ) {
6020 return $this->mStripState
->killMarkers( $text );
6024 * Save the parser state required to convert the given half-parsed text to
6025 * HTML. "Half-parsed" in this context means the output of
6026 * recursiveTagParse() or internalParse(). This output has strip markers
6027 * from replaceVariables (extensionSubstitution() etc.), and link
6028 * placeholders from replaceLinkHolders().
6030 * Returns an array which can be serialized and stored persistently. This
6031 * array can later be loaded into another parser instance with
6032 * unserializeHalfParsedText(). The text can then be safely incorporated into
6033 * the return value of a parser hook.
6035 * @deprecated since 1.31
6036 * @param string $text
6040 public function serializeHalfParsedText( $text ) {
6041 wfDeprecated( __METHOD__
, '1.31' );
6044 'version' => self
::HALF_PARSED_VERSION
,
6045 'stripState' => $this->mStripState
->getSubState( $text ),
6046 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6052 * Load the parser state given in the $data array, which is assumed to
6053 * have been generated by serializeHalfParsedText(). The text contents is
6054 * extracted from the array, and its markers are transformed into markers
6055 * appropriate for the current Parser instance. This transformed text is
6056 * returned, and can be safely included in the return value of a parser
6059 * If the $data array has been stored persistently, the caller should first
6060 * check whether it is still valid, by calling isValidHalfParsedText().
6062 * @deprecated since 1.31
6063 * @param array $data Serialized data
6064 * @throws MWException
6067 public function unserializeHalfParsedText( $data ) {
6068 wfDeprecated( __METHOD__
, '1.31' );
6069 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6070 throw new MWException( __METHOD__
. ': invalid version' );
6073 # First, extract the strip state.
6074 $texts = [ $data['text'] ];
6075 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6077 # Now renumber links
6078 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6080 # Should be good to go.
6085 * Returns true if the given array, presumed to be generated by
6086 * serializeHalfParsedText(), is compatible with the current version of the
6089 * @deprecated since 1.31
6090 * @param array $data
6094 public function isValidHalfParsedText( $data ) {
6095 wfDeprecated( __METHOD__
, '1.31' );
6096 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6100 * Parsed a width param of imagelink like 300px or 200x300px
6102 * @param string $value
6103 * @param bool $parseHeight
6108 public static function parseWidthParam( $value, $parseHeight = true ) {
6109 $parsedWidthParam = [];
6110 if ( $value === '' ) {
6111 return $parsedWidthParam;
6114 # (T15500) In both cases (width/height and width only),
6115 # permit trailing "px" for backward compatibility.
6116 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6117 $width = intval( $m[1] );
6118 $height = intval( $m[2] );
6119 $parsedWidthParam['width'] = $width;
6120 $parsedWidthParam['height'] = $height;
6121 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6122 $width = intval( $value );
6123 $parsedWidthParam['width'] = $width;
6125 return $parsedWidthParam;
6129 * Lock the current instance of the parser.
6131 * This is meant to stop someone from calling the parser
6132 * recursively and messing up all the strip state.
6134 * @throws MWException If parser is in a parse
6135 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6137 protected function lock() {
6138 if ( $this->mInParse
) {
6139 throw new MWException( "Parser state cleared while parsing. "
6140 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6143 // Save the backtrace when locking, so that if some code tries locking again,
6144 // we can print the lock owner's backtrace for easier debugging
6146 $this->mInParse
= $e->getTraceAsString();
6148 $recursiveCheck = new ScopedCallback( function () {
6149 $this->mInParse
= false;
6152 return $recursiveCheck;
6156 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6158 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6159 * or if there is more than one <p/> tag in the input HTML.
6161 * @param string $html
6165 public static function stripOuterParagraph( $html ) {
6167 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6168 if ( strpos( $m[1], '</p>' ) === false ) {
6177 * Return this parser if it is not doing anything, otherwise
6178 * get a fresh parser. You can use this method by doing
6179 * $myParser = $wgParser->getFreshParser(), or more simply
6180 * $wgParser->getFreshParser()->parse( ... );
6181 * if you're unsure if $wgParser is safe to use.
6184 * @return Parser A parser object that is not parsing anything
6186 public function getFreshParser() {
6187 global $wgParserConf;
6188 if ( $this->mInParse
) {
6189 return new $wgParserConf['class']( $wgParserConf );
6196 * Set's up the PHP implementation of OOUI for use in this request
6197 * and instructs OutputPage to enable OOUI for itself.
6201 public function enableOOUI() {
6202 OutputPage
::setupOOUI();
6203 $this->mOutput
->setEnableOOUI( true );