3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @defgroup Parser Parser
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
37 * There are seven main entry points into the Parser class:
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
89 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
90 # uses to replace invalid HTML characters.
91 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
92 # Simplified expression to match an IPv4 or IPv6 address, or
93 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
94 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
95 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
96 // phpcs:ignore Generic.Files.LineLength
97 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
98 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
100 # Regular expression for a non-newline space
101 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
103 # Flags for preprocessToDom
104 const PTD_FOR_INCLUSION
= 1;
106 # Allowed values for $this->mOutputType
107 # Parameter to startExternalParse().
108 const OT_HTML
= 1; # like parse()
109 const OT_WIKI
= 2; # like preSaveTransform()
110 const OT_PREPROCESS
= 3; # like preprocess()
112 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 * @var string Prefix and suffix for temporary replacement strings
116 * for the multipass parser.
118 * \x7f should never appear in input as it's disallowed in XML.
119 * Using it at the front also gives us a little extra robustness
120 * since it shouldn't match when butted up against identifier-like
123 * Must not consist of all title characters, or else it will change
124 * the behavior of <nowiki> in a link.
126 * Must have a character that needs escaping in attributes, otherwise
127 * someone could put a strip marker in an attribute, to get around
128 * escaping quote marks, and break out of the attribute. Thus we add
131 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
132 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
134 # Markers used for wrapping the table of contents
135 const TOC_START
= '<mw:toc>';
136 const TOC_END
= '</mw:toc>';
138 /** @var int Assume that no output will later be saved this many seconds after parsing */
142 public $mTagHooks = [];
143 public $mTransparentTagHooks = [];
144 public $mFunctionHooks = [];
145 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
146 public $mFunctionTagHooks = [];
147 public $mStripList = [];
148 public $mDefaultStripList = [];
149 public $mVarCache = [];
150 public $mImageParams = [];
151 public $mImageParamsMagicArray = [];
152 public $mMarkerIndex = 0;
154 * @var bool Whether firstCallInit still needs to be called
156 public $mFirstCall = true;
158 # Initialised by initialiseVariables()
161 * @var MagicWordArray
166 * @var MagicWordArray
169 # Initialised in constructor
170 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
172 # Initialized in getPreprocessor()
173 /** @var Preprocessor */
174 public $mPreprocessor;
176 # Cleared with clearState():
188 public $mIncludeCount;
190 * @var LinkHolderArray
192 public $mLinkHolders;
195 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
196 public $mDefaultSort;
197 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
198 public $mExpensiveFunctionCount; # number of expensive parser function calls
199 public $mShowToc, $mForceTocPosition;
204 public $mUser; # User object; only used when doing pre-save transform
207 # These are variables reset at least once per parse regardless of $clearState
217 public $mTitle; # Title context, used for self-link rendering and similar things
218 public $mOutputType; # Output type, one of the OT_xxx constants
219 public $ot; # Shortcut alias, see setOutputType()
220 public $mRevisionObject; # The revision object of the specified revision ID
221 public $mRevisionId; # ID to display in {{REVISIONID}} tags
222 public $mRevisionTimestamp; # The timestamp of the specified revision ID
223 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
224 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
225 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
226 public $mInputSize = false; # For {{PAGESIZE}} on current page.
229 * @var string Deprecated accessor for the strip marker prefix.
230 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
232 public $mUniqPrefix = self
::MARKER_PREFIX
;
235 * @var array Array with the language name of each language link (i.e. the
236 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
237 * duplicate language links to the ParserOutput.
239 public $mLangLinkLanguages;
242 * @var MapCacheLRU|null
245 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
247 public $currentRevisionCache;
250 * @var bool|string Recursive call protection.
251 * This variable should be treated as if it were private.
253 public $mInParse = false;
255 /** @var SectionProfiler */
256 protected $mProfiler;
261 protected $mLinkRenderer;
263 /** @var MagicWordFactory */
264 private $magicWordFactory;
270 * @param array $conf See $wgParserConf documentation
271 * @param MagicWordFactory|null $magicWordFactory
272 * @param Language|null $contLang Content language
273 * @param string|null $urlProtocols As returned from wfUrlProtocols()
275 public function __construct(
276 array $conf = [], MagicWordFactory
$magicWordFactory = null, Language
$contLang = null,
279 $this->mConf
= $conf;
280 $this->mUrlProtocols
= $urlProtocols ??
wfUrlProtocols();
281 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
282 self
::EXT_LINK_ADDR
.
283 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
284 if ( isset( $conf['preprocessorClass'] ) ) {
285 $this->mPreprocessorClass
= $conf['preprocessorClass'];
286 } elseif ( defined( 'HPHP_VERSION' ) ) {
287 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
288 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
289 } elseif ( extension_loaded( 'domxml' ) ) {
290 # PECL extension that conflicts with the core DOM extension (T15770)
291 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
292 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
293 } elseif ( extension_loaded( 'dom' ) ) {
294 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
296 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
298 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
300 $this->magicWordFactory
= $magicWordFactory ??
301 MediaWikiServices
::getInstance()->getMagicWordFactory();
303 $this->contLang
= $contLang ?? MediaWikiServices
::getInstance()->getContentLanguage();
307 * Reduce memory usage to reduce the impact of circular references
309 public function __destruct() {
310 if ( isset( $this->mLinkHolders
) ) {
311 unset( $this->mLinkHolders
);
313 foreach ( $this as $name => $value ) {
314 unset( $this->$name );
319 * Allow extensions to clean up when the parser is cloned
321 public function __clone() {
322 $this->mInParse
= false;
324 // T58226: When you create a reference "to" an object field, that
325 // makes the object field itself be a reference too (until the other
326 // reference goes out of scope). When cloning, any field that's a
327 // reference is copied as a reference in the new object. Both of these
328 // are defined PHP5 behaviors, as inconvenient as it is for us when old
329 // hooks from PHP4 days are passing fields by reference.
330 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
331 // Make a non-reference copy of the field, then rebind the field to
332 // reference the new copy.
338 Hooks
::run( 'ParserCloned', [ $this ] );
342 * Do various kinds of initialisation on the first call of the parser
344 public function firstCallInit() {
345 if ( !$this->mFirstCall
) {
348 $this->mFirstCall
= false;
350 CoreParserFunctions
::register( $this );
351 CoreTagHooks
::register( $this );
352 $this->initialiseVariables();
354 // Avoid PHP 7.1 warning from passing $this by reference
356 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
364 public function clearState() {
365 $this->firstCallInit();
366 $this->mOutput
= new ParserOutput
;
367 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
368 $this->mAutonumber
= 0;
369 $this->mIncludeCount
= [];
370 $this->mLinkHolders
= new LinkHolderArray( $this );
372 $this->mRevisionObject
= $this->mRevisionTimestamp
=
373 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
374 $this->mVarCache
= [];
376 $this->mLangLinkLanguages
= [];
377 $this->currentRevisionCache
= null;
379 $this->mStripState
= new StripState( $this );
381 # Clear these on every parse, T6549
382 $this->mTplRedirCache
= $this->mTplDomCache
= [];
384 $this->mShowToc
= true;
385 $this->mForceTocPosition
= false;
386 $this->mIncludeSizes
= [
390 $this->mPPNodeCount
= 0;
391 $this->mGeneratedPPNodeCount
= 0;
392 $this->mHighestExpansionDepth
= 0;
393 $this->mDefaultSort
= false;
394 $this->mHeadings
= [];
395 $this->mDoubleUnderscores
= [];
396 $this->mExpensiveFunctionCount
= 0;
399 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
400 $this->mPreprocessor
= null;
403 $this->mProfiler
= new SectionProfiler();
405 // Avoid PHP 7.1 warning from passing $this by reference
407 Hooks
::run( 'ParserClearState', [ &$parser ] );
411 * Convert wikitext to HTML
412 * Do not call this function recursively.
414 * @param string $text Text we want to parse
415 * @param Title $title
416 * @param ParserOptions $options
417 * @param bool $linestart
418 * @param bool $clearState
419 * @param int|null $revid Number to pass in {{REVISIONID}}
420 * @return ParserOutput A ParserOutput
422 public function parse(
423 $text, Title
$title, ParserOptions
$options,
424 $linestart = true, $clearState = true, $revid = null
427 // We use U+007F DELETE to construct strip markers, so we have to make
428 // sure that this character does not occur in the input text.
429 $text = strtr( $text, "\x7f", "?" );
430 $magicScopeVariable = $this->lock();
432 // Strip U+0000 NULL (T159174)
433 $text = str_replace( "\000", '', $text );
435 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
437 $this->currentRevisionCache
= null;
438 $this->mInputSize
= strlen( $text );
439 if ( $this->mOptions
->getEnableLimitReport() ) {
440 $this->mOutput
->resetParseStartTime();
443 $oldRevisionId = $this->mRevisionId
;
444 $oldRevisionObject = $this->mRevisionObject
;
445 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
446 $oldRevisionUser = $this->mRevisionUser
;
447 $oldRevisionSize = $this->mRevisionSize
;
448 if ( $revid !== null ) {
449 $this->mRevisionId
= $revid;
450 $this->mRevisionObject
= null;
451 $this->mRevisionTimestamp
= null;
452 $this->mRevisionUser
= null;
453 $this->mRevisionSize
= null;
456 // Avoid PHP 7.1 warning from passing $this by reference
458 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
460 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
461 $text = $this->internalParse( $text );
462 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
464 $text = $this->internalParseHalfParsed( $text, true, $linestart );
467 * A converted title will be provided in the output object if title and
468 * content conversion are enabled, the article text does not contain
469 * a conversion-suppressing double-underscore tag, and no
470 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
471 * automatic link conversion.
473 if ( !( $options->getDisableTitleConversion()
474 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
475 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
476 ||
$this->mOutput
->getDisplayTitle() !== false )
478 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
479 if ( $convruletitle ) {
480 $this->mOutput
->setTitleText( $convruletitle );
482 $titleText = $this->getTargetLanguage()->convertTitle( $title );
483 $this->mOutput
->setTitleText( $titleText );
487 # Compute runtime adaptive expiry if set
488 $this->mOutput
->finalizeAdaptiveCacheExpiry();
490 # Warn if too many heavyweight parser functions were used
491 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
492 $this->limitationWarn( 'expensive-parserfunction',
493 $this->mExpensiveFunctionCount
,
494 $this->mOptions
->getExpensiveParserFunctionLimit()
498 # Information on limits, for the benefit of users who try to skirt them
499 if ( $this->mOptions
->getEnableLimitReport() ) {
500 $text .= $this->makeLimitReport();
503 # Wrap non-interface parser output in a <div> so it can be targeted
505 $class = $this->mOptions
->getWrapOutputClass();
506 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
507 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
510 $this->mOutput
->setText( $text );
512 $this->mRevisionId
= $oldRevisionId;
513 $this->mRevisionObject
= $oldRevisionObject;
514 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
515 $this->mRevisionUser
= $oldRevisionUser;
516 $this->mRevisionSize
= $oldRevisionSize;
517 $this->mInputSize
= false;
518 $this->currentRevisionCache
= null;
520 return $this->mOutput
;
524 * Set the limit report data in the current ParserOutput, and return the
525 * limit report HTML comment.
529 protected function makeLimitReport() {
530 global $wgShowHostnames;
532 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
534 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
535 if ( $cpuTime !== null ) {
536 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
537 sprintf( "%.3f", $cpuTime )
541 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
542 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
543 sprintf( "%.3f", $wallTime )
546 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
547 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
549 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
550 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
552 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
553 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
555 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
556 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
558 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
559 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
561 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
562 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
565 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
566 $this->mOutput
->setLimitReportData( $key, $value );
569 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
571 $limitReport = "NewPP limit report\n";
572 if ( $wgShowHostnames ) {
573 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
575 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
576 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
577 $limitReport .= 'Dynamic content: ' .
578 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
581 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
582 if ( Hooks
::run( 'ParserLimitReportFormat',
583 [ $key, &$value, &$limitReport, false, false ]
585 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
586 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
587 ->inLanguage( 'en' )->useDatabase( false );
588 if ( !$valueMsg->exists() ) {
589 $valueMsg = new RawMessage( '$1' );
591 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
592 $valueMsg->params( $value );
593 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
597 // Since we're not really outputting HTML, decode the entities and
598 // then re-encode the things that need hiding inside HTML comments.
599 $limitReport = htmlspecialchars_decode( $limitReport );
600 // Run deprecated hook
601 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
603 // Sanitize for comment. Note '‐' in the replacement is U+2010,
604 // which looks much like the problematic '-'.
605 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
606 $text = "\n<!-- \n$limitReport-->\n";
608 // Add on template profiling data in human/machine readable way
609 $dataByFunc = $this->mProfiler
->getFunctionStats();
610 uasort( $dataByFunc, function ( $a, $b ) {
611 return $b['real'] <=> $a['real']; // descending order
614 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
615 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
616 $item['%real'], $item['real'], $item['calls'],
617 htmlspecialchars( $item['name'] ) );
619 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
620 $text .= implode( "\n", $profileReport ) . "\n-->\n";
622 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
624 // Add other cache related metadata
625 if ( $wgShowHostnames ) {
626 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
628 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
629 $this->mOutput
->getCacheTime() );
630 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
631 $this->mOutput
->getCacheExpiry() );
632 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
633 $this->mOutput
->hasDynamicContent() );
635 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
636 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
637 $this->mTitle
->getPrefixedDBkey() );
643 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
644 * can be called from an extension tag hook.
646 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
647 * instead, which means that lists and links have not been fully parsed yet,
648 * and strip markers are still present.
650 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
652 * Use this function if you're a parser tag hook and you want to parse
653 * wikitext before or after applying additional transformations, and you
654 * intend to *return the result as hook output*, which will cause it to go
655 * through the rest of parsing process automatically.
657 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
658 * $text are not expanded
660 * @param string $text Text extension wants to have parsed
661 * @param bool|PPFrame $frame The frame to use for expanding any template variables
662 * @return string UNSAFE half-parsed HTML
664 public function recursiveTagParse( $text, $frame = false ) {
665 // Avoid PHP 7.1 warning from passing $this by reference
667 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
668 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
669 $text = $this->internalParse( $text, false, $frame );
674 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
675 * point can be called from an extension tag hook.
677 * The output of this function is fully-parsed HTML that is safe for output.
678 * If you're a parser tag hook, you might want to use recursiveTagParse()
681 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
682 * $text are not expanded
686 * @param string $text Text extension wants to have parsed
687 * @param bool|PPFrame $frame The frame to use for expanding any template variables
688 * @return string Fully parsed HTML
690 public function recursiveTagParseFully( $text, $frame = false ) {
691 $text = $this->recursiveTagParse( $text, $frame );
692 $text = $this->internalParseHalfParsed( $text, false );
697 * Expand templates and variables in the text, producing valid, static wikitext.
698 * Also removes comments.
699 * Do not call this function recursively.
700 * @param string $text
701 * @param Title|null $title
702 * @param ParserOptions $options
703 * @param int|null $revid
704 * @param bool|PPFrame $frame
705 * @return mixed|string
707 public function preprocess( $text, Title
$title = null,
708 ParserOptions
$options, $revid = null, $frame = false
710 $magicScopeVariable = $this->lock();
711 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
712 if ( $revid !== null ) {
713 $this->mRevisionId
= $revid;
715 // Avoid PHP 7.1 warning from passing $this by reference
717 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
718 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
719 $text = $this->replaceVariables( $text, $frame );
720 $text = $this->mStripState
->unstripBoth( $text );
725 * Recursive parser entry point that can be called from an extension tag
728 * @param string $text Text to be expanded
729 * @param bool|PPFrame $frame The frame to use for expanding any template variables
733 public function recursivePreprocess( $text, $frame = false ) {
734 $text = $this->replaceVariables( $text, $frame );
735 $text = $this->mStripState
->unstripBoth( $text );
740 * Process the wikitext for the "?preload=" feature. (T7210)
742 * "<noinclude>", "<includeonly>" etc. are parsed as for template
743 * transclusion, comments, templates, arguments, tags hooks and parser
744 * functions are untouched.
746 * @param string $text
747 * @param Title $title
748 * @param ParserOptions $options
749 * @param array $params
752 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
753 $msg = new RawMessage( $text );
754 $text = $msg->params( $params )->plain();
756 # Parser (re)initialisation
757 $magicScopeVariable = $this->lock();
758 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
760 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
761 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
762 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
763 $text = $this->mStripState
->unstripBoth( $text );
768 * Set the current user.
769 * Should only be used when doing pre-save transform.
771 * @param User|null $user User object or null (to reset)
773 public function setUser( $user ) {
774 $this->mUser
= $user;
778 * Set the context title
782 public function setTitle( $t ) {
784 $t = Title
::newFromText( 'NO TITLE' );
787 if ( $t->hasFragment() ) {
788 # Strip the fragment to avoid various odd effects
789 $this->mTitle
= $t->createFragmentTarget( '' );
796 * Accessor for the Title object
800 public function getTitle() {
801 return $this->mTitle
;
805 * Accessor/mutator for the Title object
807 * @param Title|null $x Title object or null to just get the current one
810 public function Title( $x = null ) {
811 return wfSetVar( $this->mTitle
, $x );
815 * Set the output type
817 * @param int $ot New value
819 public function setOutputType( $ot ) {
820 $this->mOutputType
= $ot;
823 'html' => $ot == self
::OT_HTML
,
824 'wiki' => $ot == self
::OT_WIKI
,
825 'pre' => $ot == self
::OT_PREPROCESS
,
826 'plain' => $ot == self
::OT_PLAIN
,
831 * Accessor/mutator for the output type
833 * @param int|null $x New value or null to just get the current one
836 public function OutputType( $x = null ) {
837 return wfSetVar( $this->mOutputType
, $x );
841 * Get the ParserOutput object
843 * @return ParserOutput
845 public function getOutput() {
846 return $this->mOutput
;
850 * Get the ParserOptions object
852 * @return ParserOptions
854 public function getOptions() {
855 return $this->mOptions
;
859 * Accessor/mutator for the ParserOptions object
861 * @param ParserOptions|null $x New value or null to just get the current one
862 * @return ParserOptions Current ParserOptions object
864 public function Options( $x = null ) {
865 return wfSetVar( $this->mOptions
, $x );
871 public function nextLinkID() {
872 return $this->mLinkID++
;
878 public function setLinkID( $id ) {
879 $this->mLinkID
= $id;
883 * Get a language object for use in parser functions such as {{FORMATNUM:}}
886 public function getFunctionLang() {
887 return $this->getTargetLanguage();
891 * Get the target language for the content being parsed. This is usually the
892 * language that the content is in.
896 * @throws MWException
899 public function getTargetLanguage() {
900 $target = $this->mOptions
->getTargetLanguage();
902 if ( $target !== null ) {
904 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
905 return $this->mOptions
->getUserLangObj();
906 } elseif ( is_null( $this->mTitle
) ) {
907 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
910 return $this->mTitle
->getPageLanguage();
914 * Get the language object for language conversion
915 * @deprecated since 1.32, just use getTargetLanguage()
916 * @return Language|null
918 public function getConverterLanguage() {
919 return $this->getTargetLanguage();
923 * Get a User object either from $this->mUser, if set, or from the
924 * ParserOptions object otherwise
928 public function getUser() {
929 if ( !is_null( $this->mUser
) ) {
932 return $this->mOptions
->getUser();
936 * Get a preprocessor object
938 * @return Preprocessor
940 public function getPreprocessor() {
941 if ( !isset( $this->mPreprocessor
) ) {
942 $class = $this->mPreprocessorClass
;
943 $this->mPreprocessor
= new $class( $this );
945 return $this->mPreprocessor
;
949 * Get a LinkRenderer instance to make links with
952 * @return LinkRenderer
954 public function getLinkRenderer() {
955 if ( !$this->mLinkRenderer
) {
956 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
957 ->getLinkRendererFactory()->create();
958 $this->mLinkRenderer
->setStubThreshold(
959 $this->getOptions()->getStubThreshold()
963 return $this->mLinkRenderer
;
967 * Get the MagicWordFactory that this Parser is using
970 * @return MagicWordFactory
972 public function getMagicWordFactory() {
973 return $this->magicWordFactory
;
977 * Get the content language that this Parser is using
982 public function getContentLanguage() {
983 return $this->contLang
;
987 * Replaces all occurrences of HTML-style comments and the given tags
988 * in the text with a random marker and returns the next text. The output
989 * parameter $matches will be an associative array filled with data in
996 * [ 'param' => 'x' ],
997 * '<element param="x">tag content</element>' ]
1000 * @param array $elements List of element names. Comments are always extracted.
1001 * @param string $text Source text string.
1002 * @param array &$matches Out parameter, Array: extracted tags
1003 * @return string Stripped text
1005 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1010 $taglist = implode( '|', $elements );
1011 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
1013 while ( $text != '' ) {
1014 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1016 if ( count( $p ) < 5 ) {
1019 if ( count( $p ) > 5 ) {
1028 $attributes = $p[2];
1033 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1034 $stripped .= $marker;
1036 if ( $close === '/>' ) {
1037 # Empty element tag, <tag />
1042 if ( $element === '!--' ) {
1045 $end = "/(<\\/$element\\s*>)/i";
1047 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1049 if ( count( $q ) < 3 ) {
1050 # No end tag -- let it run out to the end of the text.
1059 $matches[$marker] = [ $element,
1061 Sanitizer
::decodeTagAttributes( $attributes ),
1062 "<$element$attributes$close$content$tail" ];
1068 * Get a list of strippable XML-like elements
1072 public function getStripList() {
1073 return $this->mStripList
;
1077 * Add an item to the strip state
1078 * Returns the unique tag which must be inserted into the stripped text
1079 * The tag will be replaced with the original text in unstrip()
1081 * @param string $text
1085 public function insertStripItem( $text ) {
1086 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1087 $this->mMarkerIndex++
;
1088 $this->mStripState
->addGeneral( $marker, $text );
1093 * parse the wiki syntax used to render tables
1096 * @param string $text
1099 public function doTableStuff( $text ) {
1100 $lines = StringUtils
::explode( "\n", $text );
1102 $td_history = []; # Is currently a td tag open?
1103 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1104 $tr_history = []; # Is currently a tr tag open?
1105 $tr_attributes = []; # history of tr attributes
1106 $has_opened_tr = []; # Did this table open a <tr> element?
1107 $indent_level = 0; # indent level of the table
1109 foreach ( $lines as $outLine ) {
1110 $line = trim( $outLine );
1112 if ( $line === '' ) { # empty line, go to next line
1113 $out .= $outLine . "\n";
1117 $first_character = $line[0];
1118 $first_two = substr( $line, 0, 2 );
1121 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1122 # First check if we are starting a new table
1123 $indent_level = strlen( $matches[1] );
1125 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1126 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1128 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1129 array_push( $td_history, false );
1130 array_push( $last_tag_history, '' );
1131 array_push( $tr_history, false );
1132 array_push( $tr_attributes, '' );
1133 array_push( $has_opened_tr, false );
1134 } elseif ( count( $td_history ) == 0 ) {
1135 # Don't do any of the following
1136 $out .= $outLine . "\n";
1138 } elseif ( $first_two === '|}' ) {
1139 # We are ending a table
1140 $line = '</table>' . substr( $line, 2 );
1141 $last_tag = array_pop( $last_tag_history );
1143 if ( !array_pop( $has_opened_tr ) ) {
1144 $line = "<tr><td></td></tr>{$line}";
1147 if ( array_pop( $tr_history ) ) {
1148 $line = "</tr>{$line}";
1151 if ( array_pop( $td_history ) ) {
1152 $line = "</{$last_tag}>{$line}";
1154 array_pop( $tr_attributes );
1155 if ( $indent_level > 0 ) {
1156 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1160 } elseif ( $first_two === '|-' ) {
1161 # Now we have a table row
1162 $line = preg_replace( '#^\|-+#', '', $line );
1164 # Whats after the tag is now only attributes
1165 $attributes = $this->mStripState
->unstripBoth( $line );
1166 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1167 array_pop( $tr_attributes );
1168 array_push( $tr_attributes, $attributes );
1171 $last_tag = array_pop( $last_tag_history );
1172 array_pop( $has_opened_tr );
1173 array_push( $has_opened_tr, true );
1175 if ( array_pop( $tr_history ) ) {
1179 if ( array_pop( $td_history ) ) {
1180 $line = "</{$last_tag}>{$line}";
1184 array_push( $tr_history, false );
1185 array_push( $td_history, false );
1186 array_push( $last_tag_history, '' );
1187 } elseif ( $first_character === '|'
1188 ||
$first_character === '!'
1189 ||
$first_two === '|+'
1191 # This might be cell elements, td, th or captions
1192 if ( $first_two === '|+' ) {
1193 $first_character = '+';
1194 $line = substr( $line, 2 );
1196 $line = substr( $line, 1 );
1199 // Implies both are valid for table headings.
1200 if ( $first_character === '!' ) {
1201 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1204 # Split up multiple cells on the same line.
1205 # FIXME : This can result in improper nesting of tags processed
1206 # by earlier parser steps.
1207 $cells = explode( '||', $line );
1211 # Loop through each table cell
1212 foreach ( $cells as $cell ) {
1214 if ( $first_character !== '+' ) {
1215 $tr_after = array_pop( $tr_attributes );
1216 if ( !array_pop( $tr_history ) ) {
1217 $previous = "<tr{$tr_after}>\n";
1219 array_push( $tr_history, true );
1220 array_push( $tr_attributes, '' );
1221 array_pop( $has_opened_tr );
1222 array_push( $has_opened_tr, true );
1225 $last_tag = array_pop( $last_tag_history );
1227 if ( array_pop( $td_history ) ) {
1228 $previous = "</{$last_tag}>\n{$previous}";
1231 if ( $first_character === '|' ) {
1233 } elseif ( $first_character === '!' ) {
1235 } elseif ( $first_character === '+' ) {
1236 $last_tag = 'caption';
1241 array_push( $last_tag_history, $last_tag );
1243 # A cell could contain both parameters and data
1244 $cell_data = explode( '|', $cell, 2 );
1246 # T2553: Note that a '|' inside an invalid link should not
1247 # be mistaken as delimiting cell parameters
1248 # Bug T153140: Neither should language converter markup.
1249 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1250 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1251 } elseif ( count( $cell_data ) == 1 ) {
1252 // Whitespace in cells is trimmed
1253 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1255 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1256 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1257 // Whitespace in cells is trimmed
1258 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1262 array_push( $td_history, true );
1265 $out .= $outLine . "\n";
1268 # Closing open td, tr && table
1269 while ( count( $td_history ) > 0 ) {
1270 if ( array_pop( $td_history ) ) {
1273 if ( array_pop( $tr_history ) ) {
1276 if ( !array_pop( $has_opened_tr ) ) {
1277 $out .= "<tr><td></td></tr>\n";
1280 $out .= "</table>\n";
1283 # Remove trailing line-ending (b/c)
1284 if ( substr( $out, -1 ) === "\n" ) {
1285 $out = substr( $out, 0, -1 );
1288 # special case: don't return empty table
1289 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1297 * Helper function for parse() that transforms wiki markup into half-parsed
1298 * HTML. Only called for $mOutputType == self::OT_HTML.
1302 * @param string $text The text to parse
1303 * @param bool $isMain Whether this is being called from the main parse() function
1304 * @param PPFrame|bool $frame A pre-processor frame
1308 public function internalParse( $text, $isMain = true, $frame = false ) {
1311 // Avoid PHP 7.1 warning from passing $this by reference
1314 # Hook to suspend the parser in this state
1315 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1319 # if $frame is provided, then use $frame for replacing any variables
1321 # use frame depth to infer how include/noinclude tags should be handled
1322 # depth=0 means this is the top-level document; otherwise it's an included document
1323 if ( !$frame->depth
) {
1326 $flag = self
::PTD_FOR_INCLUSION
;
1328 $dom = $this->preprocessToDom( $text, $flag );
1329 $text = $frame->expand( $dom );
1331 # if $frame is not provided, then use old-style replaceVariables
1332 $text = $this->replaceVariables( $text );
1335 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1336 $text = Sanitizer
::removeHTMLtags(
1338 [ $this, 'attributeStripCallback' ],
1340 array_keys( $this->mTransparentTagHooks
),
1342 [ $this, 'addTrackingCategory' ]
1344 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1346 # Tables need to come after variable replacement for things to work
1347 # properly; putting them before other transformations should keep
1348 # exciting things like link expansions from showing up in surprising
1350 $text = $this->doTableStuff( $text );
1352 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1354 $text = $this->doDoubleUnderscore( $text );
1356 $text = $this->doHeadings( $text );
1357 $text = $this->replaceInternalLinks( $text );
1358 $text = $this->doAllQuotes( $text );
1359 $text = $this->replaceExternalLinks( $text );
1361 # replaceInternalLinks may sometimes leave behind
1362 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1363 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1365 $text = $this->doMagicLinks( $text );
1366 $text = $this->formatHeadings( $text, $origText, $isMain );
1372 * Helper function for parse() that transforms half-parsed HTML into fully
1375 * @param string $text
1376 * @param bool $isMain
1377 * @param bool $linestart
1380 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1381 $text = $this->mStripState
->unstripGeneral( $text );
1383 // Avoid PHP 7.1 warning from passing $this by reference
1387 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1390 # Clean up special characters, only run once, next-to-last before doBlockLevels
1391 $text = Sanitizer
::armorFrenchSpaces( $text );
1393 $text = $this->doBlockLevels( $text, $linestart );
1395 $this->replaceLinkHolders( $text );
1398 * The input doesn't get language converted if
1400 * b) Content isn't converted
1401 * c) It's a conversion table
1402 * d) it is an interface message (which is in the user language)
1404 if ( !( $this->mOptions
->getDisableContentConversion()
1405 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1407 if ( !$this->mOptions
->getInterfaceMessage() ) {
1408 # The position of the convert() call should not be changed. it
1409 # assumes that the links are all replaced and the only thing left
1410 # is the <nowiki> mark.
1411 $text = $this->getTargetLanguage()->convert( $text );
1415 $text = $this->mStripState
->unstripNoWiki( $text );
1418 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1421 $text = $this->replaceTransparentTags( $text );
1422 $text = $this->mStripState
->unstripGeneral( $text );
1424 $text = Sanitizer
::normalizeCharReferences( $text );
1426 if ( MWTidy
::isEnabled() ) {
1427 if ( $this->mOptions
->getTidy() ) {
1428 $text = MWTidy
::tidy( $text );
1431 # attempt to sanitize at least some nesting problems
1432 # (T4702 and quite a few others)
1434 # ''Something [http://www.cool.com cool''] -->
1435 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1436 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1437 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1438 # fix up an anchor inside another anchor, only
1439 # at least for a single single nested link (T5695)
1440 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1441 '\\1\\2</a>\\3</a>\\1\\4</a>',
1442 # fix div inside inline elements- doBlockLevels won't wrap a line which
1443 # contains a div, so fix it up here; replace
1444 # div with escaped text
1445 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1446 '\\1\\3<div\\5>\\6</div>\\8\\9',
1447 # remove empty italic or bold tag pairs, some
1448 # introduced by rules above
1449 '/<([bi])><\/\\1>/' => '',
1452 $text = preg_replace(
1453 array_keys( $tidyregs ),
1454 array_values( $tidyregs ),
1459 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1466 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1467 * magic external links.
1472 * @param string $text
1476 public function doMagicLinks( $text ) {
1477 $prots = wfUrlProtocolsWithoutProtRel();
1478 $urlChar = self
::EXT_LINK_URL_CLASS
;
1479 $addr = self
::EXT_LINK_ADDR
;
1480 $space = self
::SPACE_NOT_NL
; # non-newline space
1481 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1482 $spaces = "$space++"; # possessive match of 1 or more spaces
1483 $text = preg_replace_callback(
1485 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1486 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1487 (\b # m[3]: Free external links
1489 ($addr$urlChar*) # m[4]: Post-protocol path
1491 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1493 \bISBN $spaces ( # m[6]: ISBN, capture number
1494 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1495 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1496 [0-9Xx] # check digit
1498 )!xu", [ $this, 'magicLinkCallback' ], $text );
1503 * @throws MWException
1505 * @return string HTML
1507 public function magicLinkCallback( $m ) {
1508 if ( isset( $m[1] ) && $m[1] !== '' ) {
1511 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1514 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1515 # Free external link
1516 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1517 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1519 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1520 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1525 $cssClass = 'mw-magiclink-rfc';
1526 $trackingCat = 'magiclink-tracking-rfc';
1528 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1529 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1533 $urlmsg = 'pubmedurl';
1534 $cssClass = 'mw-magiclink-pmid';
1535 $trackingCat = 'magiclink-tracking-pmid';
1538 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1539 substr( $m[0], 0, 20 ) . '"' );
1541 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1542 $this->addTrackingCategory( $trackingCat );
1543 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1544 } elseif ( isset( $m[6] ) && $m[6] !== ''
1545 && $this->mOptions
->getMagicISBNLinks()
1549 $space = self
::SPACE_NOT_NL
; # non-newline space
1550 $isbn = preg_replace( "/$space/", ' ', $isbn );
1551 $num = strtr( $isbn, [
1556 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1557 return $this->getLinkRenderer()->makeKnownLink(
1558 SpecialPage
::getTitleFor( 'Booksources', $num ),
1561 'class' => 'internal mw-magiclink-isbn',
1562 'title' => false // suppress title attribute
1571 * Make a free external link, given a user-supplied URL
1573 * @param string $url
1574 * @param int $numPostProto
1575 * The number of characters after the protocol.
1576 * @return string HTML
1579 public function makeFreeExternalLink( $url, $numPostProto ) {
1582 # The characters '<' and '>' (which were escaped by
1583 # removeHTMLtags()) should not be included in
1584 # URLs, per RFC 2396.
1585 # Make terminate a URL as well (bug T84937)
1588 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1593 $trail = substr( $url, $m2[0][1] ) . $trail;
1594 $url = substr( $url, 0, $m2[0][1] );
1597 # Move trailing punctuation to $trail
1599 # If there is no left bracket, then consider right brackets fair game too
1600 if ( strpos( $url, '(' ) === false ) {
1604 $urlRev = strrev( $url );
1605 $numSepChars = strspn( $urlRev, $sep );
1606 # Don't break a trailing HTML entity by moving the ; into $trail
1607 # This is in hot code, so use substr_compare to avoid having to
1608 # create a new string object for the comparison
1609 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1610 # more optimization: instead of running preg_match with a $
1611 # anchor, which can be slow, do the match on the reversed
1612 # string starting at the desired offset.
1613 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1614 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1618 if ( $numSepChars ) {
1619 $trail = substr( $url, -$numSepChars ) . $trail;
1620 $url = substr( $url, 0, -$numSepChars );
1623 # Verify that we still have a real URL after trail removal, and
1624 # not just lone protocol
1625 if ( strlen( $trail ) >= $numPostProto ) {
1626 return $url . $trail;
1629 $url = Sanitizer
::cleanUrl( $url );
1631 # Is this an external image?
1632 $text = $this->maybeMakeExternalImage( $url );
1633 if ( $text === false ) {
1634 # Not an image, make a link
1635 $text = Linker
::makeExternalLink( $url,
1636 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1638 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1639 # Register it in the output object...
1640 $this->mOutput
->addExternalLink( $url );
1642 return $text . $trail;
1646 * Parse headers and return html
1650 * @param string $text
1654 public function doHeadings( $text ) {
1655 for ( $i = 6; $i >= 1; --$i ) {
1656 $h = str_repeat( '=', $i );
1657 // Trim non-newline whitespace from headings
1658 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1659 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1665 * Replace single quotes with HTML markup
1668 * @param string $text
1670 * @return string The altered text
1672 public function doAllQuotes( $text ) {
1674 $lines = StringUtils
::explode( "\n", $text );
1675 foreach ( $lines as $line ) {
1676 $outtext .= $this->doQuotes( $line ) . "\n";
1678 $outtext = substr( $outtext, 0, -1 );
1683 * Helper function for doAllQuotes()
1685 * @param string $text
1689 public function doQuotes( $text ) {
1690 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1691 $countarr = count( $arr );
1692 if ( $countarr == 1 ) {
1696 // First, do some preliminary work. This may shift some apostrophes from
1697 // being mark-up to being text. It also counts the number of occurrences
1698 // of bold and italics mark-ups.
1701 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1702 $thislen = strlen( $arr[$i] );
1703 // If there are ever four apostrophes, assume the first is supposed to
1704 // be text, and the remaining three constitute mark-up for bold text.
1705 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1706 if ( $thislen == 4 ) {
1707 $arr[$i - 1] .= "'";
1710 } elseif ( $thislen > 5 ) {
1711 // If there are more than 5 apostrophes in a row, assume they're all
1712 // text except for the last 5.
1713 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1714 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1718 // Count the number of occurrences of bold and italics mark-ups.
1719 if ( $thislen == 2 ) {
1721 } elseif ( $thislen == 3 ) {
1723 } elseif ( $thislen == 5 ) {
1729 // If there is an odd number of both bold and italics, it is likely
1730 // that one of the bold ones was meant to be an apostrophe followed
1731 // by italics. Which one we cannot know for certain, but it is more
1732 // likely to be one that has a single-letter word before it.
1733 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1734 $firstsingleletterword = -1;
1735 $firstmultiletterword = -1;
1737 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1738 if ( strlen( $arr[$i] ) == 3 ) {
1739 $x1 = substr( $arr[$i - 1], -1 );
1740 $x2 = substr( $arr[$i - 1], -2, 1 );
1741 if ( $x1 === ' ' ) {
1742 if ( $firstspace == -1 ) {
1745 } elseif ( $x2 === ' ' ) {
1746 $firstsingleletterword = $i;
1747 // if $firstsingleletterword is set, we don't
1748 // look at the other options, so we can bail early.
1751 if ( $firstmultiletterword == -1 ) {
1752 $firstmultiletterword = $i;
1758 // If there is a single-letter word, use it!
1759 if ( $firstsingleletterword > -1 ) {
1760 $arr[$firstsingleletterword] = "''";
1761 $arr[$firstsingleletterword - 1] .= "'";
1762 } elseif ( $firstmultiletterword > -1 ) {
1763 // If not, but there's a multi-letter word, use that one.
1764 $arr[$firstmultiletterword] = "''";
1765 $arr[$firstmultiletterword - 1] .= "'";
1766 } elseif ( $firstspace > -1 ) {
1767 // ... otherwise use the first one that has neither.
1768 // (notice that it is possible for all three to be -1 if, for example,
1769 // there is only one pentuple-apostrophe in the line)
1770 $arr[$firstspace] = "''";
1771 $arr[$firstspace - 1] .= "'";
1775 // Now let's actually convert our apostrophic mush to HTML!
1780 foreach ( $arr as $r ) {
1781 if ( ( $i %
2 ) == 0 ) {
1782 if ( $state === 'both' ) {
1788 $thislen = strlen( $r );
1789 if ( $thislen == 2 ) {
1790 if ( $state === 'i' ) {
1793 } elseif ( $state === 'bi' ) {
1796 } elseif ( $state === 'ib' ) {
1797 $output .= '</b></i><b>';
1799 } elseif ( $state === 'both' ) {
1800 $output .= '<b><i>' . $buffer . '</i>';
1802 } else { // $state can be 'b' or ''
1806 } elseif ( $thislen == 3 ) {
1807 if ( $state === 'b' ) {
1810 } elseif ( $state === 'bi' ) {
1811 $output .= '</i></b><i>';
1813 } elseif ( $state === 'ib' ) {
1816 } elseif ( $state === 'both' ) {
1817 $output .= '<i><b>' . $buffer . '</b>';
1819 } else { // $state can be 'i' or ''
1823 } elseif ( $thislen == 5 ) {
1824 if ( $state === 'b' ) {
1825 $output .= '</b><i>';
1827 } elseif ( $state === 'i' ) {
1828 $output .= '</i><b>';
1830 } elseif ( $state === 'bi' ) {
1831 $output .= '</i></b>';
1833 } elseif ( $state === 'ib' ) {
1834 $output .= '</b></i>';
1836 } elseif ( $state === 'both' ) {
1837 $output .= '<i><b>' . $buffer . '</b></i>';
1839 } else { // ($state == '')
1847 // Now close all remaining tags. Notice that the order is important.
1848 if ( $state === 'b' ||
$state === 'ib' ) {
1851 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1854 if ( $state === 'bi' ) {
1857 // There might be lonely ''''', so make sure we have a buffer
1858 if ( $state === 'both' && $buffer ) {
1859 $output .= '<b><i>' . $buffer . '</i></b>';
1865 * Replace external links (REL)
1867 * Note: this is all very hackish and the order of execution matters a lot.
1868 * Make sure to run tests/parser/parserTests.php if you change this code.
1872 * @param string $text
1874 * @throws MWException
1877 public function replaceExternalLinks( $text ) {
1878 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1879 if ( $bits === false ) {
1880 throw new MWException( "PCRE needs to be compiled with "
1881 . "--enable-unicode-properties in order for MediaWiki to function" );
1883 $s = array_shift( $bits );
1886 while ( $i < count( $bits ) ) {
1889 $text = $bits[$i++
];
1890 $trail = $bits[$i++
];
1892 # The characters '<' and '>' (which were escaped by
1893 # removeHTMLtags()) should not be included in
1894 # URLs, per RFC 2396.
1896 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1897 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1898 $url = substr( $url, 0, $m2[0][1] );
1901 # If the link text is an image URL, replace it with an <img> tag
1902 # This happened by accident in the original parser, but some people used it extensively
1903 $img = $this->maybeMakeExternalImage( $text );
1904 if ( $img !== false ) {
1910 # Set linktype for CSS
1913 # No link text, e.g. [http://domain.tld/some.link]
1914 if ( $text == '' ) {
1916 $langObj = $this->getTargetLanguage();
1917 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1918 $linktype = 'autonumber';
1920 # Have link text, e.g. [http://domain.tld/some.link text]s
1922 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1925 // Excluding protocol-relative URLs may avoid many false positives.
1926 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1927 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1930 $url = Sanitizer
::cleanUrl( $url );
1932 # Use the encoded URL
1933 # This means that users can paste URLs directly into the text
1934 # Funny characters like ö aren't valid in URLs anyway
1935 # This was changed in August 2004
1936 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1937 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1939 # Register link in the output object.
1940 $this->mOutput
->addExternalLink( $url );
1947 * Get the rel attribute for a particular external link.
1950 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1951 * nofollow if appropriate
1952 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1953 * @return string|null Rel attribute for $url
1955 public static function getExternalLinkRel( $url = false, $title = null ) {
1956 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1957 $ns = $title ?
$title->getNamespace() : false;
1958 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1959 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1967 * Get an associative array of additional HTML attributes appropriate for a
1968 * particular external link. This currently may include rel => nofollow
1969 * (depending on configuration, namespace, and the URL's domain) and/or a
1970 * target attribute (depending on configuration).
1972 * @param string $url URL to extract the domain from for rel =>
1973 * nofollow if appropriate
1974 * @return array Associative array of HTML attributes
1976 public function getExternalLinkAttribs( $url ) {
1978 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1980 $target = $this->mOptions
->getExternalLinkTarget();
1982 $attribs['target'] = $target;
1983 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1984 // T133507. New windows can navigate parent cross-origin.
1985 // Including noreferrer due to lacking browser
1986 // support of noopener. Eventually noreferrer should be removed.
1987 if ( $rel !== '' ) {
1990 $rel .= 'noreferrer noopener';
1993 $attribs['rel'] = $rel;
1998 * Replace unusual escape codes in a URL with their equivalent characters
2000 * This generally follows the syntax defined in RFC 3986, with special
2001 * consideration for HTTP query strings.
2003 * @param string $url
2006 public static function normalizeLinkUrl( $url ) {
2007 # First, make sure unsafe characters are encoded
2008 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2010 return rawurlencode( $m[0] );
2016 $end = strlen( $url );
2018 # Fragment part - 'fragment'
2019 $start = strpos( $url, '#' );
2020 if ( $start !== false && $start < $end ) {
2021 $ret = self
::normalizeUrlComponent(
2022 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2026 # Query part - 'query' minus &=+;
2027 $start = strpos( $url, '?' );
2028 if ( $start !== false && $start < $end ) {
2029 $ret = self
::normalizeUrlComponent(
2030 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2034 # Scheme and path part - 'pchar'
2035 # (we assume no userinfo or encoded colons in the host)
2036 $ret = self
::normalizeUrlComponent(
2037 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2042 private static function normalizeUrlComponent( $component, $unsafe ) {
2043 $callback = function ( $matches ) use ( $unsafe ) {
2044 $char = urldecode( $matches[0] );
2045 $ord = ord( $char );
2046 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2050 # Leave it escaped, but use uppercase for a-f
2051 return strtoupper( $matches[0] );
2054 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2058 * make an image if it's allowed, either through the global
2059 * option, through the exception, or through the on-wiki whitelist
2061 * @param string $url
2065 private function maybeMakeExternalImage( $url ) {
2066 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2067 $imagesexception = !empty( $imagesfrom );
2069 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2070 if ( $imagesexception && is_array( $imagesfrom ) ) {
2071 $imagematch = false;
2072 foreach ( $imagesfrom as $match ) {
2073 if ( strpos( $url, $match ) === 0 ) {
2078 } elseif ( $imagesexception ) {
2079 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2081 $imagematch = false;
2084 if ( $this->mOptions
->getAllowExternalImages()
2085 ||
( $imagesexception && $imagematch )
2087 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2089 $text = Linker
::makeExternalImage( $url );
2092 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2093 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2095 $whitelist = explode(
2097 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2100 foreach ( $whitelist as $entry ) {
2101 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2102 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2105 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2106 # Image matches a whitelist entry
2107 $text = Linker
::makeExternalImage( $url );
2116 * Process [[ ]] wikilinks
2120 * @return string Processed text
2124 public function replaceInternalLinks( $s ) {
2125 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2130 * Process [[ ]] wikilinks (RIL)
2132 * @throws MWException
2133 * @return LinkHolderArray
2137 public function replaceInternalLinks2( &$s ) {
2138 global $wgExtraInterlanguageLinkPrefixes;
2140 static $tc = false, $e1, $e1_img;
2141 # the % is needed to support urlencoded titles as well
2143 $tc = Title
::legalChars() . '#%';
2144 # Match a link having the form [[namespace:link|alternate]]trail
2145 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2146 # Match cases where there is no "]]", which might still be images
2147 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2150 $holders = new LinkHolderArray( $this );
2152 # split the entire text string on occurrences of [[
2153 $a = StringUtils
::explode( '[[', ' ' . $s );
2154 # get the first element (all text up to first [[), and remove the space we added
2157 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2158 $s = substr( $s, 1 );
2160 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2162 if ( $useLinkPrefixExtension ) {
2163 # Match the end of a line for a word that's not followed by whitespace,
2164 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2165 $charset = $this->contLang
->linkPrefixCharset();
2166 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2169 if ( is_null( $this->mTitle
) ) {
2170 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2172 $nottalk = !$this->mTitle
->isTalkPage();
2174 if ( $useLinkPrefixExtension ) {
2176 if ( preg_match( $e2, $s, $m ) ) {
2177 $first_prefix = $m[2];
2179 $first_prefix = false;
2185 $useSubpages = $this->areSubpagesAllowed();
2187 # Loop for each link
2188 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2189 # Check for excessive memory usage
2190 if ( $holders->isBig() ) {
2192 # Do the existence check, replace the link holders and clear the array
2193 $holders->replace( $s );
2197 if ( $useLinkPrefixExtension ) {
2198 if ( preg_match( $e2, $s, $m ) ) {
2205 if ( $first_prefix ) {
2206 $prefix = $first_prefix;
2207 $first_prefix = false;
2211 $might_be_img = false;
2213 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2215 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2216 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2217 # the real problem is with the $e1 regex
2219 # Still some problems for cases where the ] is meant to be outside punctuation,
2220 # and no image is in sight. See T4095.
2222 && substr( $m[3], 0, 1 ) === ']'
2223 && strpos( $text, '[' ) !== false
2225 $text .= ']'; # so that replaceExternalLinks($text) works later
2226 $m[3] = substr( $m[3], 1 );
2228 # fix up urlencoded title texts
2229 if ( strpos( $m[1], '%' ) !== false ) {
2230 # Should anchors '#' also be rejected?
2231 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2234 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2235 # Invalid, but might be an image with a link in its caption
2236 $might_be_img = true;
2238 if ( strpos( $m[1], '%' ) !== false ) {
2239 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2242 } else { # Invalid form; output directly
2243 $s .= $prefix . '[[' . $line;
2247 $origLink = ltrim( $m[1], ' ' );
2249 # Don't allow internal links to pages containing
2250 # PROTO: where PROTO is a valid URL protocol; these
2251 # should be external links.
2252 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2253 $s .= $prefix . '[[' . $line;
2257 # Make subpage if necessary
2258 if ( $useSubpages ) {
2259 $link = $this->maybeDoSubpageLink( $origLink, $text );
2264 // \x7f isn't a default legal title char, so most likely strip
2265 // markers will force us into the "invalid form" path above. But,
2266 // just in case, let's assert that xmlish tags aren't valid in
2267 // the title position.
2268 $unstrip = $this->mStripState
->killMarkers( $link );
2269 $noMarkers = ( $unstrip === $link );
2271 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2272 if ( $nt === null ) {
2273 $s .= $prefix . '[[' . $line;
2277 $ns = $nt->getNamespace();
2278 $iw = $nt->getInterwiki();
2280 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2282 if ( $might_be_img ) { # if this is actually an invalid link
2283 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2286 # look at the next 'line' to see if we can close it there
2288 $next_line = $a->current();
2289 if ( $next_line === false ||
$next_line === null ) {
2292 $m = explode( ']]', $next_line, 3 );
2293 if ( count( $m ) == 3 ) {
2294 # the first ]] closes the inner link, the second the image
2296 $text .= "[[{$m[0]}]]{$m[1]}";
2299 } elseif ( count( $m ) == 2 ) {
2300 # if there's exactly one ]] that's fine, we'll keep looking
2301 $text .= "[[{$m[0]}]]{$m[1]}";
2303 # if $next_line is invalid too, we need look no further
2304 $text .= '[[' . $next_line;
2309 # we couldn't find the end of this imageLink, so output it raw
2310 # but don't ignore what might be perfectly normal links in the text we've examined
2311 $holders->merge( $this->replaceInternalLinks2( $text ) );
2312 $s .= "{$prefix}[[$link|$text";
2313 # note: no $trail, because without an end, there *is* no trail
2316 } else { # it's not an image, so output it raw
2317 $s .= "{$prefix}[[$link|$text";
2318 # note: no $trail, because without an end, there *is* no trail
2323 $wasblank = ( $text == '' );
2327 # Strip off leading ':'
2328 $text = substr( $text, 1 );
2331 # T6598 madness. Handle the quotes only if they come from the alternate part
2332 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2333 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2334 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2335 $text = $this->doQuotes( $text );
2338 # Link not escaped by : , create the various objects
2339 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2342 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2343 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2344 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2347 # T26502: filter duplicates
2348 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2349 $this->mLangLinkLanguages
[$iw] = true;
2350 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2354 * Strip the whitespace interwiki links produce, see T10897
2356 $s = rtrim( $s . $prefix ) . $trail; # T175416
2360 if ( $ns == NS_FILE
) {
2361 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2363 # if no parameters were passed, $text
2364 # becomes something like "File:Foo.png",
2365 # which we don't want to pass on to the
2369 # recursively parse links inside the image caption
2370 # actually, this will parse them in any other parameters, too,
2371 # but it might be hard to fix that, and it doesn't matter ATM
2372 $text = $this->replaceExternalLinks( $text );
2373 $holders->merge( $this->replaceInternalLinks2( $text ) );
2375 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2376 $s .= $prefix . $this->armorLinks(
2377 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2380 } elseif ( $ns == NS_CATEGORY
) {
2382 * Strip the whitespace Category links produce, see T2087
2384 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2387 $sortkey = $this->getDefaultSort();
2391 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2392 $sortkey = str_replace( "\n", '', $sortkey );
2393 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2394 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2400 # Self-link checking. For some languages, variants of the title are checked in
2401 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2402 # for linking to a different variant.
2403 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2404 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2408 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2409 # @todo FIXME: Should do batch file existence checks, see comment below
2410 if ( $ns == NS_MEDIA
) {
2411 # Give extensions a chance to select the file revision for us
2414 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2415 [ $this, $nt, &$options, &$descQuery ] );
2416 # Fetch and register the file (file title may be different via hooks)
2417 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2418 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2419 $s .= $prefix . $this->armorLinks(
2420 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2424 # Some titles, such as valid special pages or files in foreign repos, should
2425 # be shown as bluelinks even though they're not included in the page table
2426 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2427 # batch file existence checks for NS_FILE and NS_MEDIA
2428 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2429 $this->mOutput
->addLink( $nt );
2430 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2432 # Links will be added to the output link list after checking
2433 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2440 * Render a forced-blue link inline; protect against double expansion of
2441 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2442 * Since this little disaster has to split off the trail text to avoid
2443 * breaking URLs in the following text without breaking trails on the
2444 * wiki links, it's been made into a horrible function.
2447 * @param string $text
2448 * @param string $trail
2449 * @param string $prefix
2450 * @return string HTML-wikitext mix oh yuck
2452 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2453 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2455 if ( $text == '' ) {
2456 $text = htmlspecialchars( $nt->getPrefixedText() );
2459 $link = $this->getLinkRenderer()->makeKnownLink(
2460 $nt, new HtmlArmor( "$prefix$text$inside" )
2463 return $this->armorLinks( $link ) . $trail;
2467 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2468 * going to go through further parsing steps before inline URL expansion.
2470 * Not needed quite as much as it used to be since free links are a bit
2471 * more sensible these days. But bracketed links are still an issue.
2473 * @param string $text More-or-less HTML
2474 * @return string Less-or-more HTML with NOPARSE bits
2476 public function armorLinks( $text ) {
2477 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2478 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2482 * Return true if subpage links should be expanded on this page.
2485 public function areSubpagesAllowed() {
2486 # Some namespaces don't allow subpages
2487 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2491 * Handle link to subpage if necessary
2493 * @param string $target The source of the link
2494 * @param string &$text The link text, modified as necessary
2495 * @return string The full name of the link
2498 public function maybeDoSubpageLink( $target, &$text ) {
2499 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2503 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2505 * @param string $text
2506 * @param bool $linestart Whether or not this is at the start of a line.
2508 * @return string The lists rendered as HTML
2510 public function doBlockLevels( $text, $linestart ) {
2511 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2515 * Return value of a magic variable (like PAGENAME)
2519 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2520 * @param bool|PPFrame $frame
2522 * @throws MWException
2525 public function getVariableValue( $index, $frame = false ) {
2526 global $wgSitename, $wgServer, $wgServerName;
2527 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2529 if ( is_null( $this->mTitle
) ) {
2530 // If no title set, bad things are going to happen
2531 // later. Title should always be set since this
2532 // should only be called in the middle of a parse
2533 // operation (but the unit-tests do funky stuff)
2534 throw new MWException( __METHOD__
. ' Should only be '
2535 . ' called while parsing (no title set)' );
2538 // Avoid PHP 7.1 warning from passing $this by reference
2542 * Some of these require message or data lookups and can be
2543 * expensive to check many times.
2545 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2546 if ( isset( $this->mVarCache
[$index] ) ) {
2547 return $this->mVarCache
[$index];
2551 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2552 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2554 $pageLang = $this->getFunctionLang();
2560 case 'currentmonth':
2561 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2563 case 'currentmonth1':
2564 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2566 case 'currentmonthname':
2567 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2569 case 'currentmonthnamegen':
2570 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2572 case 'currentmonthabbrev':
2573 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2576 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2579 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2582 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2585 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2587 case 'localmonthname':
2588 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2590 case 'localmonthnamegen':
2591 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2593 case 'localmonthabbrev':
2594 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2597 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2600 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2603 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2606 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2608 case 'fullpagename':
2609 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2611 case 'fullpagenamee':
2612 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2615 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2617 case 'subpagenamee':
2618 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2620 case 'rootpagename':
2621 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2623 case 'rootpagenamee':
2624 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2627 $this->mTitle
->getRootText()
2630 case 'basepagename':
2631 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2633 case 'basepagenamee':
2634 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2637 $this->mTitle
->getBaseText()
2640 case 'talkpagename':
2641 if ( $this->mTitle
->canHaveTalkPage() ) {
2642 $talkPage = $this->mTitle
->getTalkPage();
2643 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2648 case 'talkpagenamee':
2649 if ( $this->mTitle
->canHaveTalkPage() ) {
2650 $talkPage = $this->mTitle
->getTalkPage();
2651 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2656 case 'subjectpagename':
2657 $subjPage = $this->mTitle
->getSubjectPage();
2658 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2660 case 'subjectpagenamee':
2661 $subjPage = $this->mTitle
->getSubjectPage();
2662 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2664 case 'pageid': // requested in T25427
2665 $pageid = $this->getTitle()->getArticleID();
2666 if ( $pageid == 0 ) {
2667 # 0 means the page doesn't exist in the database,
2668 # which means the user is previewing a new page.
2669 # The vary-revision flag must be set, because the magic word
2670 # will have a different value once the page is saved.
2671 $this->mOutput
->setFlag( 'vary-revision' );
2672 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2674 $value = $pageid ?
: null;
2677 # Let the edit saving system know we should parse the page
2678 # *after* a revision ID has been assigned.
2679 $this->mOutput
->setFlag( 'vary-revision-id' );
2680 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2681 $value = $this->mRevisionId
;
2682 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2683 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2684 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2688 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2690 case 'revisionday2':
2691 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2693 case 'revisionmonth':
2694 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2696 case 'revisionmonth1':
2697 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2699 case 'revisionyear':
2700 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2702 case 'revisiontimestamp':
2703 # Let the edit saving system know we should parse the page
2704 # *after* a revision ID has been assigned. This is for null edits.
2705 $this->mOutput
->setFlag( 'vary-revision' );
2706 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2707 $value = $this->getRevisionTimestamp();
2709 case 'revisionuser':
2710 # Let the edit saving system know we should parse the page
2711 # *after* a revision ID has been assigned for null edits.
2712 $this->mOutput
->setFlag( 'vary-user' );
2713 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2714 $value = $this->getRevisionUser();
2716 case 'revisionsize':
2717 $value = $this->getRevisionSize();
2720 $value = str_replace( '_', ' ',
2721 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2724 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2726 case 'namespacenumber':
2727 $value = $this->mTitle
->getNamespace();
2730 $value = $this->mTitle
->canHaveTalkPage()
2731 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2735 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2737 case 'subjectspace':
2738 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2740 case 'subjectspacee':
2741 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2743 case 'currentdayname':
2744 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2747 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2750 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2753 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $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
::getInstance( $ts )->format( 'W' ) );
2761 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2763 case 'localdayname':
2764 $value = $pageLang->getWeekdayName(
2765 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2769 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2772 $value = $pageLang->time(
2773 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2779 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2782 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2783 # int to remove the padding
2784 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2787 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2789 case 'numberofarticles':
2790 $value = $pageLang->formatNum( SiteStats
::articles() );
2792 case 'numberoffiles':
2793 $value = $pageLang->formatNum( SiteStats
::images() );
2795 case 'numberofusers':
2796 $value = $pageLang->formatNum( SiteStats
::users() );
2798 case 'numberofactiveusers':
2799 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2801 case 'numberofpages':
2802 $value = $pageLang->formatNum( SiteStats
::pages() );
2804 case 'numberofadmins':
2805 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2807 case 'numberofedits':
2808 $value = $pageLang->formatNum( SiteStats
::edits() );
2810 case 'currenttimestamp':
2811 $value = wfTimestamp( TS_MW
, $ts );
2813 case 'localtimestamp':
2814 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2816 case 'currentversion':
2817 $value = SpecialVersion
::getVersion();
2820 return $wgArticlePath;
2826 return $wgServerName;
2828 return $wgScriptPath;
2830 return $wgStylePath;
2831 case 'directionmark':
2832 return $pageLang->getDirMark();
2833 case 'contentlanguage':
2834 global $wgLanguageCode;
2835 return $wgLanguageCode;
2836 case 'pagelanguage':
2837 $value = $pageLang->getCode();
2839 case 'cascadingsources':
2840 $value = CoreParserFunctions
::cascadingsources( $this );
2845 'ParserGetVariableValueSwitch',
2846 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2853 $this->mVarCache
[$index] = $value;
2862 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2863 * @param string $variable Parser variable name
2866 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2867 # Get the timezone-adjusted timestamp to be used for this revision
2868 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2869 # Possibly set vary-revision if there is not yet an associated revision
2870 if ( !$this->getRevisionObject() ) {
2871 # Get the timezone-adjusted timestamp $mtts seconds in the future
2873 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2878 if ( $resNow !== $resThen ) {
2879 # Let the edit saving system know we should parse the page
2880 # *after* a revision ID has been assigned. This is for null edits.
2881 $this->mOutput
->setFlag( 'vary-revision' );
2882 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2890 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2894 public function initialiseVariables() {
2895 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2896 $substIDs = $this->magicWordFactory
->getSubstIDs();
2898 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2899 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2903 * Preprocess some wikitext and return the document tree.
2904 * This is the ghost of replace_variables().
2906 * @param string $text The text to parse
2907 * @param int $flags Bitwise combination of:
2908 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2909 * included. Default is to assume a direct page view.
2911 * The generated DOM tree must depend only on the input text and the flags.
2912 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2914 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2915 * change in the DOM tree for a given text, must be passed through the section identifier
2916 * in the section edit link and thus back to extractSections().
2918 * The output of this function is currently only cached in process memory, but a persistent
2919 * cache may be implemented at a later date which takes further advantage of these strict
2920 * dependency requirements.
2924 public function preprocessToDom( $text, $flags = 0 ) {
2925 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2930 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2936 public static function splitWhitespace( $s ) {
2937 $ltrimmed = ltrim( $s );
2938 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2939 $trimmed = rtrim( $ltrimmed );
2940 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2942 $w2 = substr( $ltrimmed, -$diff );
2946 return [ $w1, $trimmed, $w2 ];
2950 * Replace magic variables, templates, and template arguments
2951 * with the appropriate text. Templates are substituted recursively,
2952 * taking care to avoid infinite loops.
2954 * Note that the substitution depends on value of $mOutputType:
2955 * self::OT_WIKI: only {{subst:}} templates
2956 * self::OT_PREPROCESS: templates but not extension tags
2957 * self::OT_HTML: all templates and extension tags
2959 * @param string $text The text to transform
2960 * @param bool|PPFrame $frame Object describing the arguments passed to the
2961 * template. Arguments may also be provided as an associative array, as
2962 * was the usual case before MW1.12. Providing arguments this way may be
2963 * useful for extensions wishing to perform variable replacement
2965 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2966 * double-brace expansion.
2969 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2970 # Is there any text? Also, Prevent too big inclusions!
2971 $textSize = strlen( $text );
2972 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2976 if ( $frame === false ) {
2977 $frame = $this->getPreprocessor()->newFrame();
2978 } elseif ( !( $frame instanceof PPFrame
) ) {
2979 wfDebug( __METHOD__
. " called using plain parameters instead of "
2980 . "a PPFrame instance. Creating custom frame.\n" );
2981 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2984 $dom = $this->preprocessToDom( $text );
2985 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2986 $text = $frame->expand( $dom, $flags );
2992 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2994 * @param array $args
2998 public static function createAssocArgs( $args ) {
3001 foreach ( $args as $arg ) {
3002 $eqpos = strpos( $arg, '=' );
3003 if ( $eqpos === false ) {
3004 $assocArgs[$index++
] = $arg;
3006 $name = trim( substr( $arg, 0, $eqpos ) );
3007 $value = trim( substr( $arg, $eqpos +
1 ) );
3008 if ( $value === false ) {
3011 if ( $name !== false ) {
3012 $assocArgs[$name] = $value;
3021 * Warn the user when a parser limitation is reached
3022 * Will warn at most once the user per limitation type
3024 * The results are shown during preview and run through the Parser (See EditPage.php)
3026 * @param string $limitationType Should be one of:
3027 * 'expensive-parserfunction' (corresponding messages:
3028 * 'expensive-parserfunction-warning',
3029 * 'expensive-parserfunction-category')
3030 * 'post-expand-template-argument' (corresponding messages:
3031 * 'post-expand-template-argument-warning',
3032 * 'post-expand-template-argument-category')
3033 * 'post-expand-template-inclusion' (corresponding messages:
3034 * 'post-expand-template-inclusion-warning',
3035 * 'post-expand-template-inclusion-category')
3036 * 'node-count-exceeded' (corresponding messages:
3037 * 'node-count-exceeded-warning',
3038 * 'node-count-exceeded-category')
3039 * 'expansion-depth-exceeded' (corresponding messages:
3040 * 'expansion-depth-exceeded-warning',
3041 * 'expansion-depth-exceeded-category')
3042 * @param string|int|null $current Current value
3043 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3044 * exceeded, provide the values (optional)
3046 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3047 # does no harm if $current and $max are present but are unnecessary for the message
3048 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3049 # only during preview, and that would split the parser cache unnecessarily.
3050 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3052 $this->mOutput
->addWarning( $warning );
3053 $this->addTrackingCategory( "$limitationType-category" );
3057 * Return the text of a template, after recursively
3058 * replacing any variables or templates within the template.
3060 * @param array $piece The parts of the template
3061 * $piece['title']: the title, i.e. the part before the |
3062 * $piece['parts']: the parameter array
3063 * $piece['lineStart']: whether the brace was at the start of a line
3064 * @param PPFrame $frame The current frame, contains template arguments
3066 * @return string The text of the template
3068 public function braceSubstitution( $piece, $frame ) {
3071 // $text has been filled
3073 // wiki markup in $text should be escaped
3075 // $text is HTML, armour it against wikitext transformation
3077 // Force interwiki transclusion to be done in raw mode not rendered
3078 $forceRawInterwiki = false;
3079 // $text is a DOM node needing expansion in a child frame
3080 $isChildObj = false;
3081 // $text is a DOM node needing expansion in the current frame
3082 $isLocalObj = false;
3084 # Title object, where $text came from
3087 # $part1 is the bit before the first |, and must contain only title characters.
3088 # Various prefixes will be stripped from it later.
3089 $titleWithSpaces = $frame->expand( $piece['title'] );
3090 $part1 = trim( $titleWithSpaces );
3093 # Original title text preserved for various purposes
3094 $originalTitle = $part1;
3096 # $args is a list of argument nodes, starting from index 0, not including $part1
3097 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3098 # below won't work b/c this $args isn't an object
3099 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3101 $profileSection = null; // profile templates
3105 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3107 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3108 # Decide whether to expand template or keep wikitext as-is.
3109 if ( $this->ot
['wiki'] ) {
3110 if ( $substMatch === false ) {
3111 $literal = true; # literal when in PST with no prefix
3113 $literal = false; # expand when in PST with subst: or safesubst:
3116 if ( $substMatch == 'subst' ) {
3117 $literal = true; # literal when not in PST with plain subst:
3119 $literal = false; # expand when not in PST with safesubst: or no prefix
3123 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3130 if ( !$found && $args->getLength() == 0 ) {
3131 $id = $this->mVariables
->matchStartToEnd( $part1 );
3132 if ( $id !== false ) {
3133 $text = $this->getVariableValue( $id, $frame );
3134 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3135 $this->mOutput
->updateCacheExpiry(
3136 $this->magicWordFactory
->getCacheTTL( $id ) );
3142 # MSG, MSGNW and RAW
3145 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3146 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3149 # Remove obsolete MSG:
3150 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3151 $mwMsg->matchStartAndRemove( $part1 );
3155 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3156 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3157 $forceRawInterwiki = true;
3163 $colonPos = strpos( $part1, ':' );
3164 if ( $colonPos !== false ) {
3165 $func = substr( $part1, 0, $colonPos );
3166 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3167 $argsLength = $args->getLength();
3168 for ( $i = 0; $i < $argsLength; $i++
) {
3169 $funcArgs[] = $args->item( $i );
3172 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3174 // Extract any forwarded flags
3175 if ( isset( $result['title'] ) ) {
3176 $title = $result['title'];
3178 if ( isset( $result['found'] ) ) {
3179 $found = $result['found'];
3181 if ( array_key_exists( 'text', $result ) ) {
3183 $text = $result['text'];
3185 if ( isset( $result['nowiki'] ) ) {
3186 $nowiki = $result['nowiki'];
3188 if ( isset( $result['isHTML'] ) ) {
3189 $isHTML = $result['isHTML'];
3191 if ( isset( $result['forceRawInterwiki'] ) ) {
3192 $forceRawInterwiki = $result['forceRawInterwiki'];
3194 if ( isset( $result['isChildObj'] ) ) {
3195 $isChildObj = $result['isChildObj'];
3197 if ( isset( $result['isLocalObj'] ) ) {
3198 $isLocalObj = $result['isLocalObj'];
3203 # Finish mangling title and then check for loops.
3204 # Set $title to a Title object and $titleText to the PDBK
3207 # Split the title into page and subpage
3209 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3210 if ( $part1 !== $relative ) {
3212 $ns = $this->mTitle
->getNamespace();
3214 $title = Title
::newFromText( $part1, $ns );
3216 $titleText = $title->getPrefixedText();
3217 # Check for language variants if the template is not found
3218 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3219 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3221 # Do recursion depth check
3222 $limit = $this->mOptions
->getMaxTemplateDepth();
3223 if ( $frame->depth
>= $limit ) {
3225 $text = '<span class="error">'
3226 . wfMessage( 'parser-template-recursion-depth-warning' )
3227 ->numParams( $limit )->inContentLanguage()->text()
3233 # Load from database
3234 if ( !$found && $title ) {
3235 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3236 if ( !$title->isExternal() ) {
3237 if ( $title->isSpecialPage()
3238 && $this->mOptions
->getAllowSpecialInclusion()
3239 && $this->ot
['html']
3241 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3242 // Pass the template arguments as URL parameters.
3243 // "uselang" will have no effect since the Language object
3244 // is forced to the one defined in ParserOptions.
3246 $argsLength = $args->getLength();
3247 for ( $i = 0; $i < $argsLength; $i++
) {
3248 $bits = $args->item( $i )->splitArg();
3249 if ( strval( $bits['index'] ) === '' ) {
3250 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3251 $value = trim( $frame->expand( $bits['value'] ) );
3252 $pageArgs[$name] = $value;
3256 // Create a new context to execute the special page
3257 $context = new RequestContext
;
3258 $context->setTitle( $title );
3259 $context->setRequest( new FauxRequest( $pageArgs ) );
3260 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3261 $context->setUser( $this->getUser() );
3263 // If this page is cached, then we better not be per user.
3264 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3266 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3267 $ret = SpecialPageFactory
::capturePath(
3268 $title, $context, $this->getLinkRenderer() );
3270 $text = $context->getOutput()->getHTML();
3271 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3274 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3275 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3276 $specialPage->maxIncludeCacheTime()
3280 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3281 $found = false; # access denied
3282 wfDebug( __METHOD__
. ": template inclusion denied for " .
3283 $title->getPrefixedDBkey() . "\n" );
3285 list( $text, $title ) = $this->getTemplateDom( $title );
3286 if ( $text !== false ) {
3292 # If the title is valid but undisplayable, make a link to it
3293 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3294 $text = "[[:$titleText]]";
3297 } elseif ( $title->isTrans() ) {
3298 # Interwiki transclusion
3299 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3300 $text = $this->interwikiTransclude( $title, 'render' );
3303 $text = $this->interwikiTransclude( $title, 'raw' );
3304 # Preprocess it like a template
3305 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3311 # Do infinite loop check
3312 # This has to be done after redirect resolution to avoid infinite loops via redirects
3313 if ( !$frame->loopCheck( $title ) ) {
3315 $text = '<span class="error">'
3316 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3318 $this->addTrackingCategory( 'template-loop-category' );
3319 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3320 wfEscapeWikiText( $titleText ) )->text() );
3321 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3325 # If we haven't found text to substitute by now, we're done
3326 # Recover the source wikitext and return it
3328 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3329 if ( $profileSection ) {
3330 $this->mProfiler
->scopedProfileOut( $profileSection );
3332 return [ 'object' => $text ];
3335 # Expand DOM-style return values in a child frame
3336 if ( $isChildObj ) {
3337 # Clean up argument array
3338 $newFrame = $frame->newChild( $args, $title );
3341 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3342 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3343 # Expansion is eligible for the empty-frame cache
3344 $text = $newFrame->cachedExpand( $titleText, $text );
3346 # Uncached expansion
3347 $text = $newFrame->expand( $text );
3350 if ( $isLocalObj && $nowiki ) {
3351 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3352 $isLocalObj = false;
3355 if ( $profileSection ) {
3356 $this->mProfiler
->scopedProfileOut( $profileSection );
3359 # Replace raw HTML by a placeholder
3361 $text = $this->insertStripItem( $text );
3362 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3363 # Escape nowiki-style return values
3364 $text = wfEscapeWikiText( $text );
3365 } elseif ( is_string( $text )
3366 && !$piece['lineStart']
3367 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3369 # T2529: if the template begins with a table or block-level
3370 # element, it should be treated as beginning a new line.
3371 # This behavior is somewhat controversial.
3372 $text = "\n" . $text;
3375 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3376 # Error, oversize inclusion
3377 if ( $titleText !== false ) {
3378 # Make a working, properly escaped link if possible (T25588)
3379 $text = "[[:$titleText]]";
3381 # This will probably not be a working link, but at least it may
3382 # provide some hint of where the problem is
3383 preg_replace( '/^:/', '', $originalTitle );
3384 $text = "[[:$originalTitle]]";
3386 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3387 . 'post-expand include size too large -->' );
3388 $this->limitationWarn( 'post-expand-template-inclusion' );
3391 if ( $isLocalObj ) {
3392 $ret = [ 'object' => $text ];
3394 $ret = [ 'text' => $text ];
3401 * Call a parser function and return an array with text and flags.
3403 * The returned array will always contain a boolean 'found', indicating
3404 * whether the parser function was found or not. It may also contain the
3406 * text: string|object, resulting wikitext or PP DOM object
3407 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3408 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3409 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3410 * nowiki: bool, wiki markup in $text should be escaped
3413 * @param PPFrame $frame The current frame, contains template arguments
3414 * @param string $function Function name
3415 * @param array $args Arguments to the function
3416 * @throws MWException
3419 public function callParserFunction( $frame, $function, array $args = [] ) {
3420 # Case sensitive functions
3421 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3422 $function = $this->mFunctionSynonyms
[1][$function];
3424 # Case insensitive functions
3425 $function = $this->contLang
->lc( $function );
3426 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3427 $function = $this->mFunctionSynonyms
[0][$function];
3429 return [ 'found' => false ];
3433 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3435 // Avoid PHP 7.1 warning from passing $this by reference
3438 $allArgs = [ &$parser ];
3439 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3440 # Convert arguments to PPNodes and collect for appending to $allArgs
3442 foreach ( $args as $k => $v ) {
3443 if ( $v instanceof PPNode ||
$k === 0 ) {
3446 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3450 # Add a frame parameter, and pass the arguments as an array
3451 $allArgs[] = $frame;
3452 $allArgs[] = $funcArgs;
3454 # Convert arguments to plain text and append to $allArgs
3455 foreach ( $args as $k => $v ) {
3456 if ( $v instanceof PPNode
) {
3457 $allArgs[] = trim( $frame->expand( $v ) );
3458 } elseif ( is_int( $k ) && $k >= 0 ) {
3459 $allArgs[] = trim( $v );
3461 $allArgs[] = trim( "$k=$v" );
3466 $result = $callback( ...$allArgs );
3468 # The interface for function hooks allows them to return a wikitext
3469 # string or an array containing the string and any flags. This mungs
3470 # things around to match what this method should return.
3471 if ( !is_array( $result ) ) {
3477 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3478 $result['text'] = $result[0];
3480 unset( $result[0] );
3487 $preprocessFlags = 0;
3488 if ( isset( $result['noparse'] ) ) {
3489 $noparse = $result['noparse'];
3491 if ( isset( $result['preprocessFlags'] ) ) {
3492 $preprocessFlags = $result['preprocessFlags'];
3496 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3497 $result['isChildObj'] = true;
3504 * Get the semi-parsed DOM representation of a template with a given title,
3505 * and its redirect destination title. Cached.
3507 * @param Title $title
3511 public function getTemplateDom( $title ) {
3512 $cacheTitle = $title;
3513 $titleText = $title->getPrefixedDBkey();
3515 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3516 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3517 $title = Title
::makeTitle( $ns, $dbk );
3518 $titleText = $title->getPrefixedDBkey();
3520 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3521 return [ $this->mTplDomCache
[$titleText], $title ];
3524 # Cache miss, go to the database
3525 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3527 if ( $text === false ) {
3528 $this->mTplDomCache
[$titleText] = false;
3529 return [ false, $title ];
3532 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3533 $this->mTplDomCache
[$titleText] = $dom;
3535 if ( !$title->equals( $cacheTitle ) ) {
3536 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3537 [ $title->getNamespace(), $title->getDBkey() ];
3540 return [ $dom, $title ];
3544 * Fetch the current revision of a given title. Note that the revision
3545 * (and even the title) may not exist in the database, so everything
3546 * contributing to the output of the parser should use this method
3547 * where possible, rather than getting the revisions themselves. This
3548 * method also caches its results, so using it benefits performance.
3551 * @param Title $title
3554 public function fetchCurrentRevisionOfTitle( $title ) {
3555 $cacheKey = $title->getPrefixedDBkey();
3556 if ( !$this->currentRevisionCache
) {
3557 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3559 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3560 $this->currentRevisionCache
->set( $cacheKey,
3561 // Defaults to Parser::statelessFetchRevision()
3562 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3565 return $this->currentRevisionCache
->get( $cacheKey );
3569 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3570 * without passing them on to it.
3573 * @param Title $title
3574 * @param Parser|bool $parser
3575 * @return Revision|bool False if missing
3577 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3578 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3584 * Fetch the unparsed text of a template and register a reference to it.
3585 * @param Title $title
3586 * @return array ( string or false, Title )
3588 public function fetchTemplateAndTitle( $title ) {
3589 // Defaults to Parser::statelessFetchTemplate()
3590 $templateCb = $this->mOptions
->getTemplateCallback();
3591 $stuff = call_user_func( $templateCb, $title, $this );
3592 // We use U+007F DELETE to distinguish strip markers from regular text.
3593 $text = $stuff['text'];
3594 if ( is_string( $stuff['text'] ) ) {
3595 $text = strtr( $text, "\x7f", "?" );
3597 $finalTitle = $stuff['finalTitle'] ??
$title;
3598 if ( isset( $stuff['deps'] ) ) {
3599 foreach ( $stuff['deps'] as $dep ) {
3600 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3601 if ( $dep['title']->equals( $this->getTitle() ) ) {
3602 // If we transclude ourselves, the final result
3603 // will change based on the new version of the page
3604 $this->mOutput
->setFlag( 'vary-revision' );
3608 return [ $text, $finalTitle ];
3612 * Fetch the unparsed text of a template and register a reference to it.
3613 * @param Title $title
3614 * @return string|bool
3616 public function fetchTemplate( $title ) {
3617 return $this->fetchTemplateAndTitle( $title )[0];
3621 * Static function to get a template
3622 * Can be overridden via ParserOptions::setTemplateCallback().
3624 * @param Title $title
3625 * @param bool|Parser $parser
3629 public static function statelessFetchTemplate( $title, $parser = false ) {
3630 $text = $skip = false;
3631 $finalTitle = $title;
3634 # Loop to fetch the article, with up to 1 redirect
3635 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3636 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3637 # Give extensions a chance to select the revision instead
3638 $id = false; # Assume current
3639 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3640 [ $parser, $title, &$skip, &$id ] );
3646 'page_id' => $title->getArticleID(),
3653 $rev = Revision
::newFromId( $id );
3654 } elseif ( $parser ) {
3655 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3657 $rev = Revision
::newFromTitle( $title );
3659 $rev_id = $rev ?
$rev->getId() : 0;
3660 # If there is no current revision, there is no page
3661 if ( $id === false && !$rev ) {
3662 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3663 $linkCache->addBadLinkObj( $title );
3668 'page_id' => $title->getArticleID(),
3669 'rev_id' => $rev_id ];
3670 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3671 # We fetched a rev from a different title; register it too...
3673 'title' => $rev->getTitle(),
3674 'page_id' => $rev->getPage(),
3675 'rev_id' => $rev_id ];
3679 $content = $rev->getContent();
3680 $text = $content ?
$content->getWikitextForTransclusion() : null;
3682 Hooks
::run( 'ParserFetchTemplate',
3683 [ $parser, $title, $rev, &$text, &$deps ] );
3685 if ( $text === false ||
$text === null ) {
3689 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3690 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3691 lcfirst( $title->getText() ) )->inContentLanguage();
3692 if ( !$message->exists() ) {
3696 $content = $message->content();
3697 $text = $message->plain();
3705 $finalTitle = $title;
3706 $title = $content->getRedirectTarget();
3710 'finalTitle' => $finalTitle,
3715 * Fetch a file and its title and register a reference to it.
3716 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3717 * @param Title $title
3718 * @param array $options Array of options to RepoGroup::findFile
3720 * @deprecated since 1.32, use fetchFileAndTitle instead
3722 public function fetchFile( $title, $options = [] ) {
3723 wfDeprecated( __METHOD__
, '1.32' );
3724 return $this->fetchFileAndTitle( $title, $options )[0];
3728 * Fetch a file and its title and register a reference to it.
3729 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3730 * @param Title $title
3731 * @param array $options Array of options to RepoGroup::findFile
3732 * @return array ( File or false, Title of file )
3734 public function fetchFileAndTitle( $title, $options = [] ) {
3735 $file = $this->fetchFileNoRegister( $title, $options );
3737 $time = $file ?
$file->getTimestamp() : false;
3738 $sha1 = $file ?
$file->getSha1() : false;
3739 # Register the file as a dependency...
3740 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3741 if ( $file && !$title->equals( $file->getTitle() ) ) {
3742 # Update fetched file title
3743 $title = $file->getTitle();
3744 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3746 return [ $file, $title ];
3750 * Helper function for fetchFileAndTitle.
3752 * Also useful if you need to fetch a file but not use it yet,
3753 * for example to get the file's handler.
3755 * @param Title $title
3756 * @param array $options Array of options to RepoGroup::findFile
3759 protected function fetchFileNoRegister( $title, $options = [] ) {
3760 if ( isset( $options['broken'] ) ) {
3761 $file = false; // broken thumbnail forced by hook
3762 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3763 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3764 } else { // get by (name,timestamp)
3765 $file = wfFindFile( $title, $options );
3771 * Transclude an interwiki link.
3773 * @param Title $title
3774 * @param string $action
3778 public function interwikiTransclude( $title, $action ) {
3779 global $wgEnableScaryTranscluding;
3781 if ( !$wgEnableScaryTranscluding ) {
3782 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3785 $url = $title->getFullURL( [ 'action' => $action ] );
3787 if ( strlen( $url ) > 255 ) {
3788 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3790 return $this->fetchScaryTemplateMaybeFromCache( $url );
3794 * @param string $url
3795 * @return mixed|string
3797 public function fetchScaryTemplateMaybeFromCache( $url ) {
3798 global $wgTranscludeCacheExpiry;
3799 $dbr = wfGetDB( DB_REPLICA
);
3800 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3801 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3802 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3804 return $obj->tc_contents
;
3807 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3808 $status = $req->execute(); // Status object
3809 if ( $status->isOK() ) {
3810 $text = $req->getContent();
3811 } elseif ( $req->getStatus() != 200 ) {
3812 // Though we failed to fetch the content, this status is useless.
3813 return wfMessage( 'scarytranscludefailed-httpstatus' )
3814 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3816 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3819 $dbw = wfGetDB( DB_MASTER
);
3820 $dbw->replace( 'transcache', [ 'tc_url' ], [
3822 'tc_time' => $dbw->timestamp( time() ),
3823 'tc_contents' => $text
3829 * Triple brace replacement -- used for template arguments
3832 * @param array $piece
3833 * @param PPFrame $frame
3837 public function argSubstitution( $piece, $frame ) {
3839 $parts = $piece['parts'];
3840 $nameWithSpaces = $frame->expand( $piece['title'] );
3841 $argName = trim( $nameWithSpaces );
3843 $text = $frame->getArgument( $argName );
3844 if ( $text === false && $parts->getLength() > 0
3845 && ( $this->ot
['html']
3847 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3850 # No match in frame, use the supplied default
3851 $object = $parts->item( 0 )->getChildren();
3853 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3854 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3855 $this->limitationWarn( 'post-expand-template-argument' );
3858 if ( $text === false && $object === false ) {
3860 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3862 if ( $error !== false ) {
3865 if ( $object !== false ) {
3866 $ret = [ 'object' => $object ];
3868 $ret = [ 'text' => $text ];
3875 * Return the text to be used for a given extension tag.
3876 * This is the ghost of strip().
3878 * @param array $params Associative array of parameters:
3879 * name PPNode for the tag name
3880 * attr PPNode for unparsed text where tag attributes are thought to be
3881 * attributes Optional associative array of parsed attributes
3882 * inner Contents of extension element
3883 * noClose Original text did not have a close tag
3884 * @param PPFrame $frame
3886 * @throws MWException
3889 public function extensionSubstitution( $params, $frame ) {
3890 static $errorStr = '<span class="error">';
3891 static $errorLen = 20;
3893 $name = $frame->expand( $params['name'] );
3894 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3895 // Probably expansion depth or node count exceeded. Just punt the
3900 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3901 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3906 // We can't safely check if the expansion for $content resulted in an
3907 // error, because the content could happen to be the error string
3909 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3911 $marker = self
::MARKER_PREFIX
. "-$name-"
3912 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3914 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3915 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3916 if ( $isFunctionTag ) {
3917 $markerType = 'none';
3919 $markerType = 'general';
3921 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3922 $name = strtolower( $name );
3923 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3924 if ( isset( $params['attributes'] ) ) {
3925 $attributes = $attributes +
$params['attributes'];
3928 if ( isset( $this->mTagHooks
[$name] ) ) {
3929 $output = call_user_func_array( $this->mTagHooks
[$name],
3930 [ $content, $attributes, $this, $frame ] );
3931 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3932 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3934 // Avoid PHP 7.1 warning from passing $this by reference
3936 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3938 $output = '<span class="error">Invalid tag extension name: ' .
3939 htmlspecialchars( $name ) . '</span>';
3942 if ( is_array( $output ) ) {
3945 $output = $flags[0];
3946 if ( isset( $flags['markerType'] ) ) {
3947 $markerType = $flags['markerType'];
3951 if ( is_null( $attrText ) ) {
3954 if ( isset( $params['attributes'] ) ) {
3955 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3956 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3957 htmlspecialchars( $attrValue ) . '"';
3960 if ( $content === null ) {
3961 $output = "<$name$attrText/>";
3963 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3964 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3968 $output = "<$name$attrText>$content$close";
3972 if ( $markerType === 'none' ) {
3974 } elseif ( $markerType === 'nowiki' ) {
3975 $this->mStripState
->addNoWiki( $marker, $output );
3976 } elseif ( $markerType === 'general' ) {
3977 $this->mStripState
->addGeneral( $marker, $output );
3979 throw new MWException( __METHOD__
. ': invalid marker type' );
3985 * Increment an include size counter
3987 * @param string $type The type of expansion
3988 * @param int $size The size of the text
3989 * @return bool False if this inclusion would take it over the maximum, true otherwise
3991 public function incrementIncludeSize( $type, $size ) {
3992 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3995 $this->mIncludeSizes
[$type] +
= $size;
4001 * Increment the expensive function count
4003 * @return bool False if the limit has been exceeded
4005 public function incrementExpensiveFunctionCount() {
4006 $this->mExpensiveFunctionCount++
;
4007 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4011 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4012 * Fills $this->mDoubleUnderscores, returns the modified text
4014 * @param string $text
4018 public function doDoubleUnderscore( $text ) {
4019 # The position of __TOC__ needs to be recorded
4020 $mw = $this->magicWordFactory
->get( 'toc' );
4021 if ( $mw->match( $text ) ) {
4022 $this->mShowToc
= true;
4023 $this->mForceTocPosition
= true;
4025 # Set a placeholder. At the end we'll fill it in with the TOC.
4026 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4028 # Only keep the first one.
4029 $text = $mw->replace( '', $text );
4032 # Now match and remove the rest of them
4033 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4034 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4036 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4037 $this->mOutput
->mNoGallery
= true;
4039 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4040 $this->mShowToc
= false;
4042 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4043 && $this->mTitle
->getNamespace() == NS_CATEGORY
4045 $this->addTrackingCategory( 'hidden-category-category' );
4047 # (T10068) Allow control over whether robots index a page.
4048 # __INDEX__ always overrides __NOINDEX__, see T16899
4049 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4050 $this->mOutput
->setIndexPolicy( 'noindex' );
4051 $this->addTrackingCategory( 'noindex-category' );
4053 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4054 $this->mOutput
->setIndexPolicy( 'index' );
4055 $this->addTrackingCategory( 'index-category' );
4058 # Cache all double underscores in the database
4059 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4060 $this->mOutput
->setProperty( $key, '' );
4067 * @see ParserOutput::addTrackingCategory()
4068 * @param string $msg Message key
4069 * @return bool Whether the addition was successful
4071 public function addTrackingCategory( $msg ) {
4072 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4076 * This function accomplishes several tasks:
4077 * 1) Auto-number headings if that option is enabled
4078 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4079 * 3) Add a Table of contents on the top for users who have enabled the option
4080 * 4) Auto-anchor headings
4082 * It loops through all headlines, collects the necessary data, then splits up the
4083 * string and re-inserts the newly formatted headlines.
4085 * @param string $text
4086 * @param string $origText Original, untouched wikitext
4087 * @param bool $isMain
4088 * @return mixed|string
4091 public function formatHeadings( $text, $origText, $isMain = true ) {
4092 global $wgMaxTocLevel;
4094 # Inhibit editsection links if requested in the page
4095 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4096 $maybeShowEditLink = false;
4098 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4101 # Get all headlines for numbering them and adding funky stuff like [edit]
4102 # links - this is for later, but we need the number of headlines right now
4103 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4104 # be trimmed here since whitespace in HTML headings is significant.
4106 $numMatches = preg_match_all(
4107 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4112 # if there are fewer than 4 headlines in the article, do not show TOC
4113 # unless it's been explicitly enabled.
4114 $enoughToc = $this->mShowToc
&&
4115 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4117 # Allow user to stipulate that a page should have a "new section"
4118 # link added via __NEWSECTIONLINK__
4119 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4120 $this->mOutput
->setNewSection( true );
4123 # Allow user to remove the "new section"
4124 # link via __NONEWSECTIONLINK__
4125 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4126 $this->mOutput
->hideNewSection( true );
4129 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4130 # override above conditions and always show TOC above first header
4131 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4132 $this->mShowToc
= true;
4140 # Ugh .. the TOC should have neat indentation levels which can be
4141 # passed to the skin functions. These are determined here
4145 $sublevelCount = [];
4151 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4152 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4153 $oldType = $this->mOutputType
;
4154 $this->setOutputType( self
::OT_WIKI
);
4155 $frame = $this->getPreprocessor()->newFrame();
4156 $root = $this->preprocessToDom( $origText );
4157 $node = $root->getFirstChild();
4162 $headlines = $numMatches !== false ?
$matches[3] : [];
4164 foreach ( $headlines as $headline ) {
4165 $isTemplate = false;
4167 $sectionIndex = false;
4169 $markerMatches = [];
4170 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4171 $serial = $markerMatches[1];
4172 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4173 $isTemplate = ( $titleText != $baseTitleText );
4174 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4178 $prevlevel = $level;
4180 $level = $matches[1][$headlineCount];
4182 if ( $level > $prevlevel ) {
4183 # Increase TOC level
4185 $sublevelCount[$toclevel] = 0;
4186 if ( $toclevel < $wgMaxTocLevel ) {
4187 $prevtoclevel = $toclevel;
4188 $toc .= Linker
::tocIndent();
4191 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4192 # Decrease TOC level, find level to jump to
4194 for ( $i = $toclevel; $i > 0; $i-- ) {
4195 if ( $levelCount[$i] == $level ) {
4196 # Found last matching level
4199 } elseif ( $levelCount[$i] < $level ) {
4200 # Found first matching level below current level
4208 if ( $toclevel < $wgMaxTocLevel ) {
4209 if ( $prevtoclevel < $wgMaxTocLevel ) {
4210 # Unindent only if the previous toc level was shown :p
4211 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4212 $prevtoclevel = $toclevel;
4214 $toc .= Linker
::tocLineEnd();
4218 # No change in level, end TOC line
4219 if ( $toclevel < $wgMaxTocLevel ) {
4220 $toc .= Linker
::tocLineEnd();
4224 $levelCount[$toclevel] = $level;
4226 # count number of headlines for each level
4227 $sublevelCount[$toclevel]++
;
4229 for ( $i = 1; $i <= $toclevel; $i++
) {
4230 if ( !empty( $sublevelCount[$i] ) ) {
4234 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4239 # The safe header is a version of the header text safe to use for links
4241 # Remove link placeholders by the link text.
4242 # <!--LINK number-->
4244 # link text with suffix
4245 # Do this before unstrip since link text can contain strip markers
4246 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4248 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4249 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4251 # Remove any <style> or <script> tags (T198618)
4252 $safeHeadline = preg_replace(
4253 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4258 # Strip out HTML (first regex removes any tag not allowed)
4260 # * <sup> and <sub> (T10393)
4264 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4265 # * <s> and <strike> (T35715)
4266 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4267 # to allow setting directionality in toc items.
4268 $tocline = preg_replace(
4270 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4271 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4277 # Strip '<span></span>', which is the result from the above if
4278 # <span id="foo"></span> is used to produce an additional anchor
4280 $tocline = str_replace( '<span></span>', '', $tocline );
4282 $tocline = trim( $tocline );
4284 # For the anchor, strip out HTML-y stuff period
4285 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4286 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4288 # Save headline for section edit hint before it's escaped
4289 $headlineHint = $safeHeadline;
4291 # Decode HTML entities
4292 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4294 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4296 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4297 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4298 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4299 if ( $fallbackHeadline === $safeHeadline ) {
4300 # No reason to have both (in fact, we can't)
4301 $fallbackHeadline = false;
4304 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4305 # @todo FIXME: We may be changing them depending on the current locale.
4306 $arrayKey = strtolower( $safeHeadline );
4307 if ( $fallbackHeadline === false ) {
4308 $fallbackArrayKey = false;
4310 $fallbackArrayKey = strtolower( $fallbackHeadline );
4313 # Create the anchor for linking from the TOC to the section
4314 $anchor = $safeHeadline;
4315 $fallbackAnchor = $fallbackHeadline;
4316 if ( isset( $refers[$arrayKey] ) ) {
4317 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4318 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4320 $linkAnchor .= "_$i";
4321 $refers["${arrayKey}_$i"] = true;
4323 $refers[$arrayKey] = true;
4325 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4326 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4327 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4328 $fallbackAnchor .= "_$i";
4329 $refers["${fallbackArrayKey}_$i"] = true;
4331 $refers[$fallbackArrayKey] = true;
4334 # Don't number the heading if it is the only one (looks silly)
4335 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4336 # the two are different if the line contains a link
4337 $headline = Html
::element(
4339 [ 'class' => 'mw-headline-number' ],
4341 ) . ' ' . $headline;
4344 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4345 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4346 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4349 # Add the section to the section tree
4350 # Find the DOM node for this header
4351 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4352 while ( $node && !$noOffset ) {
4353 if ( $node->getName() === 'h' ) {
4354 $bits = $node->splitHeading();
4355 if ( $bits['i'] == $sectionIndex ) {
4359 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4360 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4361 $node = $node->getNextSibling();
4364 'toclevel' => $toclevel,
4367 'number' => $numbering,
4368 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4369 'fromtitle' => $titleText,
4370 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4371 'anchor' => $anchor,
4374 # give headline the correct <h#> tag
4375 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4376 // Output edit section links as markers with styles that can be customized by skins
4377 if ( $isTemplate ) {
4378 # Put a T flag in the section identifier, to indicate to extractSections()
4379 # that sections inside <includeonly> should be counted.
4380 $editsectionPage = $titleText;
4381 $editsectionSection = "T-$sectionIndex";
4382 $editsectionContent = null;
4384 $editsectionPage = $this->mTitle
->getPrefixedText();
4385 $editsectionSection = $sectionIndex;
4386 $editsectionContent = $headlineHint;
4388 // We use a bit of pesudo-xml for editsection markers. The
4389 // language converter is run later on. Using a UNIQ style marker
4390 // leads to the converter screwing up the tokens when it
4391 // converts stuff. And trying to insert strip tags fails too. At
4392 // this point all real inputted tags have already been escaped,
4393 // so we don't have to worry about a user trying to input one of
4394 // these markers directly. We use a page and section attribute
4395 // to stop the language converter from converting these
4396 // important bits of data, but put the headline hint inside a
4397 // content block because the language converter is supposed to
4398 // be able to convert that piece of data.
4399 // Gets replaced with html in ParserOutput::getText
4400 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4401 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4402 if ( $editsectionContent !== null ) {
4403 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4410 $head[$headlineCount] = Linker
::makeHeadline( $level,
4411 $matches['attrib'][$headlineCount], $anchor, $headline,
4412 $editlink, $fallbackAnchor );
4417 $this->setOutputType( $oldType );
4419 # Never ever show TOC if no headers
4420 if ( $numVisible < 1 ) {
4425 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4426 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4428 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4429 $this->mOutput
->setTOCHTML( $toc );
4430 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4434 $this->mOutput
->setSections( $tocraw );
4437 # split up and insert constructed headlines
4438 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4441 // build an array of document sections
4443 foreach ( $blocks as $block ) {
4444 // $head is zero-based, sections aren't.
4445 if ( empty( $head[$i - 1] ) ) {
4446 $sections[$i] = $block;
4448 $sections[$i] = $head[$i - 1] . $block;
4452 * Send a hook, one per section.
4453 * The idea here is to be able to make section-level DIVs, but to do so in a
4454 * lower-impact, more correct way than r50769
4457 * $section : the section number
4458 * &$sectionContent : ref to the content of the section
4459 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4461 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4466 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4467 // append the TOC at the beginning
4468 // Top anchor now in skin
4469 $sections[0] = $sections[0] . $toc . "\n";
4472 $full .= implode( '', $sections );
4474 if ( $this->mForceTocPosition
) {
4475 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4482 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4483 * conversion, substituting signatures, {{subst:}} templates, etc.
4485 * @param string $text The text to transform
4486 * @param Title $title The Title object for the current article
4487 * @param User $user The User object describing the current user
4488 * @param ParserOptions $options Parsing options
4489 * @param bool $clearState Whether to clear the parser state first
4490 * @return string The altered wiki markup
4492 public function preSaveTransform( $text, Title
$title, User
$user,
4493 ParserOptions
$options, $clearState = true
4495 if ( $clearState ) {
4496 $magicScopeVariable = $this->lock();
4498 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4499 $this->setUser( $user );
4501 // Strip U+0000 NULL (T159174)
4502 $text = str_replace( "\000", '', $text );
4504 // We still normalize line endings for backwards-compatibility
4505 // with other code that just calls PST, but this should already
4506 // be handled in TextContent subclasses
4507 $text = TextContent
::normalizeLineEndings( $text );
4509 if ( $options->getPreSaveTransform() ) {
4510 $text = $this->pstPass2( $text, $user );
4512 $text = $this->mStripState
->unstripBoth( $text );
4514 $this->setUser( null ); # Reset
4520 * Pre-save transform helper function
4522 * @param string $text
4527 private function pstPass2( $text, $user ) {
4528 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4529 # $this->contLang here in order to give everyone the same signature and use the default one
4530 # rather than the one selected in each user's preferences. (see also T14815)
4531 $ts = $this->mOptions
->getTimestamp();
4532 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4533 $ts = $timestamp->format( 'YmdHis' );
4534 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4536 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4538 # Variable replacement
4539 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4540 $text = $this->replaceVariables( $text );
4542 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4543 # which may corrupt this parser instance via its wfMessage()->text() call-
4546 if ( strpos( $text, '~~~' ) !== false ) {
4547 $sigText = $this->getUserSig( $user );
4548 $text = strtr( $text, [
4550 '~~~~' => "$sigText $d",
4553 # The main two signature forms used above are time-sensitive
4554 $this->mOutput
->setFlag( 'user-signature' );
4557 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4558 $tc = '[' . Title
::legalChars() . ']';
4559 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4561 // [[ns:page (context)|]]
4562 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4563 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4564 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4565 // [[ns:page (context), context|]] (using either single or double-width comma)
4566 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4567 // [[|page]] (reverse pipe trick: add context from page title)
4568 $p2 = "/\[\[\\|($tc+)]]/";
4570 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4571 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4572 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4573 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4575 $t = $this->mTitle
->getText();
4577 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4578 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4579 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4580 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4582 # if there's no context, don't bother duplicating the title
4583 $text = preg_replace( $p2, '[[\\1]]', $text );
4590 * Fetch the user's signature text, if any, and normalize to
4591 * validated, ready-to-insert wikitext.
4592 * If you have pre-fetched the nickname or the fancySig option, you can
4593 * specify them here to save a database query.
4594 * Do not reuse this parser instance after calling getUserSig(),
4595 * as it may have changed if it's the $wgParser.
4597 * @param User &$user
4598 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4599 * @param bool|null $fancySig whether the nicknname is the complete signature
4600 * or null to use default value
4603 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4604 global $wgMaxSigChars;
4606 $username = $user->getName();
4608 # If not given, retrieve from the user object.
4609 if ( $nickname === false ) {
4610 $nickname = $user->getOption( 'nickname' );
4613 if ( is_null( $fancySig ) ) {
4614 $fancySig = $user->getBoolOption( 'fancysig' );
4617 $nickname = $nickname == null ?
$username : $nickname;
4619 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4620 $nickname = $username;
4621 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4622 } elseif ( $fancySig !== false ) {
4623 # Sig. might contain markup; validate this
4624 if ( $this->validateSig( $nickname ) !== false ) {
4625 # Validated; clean up (if needed) and return it
4626 return $this->cleanSig( $nickname, true );
4628 # Failed to validate; fall back to the default
4629 $nickname = $username;
4630 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4634 # Make sure nickname doesnt get a sig in a sig
4635 $nickname = self
::cleanSigInSig( $nickname );
4637 # If we're still here, make it a link to the user page
4638 $userText = wfEscapeWikiText( $username );
4639 $nickText = wfEscapeWikiText( $nickname );
4640 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4642 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4643 ->title( $this->getTitle() )->text();
4647 * Check that the user's signature contains no bad XML
4649 * @param string $text
4650 * @return string|bool An expanded string, or false if invalid.
4652 public function validateSig( $text ) {
4653 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4657 * Clean up signature text
4659 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4660 * 2) Substitute all transclusions
4662 * @param string $text
4663 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4664 * @return string Signature text
4666 public function cleanSig( $text, $parsing = false ) {
4669 $magicScopeVariable = $this->lock();
4670 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4673 # Option to disable this feature
4674 if ( !$this->mOptions
->getCleanSignatures() ) {
4678 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4679 # => Move this logic to braceSubstitution()
4680 $substWord = $this->magicWordFactory
->get( 'subst' );
4681 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4682 $substText = '{{' . $substWord->getSynonym( 0 );
4684 $text = preg_replace( $substRegex, $substText, $text );
4685 $text = self
::cleanSigInSig( $text );
4686 $dom = $this->preprocessToDom( $text );
4687 $frame = $this->getPreprocessor()->newFrame();
4688 $text = $frame->expand( $dom );
4691 $text = $this->mStripState
->unstripBoth( $text );
4698 * Strip 3, 4 or 5 tildes out of signatures.
4700 * @param string $text
4701 * @return string Signature text with /~{3,5}/ removed
4703 public static function cleanSigInSig( $text ) {
4704 $text = preg_replace( '/~{3,5}/', '', $text );
4709 * Set up some variables which are usually set up in parse()
4710 * so that an external function can call some class members with confidence
4712 * @param Title|null $title
4713 * @param ParserOptions $options
4714 * @param int $outputType
4715 * @param bool $clearState
4717 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4718 $outputType, $clearState = true
4720 $this->startParse( $title, $options, $outputType, $clearState );
4724 * @param Title|null $title
4725 * @param ParserOptions $options
4726 * @param int $outputType
4727 * @param bool $clearState
4729 private function startParse( Title
$title = null, ParserOptions
$options,
4730 $outputType, $clearState = true
4732 $this->setTitle( $title );
4733 $this->mOptions
= $options;
4734 $this->setOutputType( $outputType );
4735 if ( $clearState ) {
4736 $this->clearState();
4741 * Wrapper for preprocess()
4743 * @param string $text The text to preprocess
4744 * @param ParserOptions $options
4745 * @param Title|null $title Title object or null to use $wgTitle
4748 public function transformMsg( $text, $options, $title = null ) {
4749 static $executing = false;
4751 # Guard against infinite recursion
4762 $text = $this->preprocess( $text, $title, $options );
4769 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4770 * The callback should have the following form:
4771 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4773 * Transform and return $text. Use $parser for any required context, e.g. use
4774 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4776 * Hooks may return extended information by returning an array, of which the
4777 * first numbered element (index 0) must be the return string, and all other
4778 * entries are extracted into local variables within an internal function
4779 * in the Parser class.
4781 * This interface (introduced r61913) appears to be undocumented, but
4782 * 'markerType' is used by some core tag hooks to override which strip
4783 * array their results are placed in. **Use great caution if attempting
4784 * this interface, as it is not documented and injudicious use could smash
4785 * private variables.**
4787 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4788 * @param callable $callback The callback function (and object) to use for the tag
4789 * @throws MWException
4790 * @return callable|null The old value of the mTagHooks array associated with the hook
4792 public function setHook( $tag, callable
$callback ) {
4793 $tag = strtolower( $tag );
4794 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4795 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4797 $oldVal = $this->mTagHooks
[$tag] ??
null;
4798 $this->mTagHooks
[$tag] = $callback;
4799 if ( !in_array( $tag, $this->mStripList
) ) {
4800 $this->mStripList
[] = $tag;
4807 * As setHook(), but letting the contents be parsed.
4809 * Transparent tag hooks are like regular XML-style tag hooks, except they
4810 * operate late in the transformation sequence, on HTML instead of wikitext.
4812 * This is probably obsoleted by things dealing with parser frames?
4813 * The only extension currently using it is geoserver.
4816 * @todo better document or deprecate this
4818 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4819 * @param callable $callback The callback function (and object) to use for the tag
4820 * @throws MWException
4821 * @return callable|null The old value of the mTagHooks array associated with the hook
4823 public function setTransparentTagHook( $tag, callable
$callback ) {
4824 $tag = strtolower( $tag );
4825 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4826 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4828 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4829 $this->mTransparentTagHooks
[$tag] = $callback;
4835 * Remove all tag hooks
4837 public function clearTagHooks() {
4838 $this->mTagHooks
= [];
4839 $this->mFunctionTagHooks
= [];
4840 $this->mStripList
= $this->mDefaultStripList
;
4844 * Create a function, e.g. {{sum:1|2|3}}
4845 * The callback function should have the form:
4846 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4848 * Or with Parser::SFH_OBJECT_ARGS:
4849 * function myParserFunction( $parser, $frame, $args ) { ... }
4851 * The callback may either return the text result of the function, or an array with the text
4852 * in element 0, and a number of flags in the other elements. The names of the flags are
4853 * specified in the keys. Valid flags are:
4854 * found The text returned is valid, stop processing the template. This
4856 * nowiki Wiki markup in the return value should be escaped
4857 * isHTML The returned text is HTML, armour it against wikitext transformation
4859 * @param string $id The magic word ID
4860 * @param callable $callback The callback function (and object) to use
4861 * @param int $flags A combination of the following flags:
4862 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4864 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4865 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4866 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4867 * the arguments, and to control the way they are expanded.
4869 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4870 * arguments, for instance:
4871 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4873 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4874 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4875 * working if/when this is changed.
4877 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4880 * Please read the documentation in includes/parser/Preprocessor.php for more information
4881 * about the methods available in PPFrame and PPNode.
4883 * @throws MWException
4884 * @return string|callable The old callback function for this name, if any
4886 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4887 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4888 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4890 # Add to function cache
4891 $mw = $this->magicWordFactory
->get( $id );
4893 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4896 $synonyms = $mw->getSynonyms();
4897 $sensitive = intval( $mw->isCaseSensitive() );
4899 foreach ( $synonyms as $syn ) {
4901 if ( !$sensitive ) {
4902 $syn = $this->contLang
->lc( $syn );
4905 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4908 # Remove trailing colon
4909 if ( substr( $syn, -1, 1 ) === ':' ) {
4910 $syn = substr( $syn, 0, -1 );
4912 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4918 * Get all registered function hook identifiers
4922 public function getFunctionHooks() {
4923 return array_keys( $this->mFunctionHooks
);
4927 * Create a tag function, e.g. "<test>some stuff</test>".
4928 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4929 * Unlike parser functions, their content is not preprocessed.
4930 * @param string $tag
4931 * @param callable $callback
4933 * @throws MWException
4936 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4937 $tag = strtolower( $tag );
4938 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4939 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4941 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4942 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4944 if ( !in_array( $tag, $this->mStripList
) ) {
4945 $this->mStripList
[] = $tag;
4952 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4953 * Placeholders created in Linker::link()
4955 * @param string &$text
4956 * @param int $options
4958 public function replaceLinkHolders( &$text, $options = 0 ) {
4959 $this->mLinkHolders
->replace( $text );
4963 * Replace "<!--LINK-->" link placeholders with plain text of links
4964 * (not HTML-formatted).
4966 * @param string $text
4969 public function replaceLinkHoldersText( $text ) {
4970 return $this->mLinkHolders
->replaceText( $text );
4974 * Renders an image gallery from a text with one line per image.
4975 * text labels may be given by using |-style alternative text. E.g.
4976 * Image:one.jpg|The number "1"
4977 * Image:tree.jpg|A tree
4978 * given as text will return the HTML of a gallery with two images,
4979 * labeled 'The number "1"' and
4982 * @param string $text
4983 * @param array $params
4984 * @return string HTML
4986 public function renderImageGallery( $text, $params ) {
4988 if ( isset( $params['mode'] ) ) {
4989 $mode = $params['mode'];
4993 $ig = ImageGalleryBase
::factory( $mode );
4994 } catch ( Exception
$e ) {
4995 // If invalid type set, fallback to default.
4996 $ig = ImageGalleryBase
::factory( false );
4999 $ig->setContextTitle( $this->mTitle
);
5000 $ig->setShowBytes( false );
5001 $ig->setShowDimensions( false );
5002 $ig->setShowFilename( false );
5003 $ig->setParser( $this );
5004 $ig->setHideBadImages();
5005 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5007 if ( isset( $params['showfilename'] ) ) {
5008 $ig->setShowFilename( true );
5010 $ig->setShowFilename( false );
5012 if ( isset( $params['caption'] ) ) {
5013 $caption = $params['caption'];
5014 $caption = htmlspecialchars( $caption );
5015 $caption = $this->replaceInternalLinks( $caption );
5016 $ig->setCaptionHtml( $caption );
5018 if ( isset( $params['perrow'] ) ) {
5019 $ig->setPerRow( $params['perrow'] );
5021 if ( isset( $params['widths'] ) ) {
5022 $ig->setWidths( $params['widths'] );
5024 if ( isset( $params['heights'] ) ) {
5025 $ig->setHeights( $params['heights'] );
5027 $ig->setAdditionalOptions( $params );
5029 // Avoid PHP 7.1 warning from passing $this by reference
5031 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5033 $lines = StringUtils
::explode( "\n", $text );
5034 foreach ( $lines as $line ) {
5035 # match lines like these:
5036 # Image:someimage.jpg|This is some image
5038 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5040 if ( count( $matches ) == 0 ) {
5044 if ( strpos( $matches[0], '%' ) !== false ) {
5045 $matches[1] = rawurldecode( $matches[1] );
5047 $title = Title
::newFromText( $matches[1], NS_FILE
);
5048 if ( is_null( $title ) ) {
5049 # Bogus title. Ignore these so we don't bomb out later.
5053 # We need to get what handler the file uses, to figure out parameters.
5054 # Note, a hook can overide the file name, and chose an entirely different
5055 # file (which potentially could be of a different type and have different handler).
5058 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5059 [ $this, $title, &$options, &$descQuery ] );
5060 # Don't register it now, as TraditionalImageGallery does that later.
5061 $file = $this->fetchFileNoRegister( $title, $options );
5062 $handler = $file ?
$file->getHandler() : false;
5065 'img_alt' => 'gallery-internal-alt',
5066 'img_link' => 'gallery-internal-link',
5069 $paramMap = $paramMap +
$handler->getParamMap();
5070 // We don't want people to specify per-image widths.
5071 // Additionally the width parameter would need special casing anyhow.
5072 unset( $paramMap['img_width'] );
5075 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5080 $handlerOptions = [];
5081 if ( isset( $matches[3] ) ) {
5082 // look for an |alt= definition while trying not to break existing
5083 // captions with multiple pipes (|) in it, until a more sensible grammar
5084 // is defined for images in galleries
5086 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5087 // splitting on '|' is a bit odd, and different from makeImage.
5088 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5089 // Protect LanguageConverter markup
5090 $parameterMatches = StringUtils
::delimiterExplode(
5091 '-{', '}-', '|', $matches[3], true /* nested */
5094 foreach ( $parameterMatches as $parameterMatch ) {
5095 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5097 $paramName = $paramMap[$magicName];
5099 switch ( $paramName ) {
5100 case 'gallery-internal-alt':
5101 $alt = $this->stripAltText( $match, false );
5103 case 'gallery-internal-link':
5104 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5105 $chars = self
::EXT_LINK_URL_CLASS
;
5106 $addr = self
::EXT_LINK_ADDR
;
5107 $prots = $this->mUrlProtocols
;
5108 // check to see if link matches an absolute url, if not then it must be a wiki link.
5109 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5110 // Result of LanguageConverter::markNoConversion
5111 // invoked on an external link.
5112 $linkValue = substr( $linkValue, 4, -2 );
5114 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5116 $this->mOutput
->addExternalLink( $link );
5118 $localLinkTitle = Title
::newFromText( $linkValue );
5119 if ( $localLinkTitle !== null ) {
5120 $this->mOutput
->addLink( $localLinkTitle );
5121 $link = $localLinkTitle->getLinkURL();
5126 // Must be a handler specific parameter.
5127 if ( $handler->validateParam( $paramName, $match ) ) {
5128 $handlerOptions[$paramName] = $match;
5130 // Guess not, consider it as caption.
5131 wfDebug( "$parameterMatch failed parameter validation\n" );
5132 $label = $parameterMatch;
5138 $label = $parameterMatch;
5143 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5145 $html = $ig->toHTML();
5146 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5151 * @param MediaHandler $handler
5154 public function getImageParams( $handler ) {
5156 $handlerClass = get_class( $handler );
5160 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5161 # Initialise static lists
5162 static $internalParamNames = [
5163 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5164 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5165 'bottom', 'text-bottom' ],
5166 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5167 'upright', 'border', 'link', 'alt', 'class' ],
5169 static $internalParamMap;
5170 if ( !$internalParamMap ) {
5171 $internalParamMap = [];
5172 foreach ( $internalParamNames as $type => $names ) {
5173 foreach ( $names as $name ) {
5174 // For grep: img_left, img_right, img_center, img_none,
5175 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5176 // img_bottom, img_text_bottom,
5177 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5178 // img_border, img_link, img_alt, img_class
5179 $magicName = str_replace( '-', '_', "img_$name" );
5180 $internalParamMap[$magicName] = [ $type, $name ];
5185 # Add handler params
5186 $paramMap = $internalParamMap;
5188 $handlerParamMap = $handler->getParamMap();
5189 foreach ( $handlerParamMap as $magic => $paramName ) {
5190 $paramMap[$magic] = [ 'handler', $paramName ];
5193 $this->mImageParams
[$handlerClass] = $paramMap;
5194 $this->mImageParamsMagicArray
[$handlerClass] =
5195 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5197 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5201 * Parse image options text and use it to make an image
5203 * @param Title $title
5204 * @param string $options
5205 * @param LinkHolderArray|bool $holders
5206 * @return string HTML
5208 public function makeImage( $title, $options, $holders = false ) {
5209 # Check if the options text is of the form "options|alt text"
5211 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5212 # * left no resizing, just left align. label is used for alt= only
5213 # * right same, but right aligned
5214 # * none same, but not aligned
5215 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5216 # * center center the image
5217 # * frame Keep original image size, no magnify-button.
5218 # * framed Same as "frame"
5219 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5220 # * upright reduce width for upright images, rounded to full __0 px
5221 # * border draw a 1px border around the image
5222 # * alt Text for HTML alt attribute (defaults to empty)
5223 # * class Set a class for img node
5224 # * link Set the target of the image link. Can be external, interwiki, or local
5225 # vertical-align values (no % or length right now):
5235 # Protect LanguageConverter markup when splitting into parts
5236 $parts = StringUtils
::delimiterExplode(
5237 '-{', '}-', '|', $options, true /* allow nesting */
5240 # Give extensions a chance to select the file revision for us
5243 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5244 [ $this, $title, &$options, &$descQuery ] );
5245 # Fetch and register the file (file title may be different via hooks)
5246 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5249 $handler = $file ?
$file->getHandler() : false;
5251 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5254 $this->addTrackingCategory( 'broken-file-category' );
5257 # Process the input parameters
5259 $params = [ 'frame' => [], 'handler' => [],
5260 'horizAlign' => [], 'vertAlign' => [] ];
5261 $seenformat = false;
5262 foreach ( $parts as $part ) {
5263 $part = trim( $part );
5264 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5266 if ( isset( $paramMap[$magicName] ) ) {
5267 list( $type, $paramName ) = $paramMap[$magicName];
5269 # Special case; width and height come in one variable together
5270 if ( $type === 'handler' && $paramName === 'width' ) {
5271 $parsedWidthParam = self
::parseWidthParam( $value );
5272 if ( isset( $parsedWidthParam['width'] ) ) {
5273 $width = $parsedWidthParam['width'];
5274 if ( $handler->validateParam( 'width', $width ) ) {
5275 $params[$type]['width'] = $width;
5279 if ( isset( $parsedWidthParam['height'] ) ) {
5280 $height = $parsedWidthParam['height'];
5281 if ( $handler->validateParam( 'height', $height ) ) {
5282 $params[$type]['height'] = $height;
5286 # else no validation -- T15436
5288 if ( $type === 'handler' ) {
5289 # Validate handler parameter
5290 $validated = $handler->validateParam( $paramName, $value );
5292 # Validate internal parameters
5293 switch ( $paramName ) {
5297 # @todo FIXME: Possibly check validity here for
5298 # manualthumb? downstream behavior seems odd with
5299 # missing manual thumbs.
5301 $value = $this->stripAltText( $value, $holders );
5304 $chars = self
::EXT_LINK_URL_CLASS
;
5305 $addr = self
::EXT_LINK_ADDR
;
5306 $prots = $this->mUrlProtocols
;
5307 if ( $value === '' ) {
5308 $paramName = 'no-link';
5311 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5312 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5313 $paramName = 'link-url';
5314 $this->mOutput
->addExternalLink( $value );
5315 if ( $this->mOptions
->getExternalLinkTarget() ) {
5316 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5321 $linkTitle = Title
::newFromText( $value );
5323 $paramName = 'link-title';
5324 $value = $linkTitle;
5325 $this->mOutput
->addLink( $linkTitle );
5333 // use first appearing option, discard others.
5334 $validated = !$seenformat;
5338 # Most other things appear to be empty or numeric...
5339 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5344 $params[$type][$paramName] = $value;
5348 if ( !$validated ) {
5353 # Process alignment parameters
5354 if ( $params['horizAlign'] ) {
5355 $params['frame']['align'] = key( $params['horizAlign'] );
5357 if ( $params['vertAlign'] ) {
5358 $params['frame']['valign'] = key( $params['vertAlign'] );
5361 $params['frame']['caption'] = $caption;
5363 # Will the image be presented in a frame, with the caption below?
5364 $imageIsFramed = isset( $params['frame']['frame'] )
5365 ||
isset( $params['frame']['framed'] )
5366 ||
isset( $params['frame']['thumbnail'] )
5367 ||
isset( $params['frame']['manualthumb'] );
5369 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5370 # came to also set the caption, ordinary text after the image -- which
5371 # makes no sense, because that just repeats the text multiple times in
5372 # screen readers. It *also* came to set the title attribute.
5373 # Now that we have an alt attribute, we should not set the alt text to
5374 # equal the caption: that's worse than useless, it just repeats the
5375 # text. This is the framed/thumbnail case. If there's no caption, we
5376 # use the unnamed parameter for alt text as well, just for the time be-
5377 # ing, if the unnamed param is set and the alt param is not.
5378 # For the future, we need to figure out if we want to tweak this more,
5379 # e.g., introducing a title= parameter for the title; ignoring the un-
5380 # named parameter entirely for images without a caption; adding an ex-
5381 # plicit caption= parameter and preserving the old magic unnamed para-
5383 if ( $imageIsFramed ) { # Framed image
5384 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5385 # No caption or alt text, add the filename as the alt text so
5386 # that screen readers at least get some description of the image
5387 $params['frame']['alt'] = $title->getText();
5389 # Do not set $params['frame']['title'] because tooltips don't make sense
5391 } else { # Inline image
5392 if ( !isset( $params['frame']['alt'] ) ) {
5393 # No alt text, use the "caption" for the alt text
5394 if ( $caption !== '' ) {
5395 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5397 # No caption, fall back to using the filename for the
5399 $params['frame']['alt'] = $title->getText();
5402 # Use the "caption" for the tooltip text
5403 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5406 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5408 # Linker does the rest
5409 $time = $options['time'] ??
false;
5410 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5411 $time, $descQuery, $this->mOptions
->getThumbSize() );
5413 # Give the handler a chance to modify the parser object
5415 $handler->parserTransformHook( $this, $file );
5422 * @param string $caption
5423 * @param LinkHolderArray|bool $holders
5424 * @return mixed|string
5426 protected function stripAltText( $caption, $holders ) {
5427 # Strip bad stuff out of the title (tooltip). We can't just use
5428 # replaceLinkHoldersText() here, because if this function is called
5429 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5431 $tooltip = $holders->replaceText( $caption );
5433 $tooltip = $this->replaceLinkHoldersText( $caption );
5436 # make sure there are no placeholders in thumbnail attributes
5437 # that are later expanded to html- so expand them now and
5439 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5440 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5446 * Set a flag in the output object indicating that the content is dynamic and
5447 * shouldn't be cached.
5448 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5450 public function disableCache() {
5451 wfDebug( "Parser output marked as uncacheable.\n" );
5452 if ( !$this->mOutput
) {
5453 throw new MWException( __METHOD__
.
5454 " can only be called when actually parsing something" );
5456 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5460 * Callback from the Sanitizer for expanding items found in HTML attribute
5461 * values, so they can be safely tested and escaped.
5463 * @param string &$text
5464 * @param bool|PPFrame $frame
5467 public function attributeStripCallback( &$text, $frame = false ) {
5468 $text = $this->replaceVariables( $text, $frame );
5469 $text = $this->mStripState
->unstripBoth( $text );
5478 public function getTags() {
5480 array_keys( $this->mTransparentTagHooks
),
5481 array_keys( $this->mTagHooks
),
5482 array_keys( $this->mFunctionTagHooks
)
5487 * Replace transparent tags in $text with the values given by the callbacks.
5489 * Transparent tag hooks are like regular XML-style tag hooks, except they
5490 * operate late in the transformation sequence, on HTML instead of wikitext.
5492 * @param string $text
5496 public function replaceTransparentTags( $text ) {
5498 $elements = array_keys( $this->mTransparentTagHooks
);
5499 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5502 foreach ( $matches as $marker => $data ) {
5503 list( $element, $content, $params, $tag ) = $data;
5504 $tagName = strtolower( $element );
5505 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5506 $output = call_user_func_array(
5507 $this->mTransparentTagHooks
[$tagName],
5508 [ $content, $params, $this ]
5513 $replacements[$marker] = $output;
5515 return strtr( $text, $replacements );
5519 * Break wikitext input into sections, and either pull or replace
5520 * some particular section's text.
5522 * External callers should use the getSection and replaceSection methods.
5524 * @param string $text Page wikitext
5525 * @param string|int $sectionId A section identifier string of the form:
5526 * "<flag1> - <flag2> - ... - <section number>"
5528 * Currently the only recognised flag is "T", which means the target section number
5529 * was derived during a template inclusion parse, in other words this is a template
5530 * section edit link. If no flags are given, it was an ordinary section edit link.
5531 * This flag is required to avoid a section numbering mismatch when a section is
5532 * enclosed by "<includeonly>" (T8563).
5534 * The section number 0 pulls the text before the first heading; other numbers will
5535 * pull the given section along with its lower-level subsections. If the section is
5536 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5538 * Section 0 is always considered to exist, even if it only contains the empty
5539 * string. If $text is the empty string and section 0 is replaced, $newText is
5542 * @param string $mode One of "get" or "replace"
5543 * @param string $newText Replacement text for section data.
5544 * @return string For "get", the extracted section text.
5545 * for "replace", the whole page with the section replaced.
5547 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5548 global $wgTitle; # not generally used but removes an ugly failure mode
5550 $magicScopeVariable = $this->lock();
5551 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5553 $frame = $this->getPreprocessor()->newFrame();
5555 # Process section extraction flags
5557 $sectionParts = explode( '-', $sectionId );
5558 $sectionIndex = array_pop( $sectionParts );
5559 foreach ( $sectionParts as $part ) {
5560 if ( $part === 'T' ) {
5561 $flags |
= self
::PTD_FOR_INCLUSION
;
5565 # Check for empty input
5566 if ( strval( $text ) === '' ) {
5567 # Only sections 0 and T-0 exist in an empty document
5568 if ( $sectionIndex == 0 ) {
5569 if ( $mode === 'get' ) {
5575 if ( $mode === 'get' ) {
5583 # Preprocess the text
5584 $root = $this->preprocessToDom( $text, $flags );
5586 # <h> nodes indicate section breaks
5587 # They can only occur at the top level, so we can find them by iterating the root's children
5588 $node = $root->getFirstChild();
5590 # Find the target section
5591 if ( $sectionIndex == 0 ) {
5592 # Section zero doesn't nest, level=big
5593 $targetLevel = 1000;
5596 if ( $node->getName() === 'h' ) {
5597 $bits = $node->splitHeading();
5598 if ( $bits['i'] == $sectionIndex ) {
5599 $targetLevel = $bits['level'];
5603 if ( $mode === 'replace' ) {
5604 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5606 $node = $node->getNextSibling();
5612 if ( $mode === 'get' ) {
5619 # Find the end of the section, including nested sections
5621 if ( $node->getName() === 'h' ) {
5622 $bits = $node->splitHeading();
5623 $curLevel = $bits['level'];
5624 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5628 if ( $mode === 'get' ) {
5629 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5631 $node = $node->getNextSibling();
5634 # Write out the remainder (in replace mode only)
5635 if ( $mode === 'replace' ) {
5636 # Output the replacement text
5637 # Add two newlines on -- trailing whitespace in $newText is conventionally
5638 # stripped by the editor, so we need both newlines to restore the paragraph gap
5639 # Only add trailing whitespace if there is newText
5640 if ( $newText != "" ) {
5641 $outText .= $newText . "\n\n";
5645 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5646 $node = $node->getNextSibling();
5650 if ( is_string( $outText ) ) {
5651 # Re-insert stripped tags
5652 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5659 * This function returns the text of a section, specified by a number ($section).
5660 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5661 * the first section before any such heading (section 0).
5663 * If a section contains subsections, these are also returned.
5665 * @param string $text Text to look in
5666 * @param string|int $sectionId Section identifier as a number or string
5667 * (e.g. 0, 1 or 'T-1').
5668 * @param string $defaultText Default to return if section is not found
5670 * @return string Text of the requested section
5672 public function getSection( $text, $sectionId, $defaultText = '' ) {
5673 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5677 * This function returns $oldtext after the content of the section
5678 * specified by $section has been replaced with $text. If the target
5679 * section does not exist, $oldtext is returned unchanged.
5681 * @param string $oldText Former text of the article
5682 * @param string|int $sectionId Section identifier as a number or string
5683 * (e.g. 0, 1 or 'T-1').
5684 * @param string $newText Replacing text
5686 * @return string Modified text
5688 public function replaceSection( $oldText, $sectionId, $newText ) {
5689 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5693 * Get the ID of the revision we are parsing
5697 public function getRevisionId() {
5698 return $this->mRevisionId
;
5702 * Get the revision object for $this->mRevisionId
5704 * @return Revision|null Either a Revision object or null
5705 * @since 1.23 (public since 1.23)
5707 public function getRevisionObject() {
5708 if ( !is_null( $this->mRevisionObject
) ) {
5709 return $this->mRevisionObject
;
5711 if ( is_null( $this->mRevisionId
) ) {
5715 $rev = call_user_func(
5716 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5719 # If the parse is for a new revision, then the callback should have
5720 # already been set to force the object and should match mRevisionId.
5721 # If not, try to fetch by mRevisionId for sanity.
5722 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5723 $rev = Revision
::newFromId( $this->mRevisionId
);
5726 $this->mRevisionObject
= $rev;
5728 return $this->mRevisionObject
;
5732 * Get the timestamp associated with the current revision, adjusted for
5733 * the default server-local timestamp
5736 public function getRevisionTimestamp() {
5737 if ( is_null( $this->mRevisionTimestamp
) ) {
5738 $revObject = $this->getRevisionObject();
5739 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5741 # The cryptic '' timezone parameter tells to use the site-default
5742 # timezone offset instead of the user settings.
5743 # Since this value will be saved into the parser cache, served
5744 # to other users, and potentially even used inside links and such,
5745 # it needs to be consistent for all visitors.
5746 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
5749 return $this->mRevisionTimestamp
;
5753 * Get the name of the user that edited the last revision
5755 * @return string User name
5757 public function getRevisionUser() {
5758 if ( is_null( $this->mRevisionUser
) ) {
5759 $revObject = $this->getRevisionObject();
5761 # if this template is subst: the revision id will be blank,
5762 # so just use the current user's name
5764 $this->mRevisionUser
= $revObject->getUserText();
5765 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5766 $this->mRevisionUser
= $this->getUser()->getName();
5769 return $this->mRevisionUser
;
5773 * Get the size of the revision
5775 * @return int|null Revision size
5777 public function getRevisionSize() {
5778 if ( is_null( $this->mRevisionSize
) ) {
5779 $revObject = $this->getRevisionObject();
5781 # if this variable is subst: the revision id will be blank,
5782 # so just use the parser input size, because the own substituation
5783 # will change the size.
5785 $this->mRevisionSize
= $revObject->getSize();
5787 $this->mRevisionSize
= $this->mInputSize
;
5790 return $this->mRevisionSize
;
5794 * Mutator for $mDefaultSort
5796 * @param string $sort New value
5798 public function setDefaultSort( $sort ) {
5799 $this->mDefaultSort
= $sort;
5800 $this->mOutput
->setProperty( 'defaultsort', $sort );
5804 * Accessor for $mDefaultSort
5805 * Will use the empty string if none is set.
5807 * This value is treated as a prefix, so the
5808 * empty string is equivalent to sorting by
5813 public function getDefaultSort() {
5814 if ( $this->mDefaultSort
!== false ) {
5815 return $this->mDefaultSort
;
5822 * Accessor for $mDefaultSort
5823 * Unlike getDefaultSort(), will return false if none is set
5825 * @return string|bool
5827 public function getCustomDefaultSort() {
5828 return $this->mDefaultSort
;
5831 private static function getSectionNameFromStrippedText( $text ) {
5832 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5833 $text = Sanitizer
::decodeCharReferences( $text );
5834 $text = self
::normalizeSectionName( $text );
5838 private static function makeAnchor( $sectionName ) {
5839 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5842 private static function makeLegacyAnchor( $sectionName ) {
5843 global $wgFragmentMode;
5844 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5845 // ForAttribute() and ForLink() are the same for legacy encoding
5846 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5848 $id = Sanitizer
::escapeIdForLink( $sectionName );
5855 * Try to guess the section anchor name based on a wikitext fragment
5856 * presumably extracted from a heading, for example "Header" from
5859 * @param string $text
5860 * @return string Anchor (starting with '#')
5862 public function guessSectionNameFromWikiText( $text ) {
5863 # Strip out wikitext links(they break the anchor)
5864 $text = $this->stripSectionName( $text );
5865 $sectionName = self
::getSectionNameFromStrippedText( $text );
5866 return self
::makeAnchor( $sectionName );
5870 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5871 * instead, if possible. For use in redirects, since various versions
5872 * of Microsoft browsers interpret Location: headers as something other
5873 * than UTF-8, resulting in breakage.
5875 * @param string $text The section name
5876 * @return string Anchor (starting with '#')
5878 public function guessLegacySectionNameFromWikiText( $text ) {
5879 # Strip out wikitext links(they break the anchor)
5880 $text = $this->stripSectionName( $text );
5881 $sectionName = self
::getSectionNameFromStrippedText( $text );
5882 return self
::makeLegacyAnchor( $sectionName );
5886 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5887 * @param string $text Section name (plain text)
5888 * @return string Anchor (starting with '#')
5890 public static function guessSectionNameFromStrippedText( $text ) {
5891 $sectionName = self
::getSectionNameFromStrippedText( $text );
5892 return self
::makeAnchor( $sectionName );
5896 * Apply the same normalization as code making links to this section would
5898 * @param string $text
5901 private static function normalizeSectionName( $text ) {
5902 # T90902: ensure the same normalization is applied for IDs as to links
5903 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5906 $parts = $titleParser->splitTitleString( "#$text" );
5907 } catch ( MalformedTitleException
$ex ) {
5910 return $parts['fragment'];
5914 * Strips a text string of wikitext for use in a section anchor
5916 * Accepts a text string and then removes all wikitext from the
5917 * string and leaves only the resultant text (i.e. the result of
5918 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5919 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5920 * to create valid section anchors by mimicing the output of the
5921 * parser when headings are parsed.
5923 * @param string $text Text string to be stripped of wikitext
5924 * for use in a Section anchor
5925 * @return string Filtered text string
5927 public function stripSectionName( $text ) {
5928 # Strip internal link markup
5929 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5930 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5932 # Strip external link markup
5933 # @todo FIXME: Not tolerant to blank link text
5934 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5935 # on how many empty links there are on the page - need to figure that out.
5936 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5938 # Parse wikitext quotes (italics & bold)
5939 $text = $this->doQuotes( $text );
5942 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5947 * strip/replaceVariables/unstrip for preprocessor regression testing
5949 * @param string $text
5950 * @param Title $title
5951 * @param ParserOptions $options
5952 * @param int $outputType
5956 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5957 $outputType = self
::OT_HTML
5959 $magicScopeVariable = $this->lock();
5960 $this->startParse( $title, $options, $outputType, true );
5962 $text = $this->replaceVariables( $text );
5963 $text = $this->mStripState
->unstripBoth( $text );
5964 $text = Sanitizer
::removeHTMLtags( $text );
5969 * @param string $text
5970 * @param Title $title
5971 * @param ParserOptions $options
5974 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5975 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5979 * @param string $text
5980 * @param Title $title
5981 * @param ParserOptions $options
5984 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5985 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5989 * Call a callback function on all regions of the given text that are not
5990 * inside strip markers, and replace those regions with the return value
5991 * of the callback. For example, with input:
5995 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5996 * two strings will be replaced with the value returned by the callback in
6000 * @param callable $callback
6004 public function markerSkipCallback( $s, $callback ) {
6007 while ( $i < strlen( $s ) ) {
6008 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6009 if ( $markerStart === false ) {
6010 $out .= call_user_func( $callback, substr( $s, $i ) );
6013 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6014 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6015 if ( $markerEnd === false ) {
6016 $out .= substr( $s, $markerStart );
6019 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6020 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6029 * Remove any strip markers found in the given text.
6031 * @param string $text
6034 public function killMarkers( $text ) {
6035 return $this->mStripState
->killMarkers( $text );
6039 * Save the parser state required to convert the given half-parsed text to
6040 * HTML. "Half-parsed" in this context means the output of
6041 * recursiveTagParse() or internalParse(). This output has strip markers
6042 * from replaceVariables (extensionSubstitution() etc.), and link
6043 * placeholders from replaceLinkHolders().
6045 * Returns an array which can be serialized and stored persistently. This
6046 * array can later be loaded into another parser instance with
6047 * unserializeHalfParsedText(). The text can then be safely incorporated into
6048 * the return value of a parser hook.
6050 * @deprecated since 1.31
6051 * @param string $text
6055 public function serializeHalfParsedText( $text ) {
6056 wfDeprecated( __METHOD__
, '1.31' );
6059 'version' => self
::HALF_PARSED_VERSION
,
6060 'stripState' => $this->mStripState
->getSubState( $text ),
6061 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6067 * Load the parser state given in the $data array, which is assumed to
6068 * have been generated by serializeHalfParsedText(). The text contents is
6069 * extracted from the array, and its markers are transformed into markers
6070 * appropriate for the current Parser instance. This transformed text is
6071 * returned, and can be safely included in the return value of a parser
6074 * If the $data array has been stored persistently, the caller should first
6075 * check whether it is still valid, by calling isValidHalfParsedText().
6077 * @deprecated since 1.31
6078 * @param array $data Serialized data
6079 * @throws MWException
6082 public function unserializeHalfParsedText( $data ) {
6083 wfDeprecated( __METHOD__
, '1.31' );
6084 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6085 throw new MWException( __METHOD__
. ': invalid version' );
6088 # First, extract the strip state.
6089 $texts = [ $data['text'] ];
6090 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6092 # Now renumber links
6093 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6095 # Should be good to go.
6100 * Returns true if the given array, presumed to be generated by
6101 * serializeHalfParsedText(), is compatible with the current version of the
6104 * @deprecated since 1.31
6105 * @param array $data
6109 public function isValidHalfParsedText( $data ) {
6110 wfDeprecated( __METHOD__
, '1.31' );
6111 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6115 * Parsed a width param of imagelink like 300px or 200x300px
6117 * @param string $value
6118 * @param bool $parseHeight
6123 public static function parseWidthParam( $value, $parseHeight = true ) {
6124 $parsedWidthParam = [];
6125 if ( $value === '' ) {
6126 return $parsedWidthParam;
6129 # (T15500) In both cases (width/height and width only),
6130 # permit trailing "px" for backward compatibility.
6131 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6132 $width = intval( $m[1] );
6133 $height = intval( $m[2] );
6134 $parsedWidthParam['width'] = $width;
6135 $parsedWidthParam['height'] = $height;
6136 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6137 $width = intval( $value );
6138 $parsedWidthParam['width'] = $width;
6140 return $parsedWidthParam;
6144 * Lock the current instance of the parser.
6146 * This is meant to stop someone from calling the parser
6147 * recursively and messing up all the strip state.
6149 * @throws MWException If parser is in a parse
6150 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6152 protected function lock() {
6153 if ( $this->mInParse
) {
6154 throw new MWException( "Parser state cleared while parsing. "
6155 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6158 // Save the backtrace when locking, so that if some code tries locking again,
6159 // we can print the lock owner's backtrace for easier debugging
6161 $this->mInParse
= $e->getTraceAsString();
6163 $recursiveCheck = new ScopedCallback( function () {
6164 $this->mInParse
= false;
6167 return $recursiveCheck;
6171 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6173 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6174 * or if there is more than one <p/> tag in the input HTML.
6176 * @param string $html
6180 public static function stripOuterParagraph( $html ) {
6182 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6183 if ( strpos( $m[1], '</p>' ) === false ) {
6192 * Return this parser if it is not doing anything, otherwise
6193 * get a fresh parser. You can use this method by doing
6194 * $myParser = $wgParser->getFreshParser(), or more simply
6195 * $wgParser->getFreshParser()->parse( ... );
6196 * if you're unsure if $wgParser is safe to use.
6199 * @return Parser A parser object that is not parsing anything
6201 public function getFreshParser() {
6202 global $wgParserConf;
6203 if ( $this->mInParse
) {
6204 return new $wgParserConf['class']( $wgParserConf );
6211 * Set's up the PHP implementation of OOUI for use in this request
6212 * and instructs OutputPage to enable OOUI for itself.
6216 public function enableOOUI() {
6217 OutputPage
::setupOOUI();
6218 $this->mOutput
->setEnableOOUI( true );