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\BadFileLookup
;
24 use MediaWiki\Config\ServiceOptions
;
25 use MediaWiki\Linker\LinkRenderer
;
26 use MediaWiki\Linker\LinkRendererFactory
;
27 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\MediaWikiServices
;
29 use MediaWiki\Special\SpecialPageFactory
;
30 use Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Psr\Log\LoggerInterface
;
35 * @defgroup Parser Parser
39 * PHP Parser - Processes wiki markup (which uses a more user-friendly
40 * syntax, such as "[[link]]" for making links), and provides a one-way
41 * transformation of that wiki markup it into (X)HTML output / markup
42 * (which in turn the browser understands, and can display).
44 * There are seven main entry points into the Parser class:
47 * produces HTML output
48 * - Parser::preSaveTransform()
49 * produces altered wiki markup
50 * - Parser::preprocess()
51 * removes HTML comments and expands templates
52 * - Parser::cleanSig() and Parser::cleanSigInSig()
53 * cleans a signature before saving it to preferences
54 * - Parser::getSection()
55 * return the content of a section from an article for section editing
56 * - Parser::replaceSection()
57 * replaces a section by number inside an article
58 * - Parser::getPreloadText()
59 * removes <noinclude> sections and <includeonly> tags
61 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
64 * $wgNamespacesWithSubpages
66 * @par Settings only within ParserOptions:
67 * $wgAllowExternalImages
68 * $wgAllowSpecialInclusion
76 * Update this version number when the ParserOutput format
77 * changes in an incompatible way, so the parser cache
78 * can automatically discard old data.
80 const VERSION
= '1.6.4';
83 * Update this version number when the output of serialiseHalfParsedText()
84 * changes in an incompatible way
86 const HALF_PARSED_VERSION
= 2;
88 # Flags for Parser::setFunctionHook
89 const SFH_NO_HASH
= 1;
90 const SFH_OBJECT_ARGS
= 2;
92 # Constants needed for external link processing
93 # Everything except bracket, space, or control characters
94 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
95 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
96 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
97 # uses to replace invalid HTML characters.
98 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
99 # Simplified expression to match an IPv4 or IPv6 address, or
100 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
101 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
102 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
103 // phpcs:ignore Generic.Files.LineLength
104 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
105 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
107 # Regular expression for a non-newline space
108 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
110 # Flags for preprocessToDom
111 const PTD_FOR_INCLUSION
= 1;
113 # Allowed values for $this->mOutputType
114 # Parameter to startExternalParse().
115 const OT_HTML
= 1; # like parse()
116 const OT_WIKI
= 2; # like preSaveTransform()
117 const OT_PREPROCESS
= 3; # like preprocess()
119 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
122 * @var string Prefix and suffix for temporary replacement strings
123 * for the multipass parser.
125 * \x7f should never appear in input as it's disallowed in XML.
126 * Using it at the front also gives us a little extra robustness
127 * since it shouldn't match when butted up against identifier-like
130 * Must not consist of all title characters, or else it will change
131 * the behavior of <nowiki> in a link.
133 * Must have a character that needs escaping in attributes, otherwise
134 * someone could put a strip marker in an attribute, to get around
135 * escaping quote marks, and break out of the attribute. Thus we add
138 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
139 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
141 # Markers used for wrapping the table of contents
142 const TOC_START
= '<mw:toc>';
143 const TOC_END
= '</mw:toc>';
145 /** @var int Assume that no output will later be saved this many seconds after parsing */
149 public $mTagHooks = [];
150 public $mTransparentTagHooks = [];
151 public $mFunctionHooks = [];
152 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
153 public $mFunctionTagHooks = [];
154 public $mStripList = [];
155 public $mDefaultStripList = [];
156 public $mVarCache = [];
157 public $mImageParams = [];
158 public $mImageParamsMagicArray = [];
159 public $mMarkerIndex = 0;
161 * @var bool Whether firstCallInit still needs to be called
163 public $mFirstCall = true;
165 # Initialised by initializeVariables()
168 * @var MagicWordArray
173 * @var MagicWordArray
178 * @deprecated since 1.34, there should be no need to use this
183 # Initialised in constructor
184 public $mExtLinkBracketedRegex, $mUrlProtocols;
186 # Initialized in getPreprocessor()
187 /** @var Preprocessor */
188 public $mPreprocessor;
190 # Cleared with clearState():
202 public $mIncludeCount;
204 * @var LinkHolderArray
206 public $mLinkHolders;
209 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
210 public $mDefaultSort;
211 public $mTplRedirCache, $mHeadings, $mDoubleUnderscores;
212 public $mExpensiveFunctionCount; # number of expensive parser function calls
213 public $mShowToc, $mForceTocPosition;
215 public $mTplDomCache;
220 public $mUser; # User object; only used when doing pre-save transform
223 # These are variables reset at least once per parse regardless of $clearState
231 * Since 1.34, leaving `mTitle` uninitialized or setting `mTitle` to
232 * `null` is deprecated.
237 public $mTitle; # Title context, used for self-link rendering and similar things
238 public $mOutputType; # Output type, one of the OT_xxx constants
239 public $ot; # Shortcut alias, see setOutputType()
240 public $mRevisionObject; # The revision object of the specified revision ID
241 public $mRevisionId; # ID to display in {{REVISIONID}} tags
242 public $mRevisionTimestamp; # The timestamp of the specified revision ID
243 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
244 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
245 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
246 public $mInputSize = false; # For {{PAGESIZE}} on current page.
249 * @var array Array with the language name of each language link (i.e. the
250 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
251 * duplicate language links to the ParserOutput.
253 public $mLangLinkLanguages;
256 * @var MapCacheLRU|null
259 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
261 public $currentRevisionCache;
264 * @var bool|string Recursive call protection.
265 * This variable should be treated as if it were private.
267 public $mInParse = false;
269 /** @var SectionProfiler */
270 protected $mProfiler;
275 protected $mLinkRenderer;
277 /** @var MagicWordFactory */
278 private $magicWordFactory;
283 /** @var ParserFactory */
286 /** @var SpecialPageFactory */
287 private $specialPageFactory;
290 * This is called $svcOptions instead of $options like elsewhere to avoid confusion with
291 * $mOptions, which is public and widely used, and also with the local variable $options used
292 * for ParserOptions throughout this file.
294 * @var ServiceOptions
298 /** @var LinkRendererFactory */
299 private $linkRendererFactory;
301 /** @var NamespaceInfo */
304 /** @var LoggerInterface */
307 /** @var BadFileLookup */
308 private $badFileLookup;
311 * TODO Make this a const when HHVM support is dropped (T192166)
316 public static $constructorOptions = [
317 // See $wgParserConf documentation
320 // See documentation for the corresponding config options
322 'EnableScaryTranscluding',
323 'ExtraInterlanguageLinkPrefixes',
335 'TranscludeCacheExpiry',
339 * Constructing parsers directly is deprecated! Use a ParserFactory.
341 * @param ServiceOptions|null $svcOptions
342 * @param MagicWordFactory|null $magicWordFactory
343 * @param Language|null $contLang Content language
344 * @param ParserFactory|null $factory
345 * @param string|null $urlProtocols As returned from wfUrlProtocols()
346 * @param SpecialPageFactory|null $spFactory
347 * @param LinkRendererFactory|null $linkRendererFactory
348 * @param NamespaceInfo|null $nsInfo
349 * @param LoggerInterface|null $logger
350 * @param BadFileLookup|null $badFileLookup
352 public function __construct(
354 MagicWordFactory
$magicWordFactory = null,
355 Language
$contLang = null,
356 ParserFactory
$factory = null,
357 $urlProtocols = null,
358 SpecialPageFactory
$spFactory = null,
359 $linkRendererFactory = null,
362 BadFileLookup
$badFileLookup = null
364 if ( !$svcOptions ||
is_array( $svcOptions ) ) {
365 // Pre-1.34 calling convention is the first parameter is just ParserConf, the seventh is
366 // Config, and the eighth is LinkRendererFactory.
367 $this->mConf
= (array)$svcOptions;
368 if ( empty( $this->mConf
['class'] ) ) {
369 $this->mConf
['class'] = self
::class;
371 if ( empty( $this->mConf
['preprocessorClass'] ) ) {
372 $this->mConf
['preprocessorClass'] = self
::getDefaultPreprocessorClass();
374 $this->svcOptions
= new ServiceOptions( self
::$constructorOptions,
375 $this->mConf
, func_num_args() > 6
376 ?
func_get_arg( 6 ) : MediaWikiServices
::getInstance()->getMainConfig()
378 $linkRendererFactory = func_num_args() > 7 ?
func_get_arg( 7 ) : null;
379 $nsInfo = func_num_args() > 8 ?
func_get_arg( 8 ) : null;
381 // New calling convention
382 $svcOptions->assertRequiredOptions( self
::$constructorOptions );
383 // $this->mConf is public, so we'll keep those two options there as well for
384 // compatibility until it's removed
386 'class' => $svcOptions->get( 'class' ),
387 'preprocessorClass' => $svcOptions->get( 'preprocessorClass' ),
389 $this->svcOptions
= $svcOptions;
392 $this->mUrlProtocols
= $urlProtocols ??
wfUrlProtocols();
393 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
394 self
::EXT_LINK_ADDR
.
395 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
397 $this->magicWordFactory
= $magicWordFactory ??
398 MediaWikiServices
::getInstance()->getMagicWordFactory();
400 $this->contLang
= $contLang ?? MediaWikiServices
::getInstance()->getContentLanguage();
402 $this->factory
= $factory ?? MediaWikiServices
::getInstance()->getParserFactory();
403 $this->specialPageFactory
= $spFactory ??
404 MediaWikiServices
::getInstance()->getSpecialPageFactory();
405 $this->linkRendererFactory
= $linkRendererFactory ??
406 MediaWikiServices
::getInstance()->getLinkRendererFactory();
407 $this->nsInfo
= $nsInfo ?? MediaWikiServices
::getInstance()->getNamespaceInfo();
408 $this->logger
= $logger ?
: new NullLogger();
409 $this->badFileLookup
= $badFileLookup ??
410 MediaWikiServices
::getInstance()->getBadFileLookup();
414 * Reduce memory usage to reduce the impact of circular references
416 public function __destruct() {
417 if ( isset( $this->mLinkHolders
) ) {
418 // @phan-suppress-next-line PhanTypeObjectUnsetDeclaredProperty
419 unset( $this->mLinkHolders
);
421 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
422 foreach ( $this as $name => $value ) {
423 unset( $this->$name );
428 * Allow extensions to clean up when the parser is cloned
430 public function __clone() {
431 $this->mInParse
= false;
433 // T58226: When you create a reference "to" an object field, that
434 // makes the object field itself be a reference too (until the other
435 // reference goes out of scope). When cloning, any field that's a
436 // reference is copied as a reference in the new object. Both of these
437 // are defined PHP5 behaviors, as inconvenient as it is for us when old
438 // hooks from PHP4 days are passing fields by reference.
439 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
440 // Make a non-reference copy of the field, then rebind the field to
441 // reference the new copy.
447 Hooks
::run( 'ParserCloned', [ $this ] );
451 * Which class should we use for the preprocessor if not otherwise specified?
454 * @deprecated since 1.34, removing configurability of preprocessor
457 public static function getDefaultPreprocessorClass() {
458 return Preprocessor_Hash
::class;
462 * Do various kinds of initialisation on the first call of the parser
464 public function firstCallInit() {
465 if ( !$this->mFirstCall
) {
468 $this->mFirstCall
= false;
470 CoreParserFunctions
::register( $this );
471 CoreTagHooks
::register( $this );
472 $this->initializeVariables();
474 // Avoid PHP 7.1 warning from passing $this by reference
476 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
484 public function clearState() {
485 $this->firstCallInit();
486 $this->resetOutput();
487 $this->mAutonumber
= 0;
488 $this->mIncludeCount
= [];
489 $this->mLinkHolders
= new LinkHolderArray( $this );
491 $this->mRevisionObject
= $this->mRevisionTimestamp
=
492 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
493 $this->mVarCache
= [];
495 $this->mLangLinkLanguages
= [];
496 $this->currentRevisionCache
= null;
498 $this->mStripState
= new StripState( $this );
500 # Clear these on every parse, T6549
501 $this->mTplRedirCache
= $this->mTplDomCache
= [];
503 $this->mShowToc
= true;
504 $this->mForceTocPosition
= false;
505 $this->mIncludeSizes
= [
509 $this->mPPNodeCount
= 0;
510 $this->mGeneratedPPNodeCount
= 0;
511 $this->mHighestExpansionDepth
= 0;
512 $this->mDefaultSort
= false;
513 $this->mHeadings
= [];
514 $this->mDoubleUnderscores
= [];
515 $this->mExpensiveFunctionCount
= 0;
518 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
519 $this->mPreprocessor
= null;
522 $this->mProfiler
= new SectionProfiler();
524 // Avoid PHP 7.1 warning from passing $this by reference
526 Hooks
::run( 'ParserClearState', [ &$parser ] );
530 * Reset the ParserOutput
532 public function resetOutput() {
533 $this->mOutput
= new ParserOutput
;
534 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
538 * Convert wikitext to HTML
539 * Do not call this function recursively.
541 * @param string $text Text we want to parse
542 * @param-taint $text escapes_htmlnoent
543 * @param Title $title
544 * @param ParserOptions $options
545 * @param bool $linestart
546 * @param bool $clearState
547 * @param int|null $revid ID of the revision being rendered. This is used to render
548 * REVISION* magic words. 0 means that any current revision will be used. Null means
549 * that {{REVISIONID}}/{{REVISIONUSER}} will be empty and {{REVISIONTIMESTAMP}} will
550 * use the current timestamp.
551 * @return ParserOutput A ParserOutput
552 * @return-taint escaped
554 public function parse(
555 $text, Title
$title, ParserOptions
$options,
556 $linestart = true, $clearState = true, $revid = null
559 // We use U+007F DELETE to construct strip markers, so we have to make
560 // sure that this character does not occur in the input text.
561 $text = strtr( $text, "\x7f", "?" );
562 $magicScopeVariable = $this->lock();
564 // Strip U+0000 NULL (T159174)
565 $text = str_replace( "\000", '', $text );
567 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
569 $this->currentRevisionCache
= null;
570 $this->mInputSize
= strlen( $text );
571 if ( $this->mOptions
->getEnableLimitReport() ) {
572 $this->mOutput
->resetParseStartTime();
575 $oldRevisionId = $this->mRevisionId
;
576 $oldRevisionObject = $this->mRevisionObject
;
577 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
578 $oldRevisionUser = $this->mRevisionUser
;
579 $oldRevisionSize = $this->mRevisionSize
;
580 if ( $revid !== null ) {
581 $this->mRevisionId
= $revid;
582 $this->mRevisionObject
= null;
583 $this->mRevisionTimestamp
= null;
584 $this->mRevisionUser
= null;
585 $this->mRevisionSize
= null;
588 // Avoid PHP 7.1 warning from passing $this by reference
590 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
592 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
593 $text = $this->internalParse( $text );
594 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
596 $text = $this->internalParseHalfParsed( $text, true, $linestart );
599 * A converted title will be provided in the output object if title and
600 * content conversion are enabled, the article text does not contain
601 * a conversion-suppressing double-underscore tag, and no
602 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
603 * automatic link conversion.
605 if ( !( $options->getDisableTitleConversion()
606 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
607 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
608 ||
$this->mOutput
->getDisplayTitle() !== false )
610 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
611 if ( $convruletitle ) {
612 $this->mOutput
->setTitleText( $convruletitle );
614 $titleText = $this->getTargetLanguage()->convertTitle( $title );
615 $this->mOutput
->setTitleText( $titleText );
619 # Compute runtime adaptive expiry if set
620 $this->mOutput
->finalizeAdaptiveCacheExpiry();
622 # Warn if too many heavyweight parser functions were used
623 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
624 $this->limitationWarn( 'expensive-parserfunction',
625 $this->mExpensiveFunctionCount
,
626 $this->mOptions
->getExpensiveParserFunctionLimit()
630 # Information on limits, for the benefit of users who try to skirt them
631 if ( $this->mOptions
->getEnableLimitReport() ) {
632 $text .= $this->makeLimitReport();
635 # Wrap non-interface parser output in a <div> so it can be targeted
637 $class = $this->mOptions
->getWrapOutputClass();
638 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
639 $this->mOutput
->addWrapperDivClass( $class );
642 $this->mOutput
->setText( $text );
644 $this->mRevisionId
= $oldRevisionId;
645 $this->mRevisionObject
= $oldRevisionObject;
646 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
647 $this->mRevisionUser
= $oldRevisionUser;
648 $this->mRevisionSize
= $oldRevisionSize;
649 $this->mInputSize
= false;
650 $this->currentRevisionCache
= null;
652 return $this->mOutput
;
656 * Set the limit report data in the current ParserOutput, and return the
657 * limit report HTML comment.
661 protected function makeLimitReport() {
662 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
664 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
665 if ( $cpuTime !== null ) {
666 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
667 sprintf( "%.3f", $cpuTime )
671 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
672 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
673 sprintf( "%.3f", $wallTime )
676 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
677 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
679 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
680 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
682 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
683 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
685 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
686 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
688 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
689 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
691 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
692 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
695 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
696 $this->mOutput
->setLimitReportData( $key, $value );
699 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
701 $limitReport = "NewPP limit report\n";
702 if ( $this->svcOptions
->get( 'ShowHostnames' ) ) {
703 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
705 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
706 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
707 $limitReport .= 'Dynamic content: ' .
708 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
710 $limitReport .= 'Complications: [' . implode( ', ', $this->mOutput
->getAllFlags() ) . "]\n";
712 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
713 if ( Hooks
::run( 'ParserLimitReportFormat',
714 [ $key, &$value, &$limitReport, false, false ]
716 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
717 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
718 ->inLanguage( 'en' )->useDatabase( false );
719 if ( !$valueMsg->exists() ) {
720 $valueMsg = new RawMessage( '$1' );
722 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
723 $valueMsg->params( $value );
724 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
728 // Since we're not really outputting HTML, decode the entities and
729 // then re-encode the things that need hiding inside HTML comments.
730 $limitReport = htmlspecialchars_decode( $limitReport );
732 // Sanitize for comment. Note '‐' in the replacement is U+2010,
733 // which looks much like the problematic '-'.
734 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
735 $text = "\n<!-- \n$limitReport-->\n";
737 // Add on template profiling data in human/machine readable way
738 $dataByFunc = $this->mProfiler
->getFunctionStats();
739 uasort( $dataByFunc, function ( $a, $b ) {
740 return $b['real'] <=> $a['real']; // descending order
743 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
744 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
745 $item['%real'], $item['real'], $item['calls'],
746 htmlspecialchars( $item['name'] ) );
748 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
749 $text .= implode( "\n", $profileReport ) . "\n-->\n";
751 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
753 // Add other cache related metadata
754 if ( $this->svcOptions
->get( 'ShowHostnames' ) ) {
755 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
757 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
758 $this->mOutput
->getCacheTime() );
759 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
760 $this->mOutput
->getCacheExpiry() );
761 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
762 $this->mOutput
->hasDynamicContent() );
764 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
765 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
766 $this->mTitle
->getPrefixedDBkey() );
772 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
773 * can be called from an extension tag hook.
775 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
776 * instead, which means that lists and links have not been fully parsed yet,
777 * and strip markers are still present.
779 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
781 * Use this function if you're a parser tag hook and you want to parse
782 * wikitext before or after applying additional transformations, and you
783 * intend to *return the result as hook output*, which will cause it to go
784 * through the rest of parsing process automatically.
786 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
787 * $text are not expanded
789 * @param string $text Text extension wants to have parsed
790 * @param-taint $text escapes_htmlnoent
791 * @param bool|PPFrame $frame The frame to use for expanding any template variables
792 * @return string UNSAFE half-parsed HTML
793 * @return-taint escaped
795 public function recursiveTagParse( $text, $frame = false ) {
796 // Avoid PHP 7.1 warning from passing $this by reference
798 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
799 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
800 $text = $this->internalParse( $text, false, $frame );
805 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
806 * point can be called from an extension tag hook.
808 * The output of this function is fully-parsed HTML that is safe for output.
809 * If you're a parser tag hook, you might want to use recursiveTagParse()
812 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
813 * $text are not expanded
817 * @param string $text Text extension wants to have parsed
818 * @param-taint $text escapes_htmlnoent
819 * @param bool|PPFrame $frame The frame to use for expanding any template variables
820 * @return string Fully parsed HTML
821 * @return-taint escaped
823 public function recursiveTagParseFully( $text, $frame = false ) {
824 $text = $this->recursiveTagParse( $text, $frame );
825 $text = $this->internalParseHalfParsed( $text, false );
830 * Expand templates and variables in the text, producing valid, static wikitext.
831 * Also removes comments.
832 * Do not call this function recursively.
833 * @param string $text
834 * @param Title|null $title
835 * @param ParserOptions $options
836 * @param int|null $revid
837 * @param bool|PPFrame $frame
838 * @return mixed|string
840 public function preprocess( $text, Title
$title = null,
841 ParserOptions
$options, $revid = null, $frame = false
843 $magicScopeVariable = $this->lock();
844 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
845 if ( $revid !== null ) {
846 $this->mRevisionId
= $revid;
848 // Avoid PHP 7.1 warning from passing $this by reference
850 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
851 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
852 $text = $this->replaceVariables( $text, $frame );
853 $text = $this->mStripState
->unstripBoth( $text );
858 * Recursive parser entry point that can be called from an extension tag
861 * @param string $text Text to be expanded
862 * @param bool|PPFrame $frame The frame to use for expanding any template variables
866 public function recursivePreprocess( $text, $frame = false ) {
867 $text = $this->replaceVariables( $text, $frame );
868 $text = $this->mStripState
->unstripBoth( $text );
873 * Process the wikitext for the "?preload=" feature. (T7210)
875 * "<noinclude>", "<includeonly>" etc. are parsed as for template
876 * transclusion, comments, templates, arguments, tags hooks and parser
877 * functions are untouched.
879 * @param string $text
880 * @param Title $title
881 * @param ParserOptions $options
882 * @param array $params
885 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
886 $msg = new RawMessage( $text );
887 $text = $msg->params( $params )->plain();
889 # Parser (re)initialisation
890 $magicScopeVariable = $this->lock();
891 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
893 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
894 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
895 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
896 $text = $this->mStripState
->unstripBoth( $text );
901 * Set the current user.
902 * Should only be used when doing pre-save transform.
904 * @param User|null $user User object or null (to reset)
906 public function setUser( $user ) {
907 $this->mUser
= $user;
911 * Set the context title
913 * @param Title|null $t
915 public function setTitle( Title
$t = null ) {
917 $t = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/Parser' );
920 if ( $t->hasFragment() ) {
921 # Strip the fragment to avoid various odd effects
922 $this->mTitle
= $t->createFragmentTarget( '' );
929 * Accessor for the Title object
931 * Since 1.34, leaving `mTitle` uninitialized as `null` is deprecated.
935 public function getTitle() : ?Title
{
936 if ( $this->mTitle
=== null ) {
937 wfDeprecated( 'Parser title should never be null', '1.34' );
939 return $this->mTitle
;
943 * Accessor/mutator for the Title object
945 * @param Title|null $x Title object or null to just get the current one
948 public function Title( Title
$x = null ) : ?Title
{
949 return wfSetVar( $this->mTitle
, $x );
953 * Set the output type
955 * @param int $ot New value
957 public function setOutputType( $ot ) {
958 $this->mOutputType
= $ot;
961 'html' => $ot == self
::OT_HTML
,
962 'wiki' => $ot == self
::OT_WIKI
,
963 'pre' => $ot == self
::OT_PREPROCESS
,
964 'plain' => $ot == self
::OT_PLAIN
,
969 * Accessor/mutator for the output type
971 * @param int|null $x New value or null to just get the current one
974 public function OutputType( $x = null ) {
975 return wfSetVar( $this->mOutputType
, $x );
979 * Get the ParserOutput object
981 * @return ParserOutput
983 public function getOutput() {
984 return $this->mOutput
;
988 * Get the ParserOptions object
990 * @return ParserOptions
992 public function getOptions() {
993 return $this->mOptions
;
997 * Accessor/mutator for the ParserOptions object
999 * @param ParserOptions|null $x New value or null to just get the current one
1000 * @return ParserOptions Current ParserOptions object
1002 public function Options( $x = null ) {
1003 return wfSetVar( $this->mOptions
, $x );
1009 public function nextLinkID() {
1010 return $this->mLinkID++
;
1016 public function setLinkID( $id ) {
1017 $this->mLinkID
= $id;
1021 * Get a language object for use in parser functions such as {{FORMATNUM:}}
1024 public function getFunctionLang() {
1025 return $this->getTargetLanguage();
1029 * Get the target language for the content being parsed. This is usually the
1030 * language that the content is in.
1034 * @throws MWException
1037 public function getTargetLanguage() {
1038 $target = $this->mOptions
->getTargetLanguage();
1040 if ( $target !== null ) {
1042 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
1043 return $this->mOptions
->getUserLangObj();
1044 } elseif ( is_null( $this->mTitle
) ) {
1045 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
1048 return $this->mTitle
->getPageLanguage();
1052 * Get the language object for language conversion
1053 * @deprecated since 1.32, just use getTargetLanguage()
1054 * @return Language|null
1056 public function getConverterLanguage() {
1057 return $this->getTargetLanguage();
1061 * Get a User object either from $this->mUser, if set, or from the
1062 * ParserOptions object otherwise
1066 public function getUser() {
1067 if ( !is_null( $this->mUser
) ) {
1068 return $this->mUser
;
1070 return $this->mOptions
->getUser();
1074 * Get a preprocessor object
1076 * @return Preprocessor
1078 public function getPreprocessor() {
1079 if ( !isset( $this->mPreprocessor
) ) {
1080 $class = $this->svcOptions
->get( 'preprocessorClass' );
1081 $this->mPreprocessor
= new $class( $this );
1083 return $this->mPreprocessor
;
1087 * Get a LinkRenderer instance to make links with
1090 * @return LinkRenderer
1092 public function getLinkRenderer() {
1093 // XXX We make the LinkRenderer with current options and then cache it forever
1094 if ( !$this->mLinkRenderer
) {
1095 $this->mLinkRenderer
= $this->linkRendererFactory
->create();
1096 $this->mLinkRenderer
->setStubThreshold(
1097 $this->getOptions()->getStubThreshold()
1101 return $this->mLinkRenderer
;
1105 * Get the MagicWordFactory that this Parser is using
1108 * @return MagicWordFactory
1110 public function getMagicWordFactory() {
1111 return $this->magicWordFactory
;
1115 * Get the content language that this Parser is using
1120 public function getContentLanguage() {
1121 return $this->contLang
;
1125 * Replaces all occurrences of HTML-style comments and the given tags
1126 * in the text with a random marker and returns the next text. The output
1127 * parameter $matches will be an associative array filled with data in
1134 * [ 'param' => 'x' ],
1135 * '<element param="x">tag content</element>' ]
1138 * @param array $elements List of element names. Comments are always extracted.
1139 * @param string $text Source text string.
1140 * @param array &$matches Out parameter, Array: extracted tags
1141 * @return string Stripped text
1143 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1148 $taglist = implode( '|', $elements );
1149 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
1151 while ( $text != '' ) {
1152 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1154 if ( count( $p ) < 5 ) {
1157 if ( count( $p ) > 5 ) {
1165 list( , $element, $attributes, $close, $inside ) = $p;
1168 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1169 $stripped .= $marker;
1171 if ( $close === '/>' ) {
1172 # Empty element tag, <tag />
1177 if ( $element === '!--' ) {
1180 $end = "/(<\\/$element\\s*>)/i";
1182 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1184 if ( count( $q ) < 3 ) {
1185 # No end tag -- let it run out to the end of the text.
1189 list( , $tail, $text ) = $q;
1193 $matches[$marker] = [ $element,
1195 Sanitizer
::decodeTagAttributes( $attributes ),
1196 "<$element$attributes$close$content$tail" ];
1202 * Get a list of strippable XML-like elements
1206 public function getStripList() {
1207 return $this->mStripList
;
1211 * Get the StripState
1213 * @return StripState
1215 public function getStripState() {
1216 return $this->mStripState
;
1220 * Add an item to the strip state
1221 * Returns the unique tag which must be inserted into the stripped text
1222 * The tag will be replaced with the original text in unstrip()
1224 * @param string $text
1228 public function insertStripItem( $text ) {
1229 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1230 $this->mMarkerIndex++
;
1231 $this->mStripState
->addGeneral( $marker, $text );
1236 * Parse the wiki syntax used to render tables.
1239 * @param string $text
1241 * @deprecated since 1.34; should not be used outside parser class.
1243 public function doTableStuff( $text ) {
1244 wfDeprecated( __METHOD__
, '1.34' );
1245 return $this->handleTables( $text );
1249 * Parse the wiki syntax used to render tables.
1251 * @param string $text
1254 private function handleTables( $text ) {
1255 $lines = StringUtils
::explode( "\n", $text );
1257 $td_history = []; # Is currently a td tag open?
1258 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1259 $tr_history = []; # Is currently a tr tag open?
1260 $tr_attributes = []; # history of tr attributes
1261 $has_opened_tr = []; # Did this table open a <tr> element?
1262 $indent_level = 0; # indent level of the table
1264 foreach ( $lines as $outLine ) {
1265 $line = trim( $outLine );
1267 if ( $line === '' ) { # empty line, go to next line
1268 $out .= $outLine . "\n";
1272 $first_character = $line[0];
1273 $first_two = substr( $line, 0, 2 );
1276 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1277 # First check if we are starting a new table
1278 $indent_level = strlen( $matches[1] );
1280 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1281 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1283 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1284 array_push( $td_history, false );
1285 array_push( $last_tag_history, '' );
1286 array_push( $tr_history, false );
1287 array_push( $tr_attributes, '' );
1288 array_push( $has_opened_tr, false );
1289 } elseif ( count( $td_history ) == 0 ) {
1290 # Don't do any of the following
1291 $out .= $outLine . "\n";
1293 } elseif ( $first_two === '|}' ) {
1294 # We are ending a table
1295 $line = '</table>' . substr( $line, 2 );
1296 $last_tag = array_pop( $last_tag_history );
1298 if ( !array_pop( $has_opened_tr ) ) {
1299 $line = "<tr><td></td></tr>{$line}";
1302 if ( array_pop( $tr_history ) ) {
1303 $line = "</tr>{$line}";
1306 if ( array_pop( $td_history ) ) {
1307 $line = "</{$last_tag}>{$line}";
1309 array_pop( $tr_attributes );
1310 if ( $indent_level > 0 ) {
1311 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1315 } elseif ( $first_two === '|-' ) {
1316 # Now we have a table row
1317 $line = preg_replace( '#^\|-+#', '', $line );
1319 # Whats after the tag is now only attributes
1320 $attributes = $this->mStripState
->unstripBoth( $line );
1321 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1322 array_pop( $tr_attributes );
1323 array_push( $tr_attributes, $attributes );
1326 $last_tag = array_pop( $last_tag_history );
1327 array_pop( $has_opened_tr );
1328 array_push( $has_opened_tr, true );
1330 if ( array_pop( $tr_history ) ) {
1334 if ( array_pop( $td_history ) ) {
1335 $line = "</{$last_tag}>{$line}";
1339 array_push( $tr_history, false );
1340 array_push( $td_history, false );
1341 array_push( $last_tag_history, '' );
1342 } elseif ( $first_character === '|'
1343 ||
$first_character === '!'
1344 ||
$first_two === '|+'
1346 # This might be cell elements, td, th or captions
1347 if ( $first_two === '|+' ) {
1348 $first_character = '+';
1349 $line = substr( $line, 2 );
1351 $line = substr( $line, 1 );
1354 // Implies both are valid for table headings.
1355 if ( $first_character === '!' ) {
1356 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1359 # Split up multiple cells on the same line.
1360 # FIXME : This can result in improper nesting of tags processed
1361 # by earlier parser steps.
1362 $cells = explode( '||', $line );
1366 # Loop through each table cell
1367 foreach ( $cells as $cell ) {
1369 if ( $first_character !== '+' ) {
1370 $tr_after = array_pop( $tr_attributes );
1371 if ( !array_pop( $tr_history ) ) {
1372 $previous = "<tr{$tr_after}>\n";
1374 array_push( $tr_history, true );
1375 array_push( $tr_attributes, '' );
1376 array_pop( $has_opened_tr );
1377 array_push( $has_opened_tr, true );
1380 $last_tag = array_pop( $last_tag_history );
1382 if ( array_pop( $td_history ) ) {
1383 $previous = "</{$last_tag}>\n{$previous}";
1386 if ( $first_character === '|' ) {
1388 } elseif ( $first_character === '!' ) {
1390 } elseif ( $first_character === '+' ) {
1391 $last_tag = 'caption';
1396 array_push( $last_tag_history, $last_tag );
1398 # A cell could contain both parameters and data
1399 $cell_data = explode( '|', $cell, 2 );
1401 # T2553: Note that a '|' inside an invalid link should not
1402 # be mistaken as delimiting cell parameters
1403 # Bug T153140: Neither should language converter markup.
1404 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1405 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1406 } elseif ( count( $cell_data ) == 1 ) {
1407 // Whitespace in cells is trimmed
1408 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1410 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1411 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1412 // Whitespace in cells is trimmed
1413 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1417 array_push( $td_history, true );
1420 $out .= $outLine . "\n";
1423 # Closing open td, tr && table
1424 while ( count( $td_history ) > 0 ) {
1425 if ( array_pop( $td_history ) ) {
1428 if ( array_pop( $tr_history ) ) {
1431 if ( !array_pop( $has_opened_tr ) ) {
1432 $out .= "<tr><td></td></tr>\n";
1435 $out .= "</table>\n";
1438 # Remove trailing line-ending (b/c)
1439 if ( substr( $out, -1 ) === "\n" ) {
1440 $out = substr( $out, 0, -1 );
1443 # special case: don't return empty table
1444 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1452 * Helper function for parse() that transforms wiki markup into half-parsed
1453 * HTML. Only called for $mOutputType == self::OT_HTML.
1457 * @param string $text The text to parse
1458 * @param-taint $text escapes_html
1459 * @param bool $isMain Whether this is being called from the main parse() function
1460 * @param PPFrame|bool $frame A pre-processor frame
1464 public function internalParse( $text, $isMain = true, $frame = false ) {
1467 // Avoid PHP 7.1 warning from passing $this by reference
1470 # Hook to suspend the parser in this state
1471 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1475 # if $frame is provided, then use $frame for replacing any variables
1477 # use frame depth to infer how include/noinclude tags should be handled
1478 # depth=0 means this is the top-level document; otherwise it's an included document
1479 if ( !$frame->depth
) {
1482 $flag = self
::PTD_FOR_INCLUSION
;
1484 $dom = $this->preprocessToDom( $text, $flag );
1485 $text = $frame->expand( $dom );
1487 # if $frame is not provided, then use old-style replaceVariables
1488 $text = $this->replaceVariables( $text );
1491 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1492 $text = Sanitizer
::removeHTMLtags(
1494 [ $this, 'attributeStripCallback' ],
1496 array_keys( $this->mTransparentTagHooks
),
1498 [ $this, 'addTrackingCategory' ]
1500 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1502 # Tables need to come after variable replacement for things to work
1503 # properly; putting them before other transformations should keep
1504 # exciting things like link expansions from showing up in surprising
1506 $text = $this->handleTables( $text );
1508 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1510 $text = $this->handleDoubleUnderscore( $text );
1512 $text = $this->handleHeadings( $text );
1513 $text = $this->handleInternalLinks( $text );
1514 $text = $this->handleAllQuotes( $text );
1515 $text = $this->handleExternalLinks( $text );
1517 # handleInternalLinks may sometimes leave behind
1518 # absolute URLs, which have to be masked to hide them from handleExternalLinks
1519 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1521 $text = $this->handleMagicLinks( $text );
1522 $text = $this->finalizeHeadings( $text, $origText, $isMain );
1528 * Helper function for parse() that transforms half-parsed HTML into fully
1531 * @param string $text
1532 * @param bool $isMain
1533 * @param bool $linestart
1536 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1537 $text = $this->mStripState
->unstripGeneral( $text );
1539 // Avoid PHP 7.1 warning from passing $this by reference
1543 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1546 # Clean up special characters, only run once, next-to-last before doBlockLevels
1547 $text = Sanitizer
::armorFrenchSpaces( $text );
1549 $text = $this->doBlockLevels( $text, $linestart );
1551 $this->replaceLinkHoldersPrivate( $text );
1554 * The input doesn't get language converted if
1556 * b) Content isn't converted
1557 * c) It's a conversion table
1558 * d) it is an interface message (which is in the user language)
1560 if ( !( $this->mOptions
->getDisableContentConversion()
1561 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1562 && !$this->mOptions
->getInterfaceMessage()
1564 # The position of the convert() call should not be changed. it
1565 # assumes that the links are all replaced and the only thing left
1566 # is the <nowiki> mark.
1567 $text = $this->getTargetLanguage()->convert( $text );
1570 $text = $this->mStripState
->unstripNoWiki( $text );
1573 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1576 $text = $this->replaceTransparentTags( $text );
1577 $text = $this->mStripState
->unstripGeneral( $text );
1579 $text = Sanitizer
::normalizeCharReferences( $text );
1581 if ( MWTidy
::isEnabled() ) {
1582 if ( $this->mOptions
->getTidy() ) {
1583 $text = MWTidy
::tidy( $text );
1586 # attempt to sanitize at least some nesting problems
1587 # (T4702 and quite a few others)
1588 # This code path is buggy and deprecated!
1589 wfDeprecated( 'disabling tidy', '1.33' );
1591 # ''Something [http://www.cool.com cool''] -->
1592 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1593 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1594 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1595 # fix up an anchor inside another anchor, only
1596 # at least for a single single nested link (T5695)
1597 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1598 '\\1\\2</a>\\3</a>\\1\\4</a>',
1599 # fix div inside inline elements- doBlockLevels won't wrap a line which
1600 # contains a div, so fix it up here; replace
1601 # div with escaped text
1602 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1603 '\\1\\3<div\\5>\\6</div>\\8\\9',
1604 # remove empty italic or bold tag pairs, some
1605 # introduced by rules above
1606 '/<([bi])><\/\\1>/' => '',
1609 $text = preg_replace(
1610 array_keys( $tidyregs ),
1611 array_values( $tidyregs ),
1616 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1623 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1624 * magic external links.
1628 * @param string $text
1630 * @deprecated since 1.34; should not be used outside parser class.
1632 public function doMagicLinks( $text ) {
1633 wfDeprecated( __METHOD__
, '1.34' );
1634 return $this->handleMagicLinks( $text );
1638 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1639 * magic external links.
1643 * @param string $text
1647 private function handleMagicLinks( $text ) {
1648 $prots = wfUrlProtocolsWithoutProtRel();
1649 $urlChar = self
::EXT_LINK_URL_CLASS
;
1650 $addr = self
::EXT_LINK_ADDR
;
1651 $space = self
::SPACE_NOT_NL
; # non-newline space
1652 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1653 $spaces = "$space++"; # possessive match of 1 or more spaces
1654 $text = preg_replace_callback(
1656 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1657 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1658 (\b # m[3]: Free external links
1660 ($addr$urlChar*) # m[4]: Post-protocol path
1662 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1664 \bISBN $spaces ( # m[6]: ISBN, capture number
1665 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1666 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1667 [0-9Xx] # check digit
1669 )!xu", [ $this, 'magicLinkCallback' ], $text );
1674 * @throws MWException
1676 * @return string HTML
1678 public function magicLinkCallback( $m ) {
1679 if ( isset( $m[1] ) && $m[1] !== '' ) {
1682 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1685 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1686 # Free external link
1687 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1688 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1690 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1691 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1696 $cssClass = 'mw-magiclink-rfc';
1697 $trackingCat = 'magiclink-tracking-rfc';
1699 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1700 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1704 $urlmsg = 'pubmedurl';
1705 $cssClass = 'mw-magiclink-pmid';
1706 $trackingCat = 'magiclink-tracking-pmid';
1709 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1710 substr( $m[0], 0, 20 ) . '"' );
1712 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1713 $this->addTrackingCategory( $trackingCat );
1714 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1715 } elseif ( isset( $m[6] ) && $m[6] !== ''
1716 && $this->mOptions
->getMagicISBNLinks()
1720 $space = self
::SPACE_NOT_NL
; # non-newline space
1721 $isbn = preg_replace( "/$space/", ' ', $isbn );
1722 $num = strtr( $isbn, [
1727 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1728 return $this->getLinkRenderer()->makeKnownLink(
1729 SpecialPage
::getTitleFor( 'Booksources', $num ),
1732 'class' => 'internal mw-magiclink-isbn',
1733 'title' => false // suppress title attribute
1742 * Make a free external link, given a user-supplied URL
1744 * @param string $url
1745 * @param int $numPostProto
1746 * The number of characters after the protocol.
1747 * @return string HTML
1750 public function makeFreeExternalLink( $url, $numPostProto ) {
1753 # The characters '<' and '>' (which were escaped by
1754 # removeHTMLtags()) should not be included in
1755 # URLs, per RFC 2396.
1756 # Make terminate a URL as well (bug T84937)
1759 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1764 $trail = substr( $url, $m2[0][1] ) . $trail;
1765 $url = substr( $url, 0, $m2[0][1] );
1768 # Move trailing punctuation to $trail
1770 # If there is no left bracket, then consider right brackets fair game too
1771 if ( strpos( $url, '(' ) === false ) {
1775 $urlRev = strrev( $url );
1776 $numSepChars = strspn( $urlRev, $sep );
1777 # Don't break a trailing HTML entity by moving the ; into $trail
1778 # This is in hot code, so use substr_compare to avoid having to
1779 # create a new string object for the comparison
1780 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1781 # more optimization: instead of running preg_match with a $
1782 # anchor, which can be slow, do the match on the reversed
1783 # string starting at the desired offset.
1784 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1785 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1789 if ( $numSepChars ) {
1790 $trail = substr( $url, -$numSepChars ) . $trail;
1791 $url = substr( $url, 0, -$numSepChars );
1794 # Verify that we still have a real URL after trail removal, and
1795 # not just lone protocol
1796 if ( strlen( $trail ) >= $numPostProto ) {
1797 return $url . $trail;
1800 $url = Sanitizer
::cleanUrl( $url );
1802 # Is this an external image?
1803 $text = $this->maybeMakeExternalImage( $url );
1804 if ( $text === false ) {
1805 # Not an image, make a link
1806 $text = Linker
::makeExternalLink( $url,
1807 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1809 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1810 # Register it in the output object...
1811 $this->mOutput
->addExternalLink( $url );
1813 return $text . $trail;
1817 * Parse headers and return html.
1820 * @param string $text
1822 * @deprecated since 1.34; should not be used outside parser class.
1824 public function doHeadings( $text ) {
1825 wfDeprecated( __METHOD__
, '1.34' );
1826 return $this->handleHeadings( $text );
1830 * Parse headers and return html
1832 * @param string $text
1835 private function handleHeadings( $text ) {
1836 for ( $i = 6; $i >= 1; --$i ) {
1837 $h = str_repeat( '=', $i );
1838 // Trim non-newline whitespace from headings
1839 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1840 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1846 * Replace single quotes with HTML markup
1849 * @param string $text
1851 * @return string The altered text
1852 * @deprecated since 1.34; should not be used outside parser class.
1854 public function doAllQuotes( $text ) {
1855 wfDeprecated( __METHOD__
, '1.34' );
1856 return $this->handleAllQuotes( $text );
1860 * Replace single quotes with HTML markup
1862 * @param string $text
1864 * @return string The altered text
1866 private function handleAllQuotes( $text ) {
1868 $lines = StringUtils
::explode( "\n", $text );
1869 foreach ( $lines as $line ) {
1870 $outtext .= $this->doQuotes( $line ) . "\n";
1872 $outtext = substr( $outtext, 0, -1 );
1877 * Helper function for doAllQuotes()
1879 * @param string $text
1884 public function doQuotes( $text ) {
1885 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1886 $countarr = count( $arr );
1887 if ( $countarr == 1 ) {
1891 // First, do some preliminary work. This may shift some apostrophes from
1892 // being mark-up to being text. It also counts the number of occurrences
1893 // of bold and italics mark-ups.
1896 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1897 $thislen = strlen( $arr[$i] );
1898 // If there are ever four apostrophes, assume the first is supposed to
1899 // be text, and the remaining three constitute mark-up for bold text.
1900 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1901 if ( $thislen == 4 ) {
1902 $arr[$i - 1] .= "'";
1905 } elseif ( $thislen > 5 ) {
1906 // If there are more than 5 apostrophes in a row, assume they're all
1907 // text except for the last 5.
1908 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1909 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1913 // Count the number of occurrences of bold and italics mark-ups.
1914 if ( $thislen == 2 ) {
1916 } elseif ( $thislen == 3 ) {
1918 } elseif ( $thislen == 5 ) {
1924 // If there is an odd number of both bold and italics, it is likely
1925 // that one of the bold ones was meant to be an apostrophe followed
1926 // by italics. Which one we cannot know for certain, but it is more
1927 // likely to be one that has a single-letter word before it.
1928 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1929 $firstsingleletterword = -1;
1930 $firstmultiletterword = -1;
1932 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1933 if ( strlen( $arr[$i] ) == 3 ) {
1934 $x1 = substr( $arr[$i - 1], -1 );
1935 $x2 = substr( $arr[$i - 1], -2, 1 );
1936 if ( $x1 === ' ' ) {
1937 if ( $firstspace == -1 ) {
1940 } elseif ( $x2 === ' ' ) {
1941 $firstsingleletterword = $i;
1942 // if $firstsingleletterword is set, we don't
1943 // look at the other options, so we can bail early.
1945 } elseif ( $firstmultiletterword == -1 ) {
1946 $firstmultiletterword = $i;
1951 // If there is a single-letter word, use it!
1952 if ( $firstsingleletterword > -1 ) {
1953 $arr[$firstsingleletterword] = "''";
1954 $arr[$firstsingleletterword - 1] .= "'";
1955 } elseif ( $firstmultiletterword > -1 ) {
1956 // If not, but there's a multi-letter word, use that one.
1957 $arr[$firstmultiletterword] = "''";
1958 $arr[$firstmultiletterword - 1] .= "'";
1959 } elseif ( $firstspace > -1 ) {
1960 // ... otherwise use the first one that has neither.
1961 // (notice that it is possible for all three to be -1 if, for example,
1962 // there is only one pentuple-apostrophe in the line)
1963 $arr[$firstspace] = "''";
1964 $arr[$firstspace - 1] .= "'";
1968 // Now let's actually convert our apostrophic mush to HTML!
1973 foreach ( $arr as $r ) {
1974 if ( ( $i %
2 ) == 0 ) {
1975 if ( $state === 'both' ) {
1981 $thislen = strlen( $r );
1982 if ( $thislen == 2 ) {
1983 if ( $state === 'i' ) {
1986 } elseif ( $state === 'bi' ) {
1989 } elseif ( $state === 'ib' ) {
1990 $output .= '</b></i><b>';
1992 } elseif ( $state === 'both' ) {
1993 $output .= '<b><i>' . $buffer . '</i>';
1995 } else { // $state can be 'b' or ''
1999 } elseif ( $thislen == 3 ) {
2000 if ( $state === 'b' ) {
2003 } elseif ( $state === 'bi' ) {
2004 $output .= '</i></b><i>';
2006 } elseif ( $state === 'ib' ) {
2009 } elseif ( $state === 'both' ) {
2010 $output .= '<i><b>' . $buffer . '</b>';
2012 } else { // $state can be 'i' or ''
2016 } elseif ( $thislen == 5 ) {
2017 if ( $state === 'b' ) {
2018 $output .= '</b><i>';
2020 } elseif ( $state === 'i' ) {
2021 $output .= '</i><b>';
2023 } elseif ( $state === 'bi' ) {
2024 $output .= '</i></b>';
2026 } elseif ( $state === 'ib' ) {
2027 $output .= '</b></i>';
2029 } elseif ( $state === 'both' ) {
2030 $output .= '<i><b>' . $buffer . '</b></i>';
2032 } else { // ($state == '')
2040 // Now close all remaining tags. Notice that the order is important.
2041 if ( $state === 'b' ||
$state === 'ib' ) {
2044 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
2047 if ( $state === 'bi' ) {
2050 // There might be lonely ''''', so make sure we have a buffer
2051 if ( $state === 'both' && $buffer ) {
2052 $output .= '<b><i>' . $buffer . '</i></b>';
2058 * Replace external links (REL)
2060 * Note: this is all very hackish and the order of execution matters a lot.
2061 * Make sure to run tests/parser/parserTests.php if you change this code.
2065 * @param string $text
2067 * @throws MWException
2070 public function replaceExternalLinks( $text ) {
2071 wfDeprecated( __METHOD__
, '1.34' );
2072 return $this->handleExternalLinks( $text );
2076 * Replace external links (REL)
2078 * Note: this is all very hackish and the order of execution matters a lot.
2079 * Make sure to run tests/parser/parserTests.php if you change this code.
2081 * @param string $text
2082 * @throws MWException
2085 private function handleExternalLinks( $text ) {
2086 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
2087 // @phan-suppress-next-line PhanTypeComparisonFromArray See phan issue #3161
2088 if ( $bits === false ) {
2089 throw new MWException( "PCRE needs to be compiled with "
2090 . "--enable-unicode-properties in order for MediaWiki to function" );
2092 $s = array_shift( $bits );
2095 while ( $i < count( $bits ) ) {
2098 $text = $bits[$i++
];
2099 $trail = $bits[$i++
];
2101 # The characters '<' and '>' (which were escaped by
2102 # removeHTMLtags()) should not be included in
2103 # URLs, per RFC 2396.
2105 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
2106 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
2107 $url = substr( $url, 0, $m2[0][1] );
2110 # If the link text is an image URL, replace it with an <img> tag
2111 # This happened by accident in the original parser, but some people used it extensively
2112 $img = $this->maybeMakeExternalImage( $text );
2113 if ( $img !== false ) {
2119 # Set linktype for CSS
2122 # No link text, e.g. [http://domain.tld/some.link]
2123 if ( $text == '' ) {
2125 $langObj = $this->getTargetLanguage();
2126 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
2127 $linktype = 'autonumber';
2129 # Have link text, e.g. [http://domain.tld/some.link text]s
2131 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
2134 // Excluding protocol-relative URLs may avoid many false positives.
2135 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
2136 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
2139 $url = Sanitizer
::cleanUrl( $url );
2141 # Use the encoded URL
2142 # This means that users can paste URLs directly into the text
2143 # Funny characters like ö aren't valid in URLs anyway
2144 # This was changed in August 2004
2145 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
2146 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
2148 # Register link in the output object.
2149 $this->mOutput
->addExternalLink( $url );
2156 * Get the rel attribute for a particular external link.
2160 * @param string|bool $url Optional URL, to extract the domain from for rel =>
2161 * nofollow if appropriate
2162 * @param LinkTarget|null $title Optional LinkTarget, for wgNoFollowNsExceptions lookups
2163 * @return string|null Rel attribute for $url
2165 public static function getExternalLinkRel( $url = false, $title = null ) {
2166 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
2167 $ns = $title ?
$title->getNamespace() : false;
2168 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
2169 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
2177 * Get an associative array of additional HTML attributes appropriate for a
2178 * particular external link. This currently may include rel => nofollow
2179 * (depending on configuration, namespace, and the URL's domain) and/or a
2180 * target attribute (depending on configuration).
2183 * @param string $url URL to extract the domain from for rel =>
2184 * nofollow if appropriate
2185 * @return array Associative array of HTML attributes
2187 public function getExternalLinkAttribs( $url ) {
2189 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
2191 $target = $this->mOptions
->getExternalLinkTarget();
2193 $attribs['target'] = $target;
2194 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
2195 // T133507. New windows can navigate parent cross-origin.
2196 // Including noreferrer due to lacking browser
2197 // support of noopener. Eventually noreferrer should be removed.
2198 if ( $rel !== '' ) {
2201 $rel .= 'noreferrer noopener';
2204 $attribs['rel'] = $rel;
2209 * Replace unusual escape codes in a URL with their equivalent characters
2211 * This generally follows the syntax defined in RFC 3986, with special
2212 * consideration for HTTP query strings.
2215 * @param string $url
2218 public static function normalizeLinkUrl( $url ) {
2219 # Test for RFC 3986 IPv6 syntax
2220 $scheme = '[a-z][a-z0-9+.-]*:';
2221 $userinfo = '(?:[a-z0-9\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*';
2222 $ipv6Host = '\\[((?:[0-9a-f:]|%3[0-A]|%[46][1-6])+)\\]';
2223 if ( preg_match( "<^(?:{$scheme})?//(?:{$userinfo}@)?{$ipv6Host}(?:[:/?#].*|)$>i", $url, $m ) &&
2224 IP
::isValid( rawurldecode( $m[1] ) )
2226 $isIPv6 = rawurldecode( $m[1] );
2231 # Make sure unsafe characters are encoded
2232 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2234 return rawurlencode( $m[0] );
2240 $end = strlen( $url );
2242 # Fragment part - 'fragment'
2243 $start = strpos( $url, '#' );
2244 if ( $start !== false && $start < $end ) {
2245 $ret = self
::normalizeUrlComponent(
2246 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2250 # Query part - 'query' minus &=+;
2251 $start = strpos( $url, '?' );
2252 if ( $start !== false && $start < $end ) {
2253 $ret = self
::normalizeUrlComponent(
2254 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2258 # Scheme and path part - 'pchar'
2259 # (we assume no userinfo or encoded colons in the host)
2260 $ret = self
::normalizeUrlComponent(
2261 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2264 if ( $isIPv6 !== false ) {
2265 $ipv6Host = "%5B({$isIPv6})%5D";
2266 $ret = preg_replace(
2267 "<^((?:{$scheme})?//(?:{$userinfo}@)?){$ipv6Host}(?=[:/?#]|$)>i",
2276 private static function normalizeUrlComponent( $component, $unsafe ) {
2277 $callback = function ( $matches ) use ( $unsafe ) {
2278 $char = urldecode( $matches[0] );
2279 $ord = ord( $char );
2280 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2284 # Leave it escaped, but use uppercase for a-f
2285 return strtoupper( $matches[0] );
2288 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2292 * make an image if it's allowed, either through the global
2293 * option, through the exception, or through the on-wiki whitelist
2295 * @param string $url
2299 private function maybeMakeExternalImage( $url ) {
2300 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2301 $imagesexception = !empty( $imagesfrom );
2303 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2304 if ( $imagesexception && is_array( $imagesfrom ) ) {
2305 $imagematch = false;
2306 foreach ( $imagesfrom as $match ) {
2307 if ( strpos( $url, $match ) === 0 ) {
2312 } elseif ( $imagesexception ) {
2313 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2315 $imagematch = false;
2318 if ( $this->mOptions
->getAllowExternalImages()
2319 ||
( $imagesexception && $imagematch )
2321 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2323 $text = Linker
::makeExternalImage( $url );
2326 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2327 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2329 $whitelist = explode(
2331 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2334 foreach ( $whitelist as $entry ) {
2335 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2336 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2339 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2340 # Image matches a whitelist entry
2341 $text = Linker
::makeExternalImage( $url );
2350 * Process [[ ]] wikilinks
2352 * @param string $text
2354 * @return string Processed text
2357 * @deprecated since 1.34; should not be used outside parser class.
2359 public function replaceInternalLinks( $text ) {
2360 wfDeprecated( __METHOD__
, '1.34' );
2361 return $this->handleInternalLinks( $text );
2365 * Process [[ ]] wikilinks
2367 * @param string $text
2369 * @return string Processed text
2371 private function handleInternalLinks( $text ) {
2372 $this->mLinkHolders
->merge( $this->handleInternalLinks2( $text ) );
2377 * Process [[ ]] wikilinks (RIL)
2378 * @param string &$text
2379 * @throws MWException
2380 * @return LinkHolderArray
2383 * @deprecated since 1.34; should not be used outside parser class.
2385 public function replaceInternalLinks2( &$text ) {
2386 wfDeprecated( __METHOD__
, '1.34' );
2387 return $this->handleInternalLinks2( $text );
2391 * Process [[ ]] wikilinks (RIL)
2393 * @throws MWException
2394 * @return LinkHolderArray
2396 private function handleInternalLinks2( &$s ) {
2397 static $tc = false, $e1, $e1_img;
2398 # the % is needed to support urlencoded titles as well
2400 $tc = Title
::legalChars() . '#%';
2401 # Match a link having the form [[namespace:link|alternate]]trail
2402 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2403 # Match cases where there is no "]]", which might still be images
2404 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2407 $holders = new LinkHolderArray( $this );
2409 # split the entire text string on occurrences of [[
2410 $a = StringUtils
::explode( '[[', ' ' . $s );
2411 # get the first element (all text up to first [[), and remove the space we added
2414 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2415 $s = substr( $s, 1 );
2417 if ( is_null( $this->mTitle
) ) {
2418 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2420 $nottalk = !$this->mTitle
->isTalkPage();
2422 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2424 if ( $useLinkPrefixExtension ) {
2425 # Match the end of a line for a word that's not followed by whitespace,
2426 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2427 $charset = $this->contLang
->linkPrefixCharset();
2428 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2430 if ( preg_match( $e2, $s, $m ) ) {
2431 $first_prefix = $m[2];
2433 $first_prefix = false;
2439 # Some namespaces don't allow subpages
2440 $useSubpages = $this->nsInfo
->hasSubpages(
2441 $this->mTitle
->getNamespace()
2444 # Loop for each link
2445 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2446 # Check for excessive memory usage
2447 if ( $holders->isBig() ) {
2449 # Do the existence check, replace the link holders and clear the array
2450 $holders->replace( $s );
2454 if ( $useLinkPrefixExtension ) {
2455 if ( preg_match( $e2, $s, $m ) ) {
2456 list( , $s, $prefix ) = $m;
2461 if ( $first_prefix ) {
2462 $prefix = $first_prefix;
2463 $first_prefix = false;
2467 $might_be_img = false;
2469 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2471 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2472 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2473 # the real problem is with the $e1 regex
2475 # Still some problems for cases where the ] is meant to be outside punctuation,
2476 # and no image is in sight. See T4095.
2478 && substr( $m[3], 0, 1 ) === ']'
2479 && strpos( $text, '[' ) !== false
2481 $text .= ']'; # so that handleExternalLinks($text) works later
2482 $m[3] = substr( $m[3], 1 );
2484 # fix up urlencoded title texts
2485 if ( strpos( $m[1], '%' ) !== false ) {
2486 # Should anchors '#' also be rejected?
2487 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2490 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2491 # Invalid, but might be an image with a link in its caption
2492 $might_be_img = true;
2494 if ( strpos( $m[1], '%' ) !== false ) {
2495 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2498 } else { # Invalid form; output directly
2499 $s .= $prefix . '[[' . $line;
2503 $origLink = ltrim( $m[1], ' ' );
2505 # Don't allow internal links to pages containing
2506 # PROTO: where PROTO is a valid URL protocol; these
2507 # should be external links.
2508 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2509 $s .= $prefix . '[[' . $line;
2513 # Make subpage if necessary
2514 if ( $useSubpages ) {
2515 $link = Linker
::normalizeSubpageLink(
2516 $this->mTitle
, $origLink, $text
2522 // \x7f isn't a default legal title char, so most likely strip
2523 // markers will force us into the "invalid form" path above. But,
2524 // just in case, let's assert that xmlish tags aren't valid in
2525 // the title position.
2526 $unstrip = $this->mStripState
->killMarkers( $link );
2527 $noMarkers = ( $unstrip === $link );
2529 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2530 if ( $nt === null ) {
2531 $s .= $prefix . '[[' . $line;
2535 $ns = $nt->getNamespace();
2536 $iw = $nt->getInterwiki();
2538 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2540 if ( $might_be_img ) { # if this is actually an invalid link
2541 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2544 # look at the next 'line' to see if we can close it there
2546 $next_line = $a->current();
2547 if ( $next_line === false ||
$next_line === null ) {
2550 $m = explode( ']]', $next_line, 3 );
2551 if ( count( $m ) == 3 ) {
2552 # the first ]] closes the inner link, the second the image
2554 $text .= "[[{$m[0]}]]{$m[1]}";
2557 } elseif ( count( $m ) == 2 ) {
2558 # if there's exactly one ]] that's fine, we'll keep looking
2559 $text .= "[[{$m[0]}]]{$m[1]}";
2561 # if $next_line is invalid too, we need look no further
2562 $text .= '[[' . $next_line;
2567 # we couldn't find the end of this imageLink, so output it raw
2568 # but don't ignore what might be perfectly normal links in the text we've examined
2569 $holders->merge( $this->handleInternalLinks2( $text ) );
2570 $s .= "{$prefix}[[$link|$text";
2571 # note: no $trail, because without an end, there *is* no trail
2574 } else { # it's not an image, so output it raw
2575 $s .= "{$prefix}[[$link|$text";
2576 # note: no $trail, because without an end, there *is* no trail
2581 $wasblank = ( $text == '' );
2585 # Strip off leading ':'
2586 $text = substr( $text, 1 );
2589 # T6598 madness. Handle the quotes only if they come from the alternate part
2590 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2591 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2592 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2593 $text = $this->doQuotes( $text );
2596 # Link not escaped by : , create the various objects
2597 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2600 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2601 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2602 in_array( $iw, $this->svcOptions
->get( 'ExtraInterlanguageLinkPrefixes' ) )
2605 # T26502: filter duplicates
2606 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2607 $this->mLangLinkLanguages
[$iw] = true;
2608 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2612 * Strip the whitespace interwiki links produce, see T10897
2614 $s = rtrim( $s . $prefix ) . $trail; # T175416
2618 if ( $ns == NS_FILE
) {
2619 if ( !$this->badFileLookup
->isBadFile( $nt->getDBkey(), $this->mTitle
) ) {
2621 # if no parameters were passed, $text
2622 # becomes something like "File:Foo.png",
2623 # which we don't want to pass on to the
2627 # recursively parse links inside the image caption
2628 # actually, this will parse them in any other parameters, too,
2629 # but it might be hard to fix that, and it doesn't matter ATM
2630 $text = $this->handleExternalLinks( $text );
2631 $holders->merge( $this->handleInternalLinks2( $text ) );
2633 # cloak any absolute URLs inside the image markup, so handleExternalLinks() won't touch them
2634 $s .= $prefix . $this->armorLinks(
2635 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2638 } elseif ( $ns == NS_CATEGORY
) {
2640 * Strip the whitespace Category links produce, see T2087
2642 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2645 $sortkey = $this->getDefaultSort();
2649 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2650 $sortkey = str_replace( "\n", '', $sortkey );
2651 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2652 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2658 # Self-link checking. For some languages, variants of the title are checked in
2659 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2660 # for linking to a different variant.
2661 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2662 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2666 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2667 # @todo FIXME: Should do batch file existence checks, see comment below
2668 if ( $ns == NS_MEDIA
) {
2669 # Give extensions a chance to select the file revision for us
2672 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2673 [ $this, $nt, &$options, &$descQuery ] );
2674 # Fetch and register the file (file title may be different via hooks)
2675 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2676 # Cloak with NOPARSE to avoid replacement in handleExternalLinks
2677 $s .= $prefix . $this->armorLinks(
2678 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2682 # Some titles, such as valid special pages or files in foreign repos, should
2683 # be shown as bluelinks even though they're not included in the page table
2684 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2685 # batch file existence checks for NS_FILE and NS_MEDIA
2686 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2687 $this->mOutput
->addLink( $nt );
2688 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2690 # Links will be added to the output link list after checking
2691 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2698 * Render a forced-blue link inline; protect against double expansion of
2699 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2700 * Since this little disaster has to split off the trail text to avoid
2701 * breaking URLs in the following text without breaking trails on the
2702 * wiki links, it's been made into a horrible function.
2705 * @param string $text
2706 * @param string $trail
2707 * @param string $prefix
2708 * @return string HTML-wikitext mix oh yuck
2710 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2711 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2713 if ( $text == '' ) {
2714 $text = htmlspecialchars( $nt->getPrefixedText() );
2717 $link = $this->getLinkRenderer()->makeKnownLink(
2718 $nt, new HtmlArmor( "$prefix$text$inside" )
2721 return $this->armorLinks( $link ) . $trail;
2725 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2726 * going to go through further parsing steps before inline URL expansion.
2728 * Not needed quite as much as it used to be since free links are a bit
2729 * more sensible these days. But bracketed links are still an issue.
2731 * @param string $text More-or-less HTML
2732 * @return string Less-or-more HTML with NOPARSE bits
2734 public function armorLinks( $text ) {
2735 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2736 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2740 * Return true if subpage links should be expanded on this page.
2742 * @deprecated since 1.34; should not be used outside parser class.
2744 public function areSubpagesAllowed() {
2745 # Some namespaces don't allow subpages
2746 wfDeprecated( __METHOD__
, '1.34' );
2747 return $this->nsInfo
->hasSubpages( $this->mTitle
->getNamespace() );
2751 * Handle link to subpage if necessary
2753 * @param string $target The source of the link
2754 * @param string &$text The link text, modified as necessary
2755 * @return string The full name of the link
2757 * @deprecated since 1.34; should not be used outside parser class.
2759 public function maybeDoSubpageLink( $target, &$text ) {
2760 wfDeprecated( __METHOD__
, '1.34' );
2761 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2765 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2767 * @param string $text
2768 * @param bool $linestart Whether or not this is at the start of a line.
2770 * @return string The lists rendered as HTML
2772 public function doBlockLevels( $text, $linestart ) {
2773 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2777 * Return value of a magic variable (like PAGENAME)
2781 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2782 * @param bool|PPFrame $frame
2784 * @throws MWException
2786 * @deprecated since 1.34; should not be used outside parser class.
2788 public function getVariableValue( $index, $frame = false ) {
2789 wfDeprecated( __METHOD__
, '1.34' );
2790 return $this->expandMagicVariable( $index, $frame );
2794 * Return value of a magic variable (like PAGENAME)
2796 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2797 * @param bool|PPFrame $frame
2799 * @throws MWException
2802 private function expandMagicVariable( $index, $frame = false ) {
2803 // XXX This function should be moved out of Parser class for
2804 // reuse by Parsoid/etc.
2805 if ( is_null( $this->mTitle
) ) {
2806 // If no title set, bad things are going to happen
2807 // later. Title should always be set since this
2808 // should only be called in the middle of a parse
2809 // operation (but the unit-tests do funky stuff)
2810 throw new MWException( __METHOD__
. ' Should only be '
2811 . ' called while parsing (no title set)' );
2814 // Avoid PHP 7.1 warning from passing $this by reference
2818 * Some of these require message or data lookups and can be
2819 * expensive to check many times.
2822 Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) &&
2823 isset( $this->mVarCache
[$index] )
2825 return $this->mVarCache
[$index];
2828 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2829 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2831 $pageLang = $this->getFunctionLang();
2837 case 'currentmonth':
2838 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2840 case 'currentmonth1':
2841 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2843 case 'currentmonthname':
2844 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2846 case 'currentmonthnamegen':
2847 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2849 case 'currentmonthabbrev':
2850 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2853 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2856 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2859 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2862 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2864 case 'localmonthname':
2865 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2867 case 'localmonthnamegen':
2868 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2870 case 'localmonthabbrev':
2871 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2874 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2877 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2880 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2883 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2885 case 'fullpagename':
2886 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2888 case 'fullpagenamee':
2889 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2892 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2894 case 'subpagenamee':
2895 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2897 case 'rootpagename':
2898 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2900 case 'rootpagenamee':
2901 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2904 $this->mTitle
->getRootText()
2907 case 'basepagename':
2908 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2910 case 'basepagenamee':
2911 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2914 $this->mTitle
->getBaseText()
2917 case 'talkpagename':
2918 if ( $this->mTitle
->canHaveTalkPage() ) {
2919 $talkPage = $this->mTitle
->getTalkPage();
2920 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2925 case 'talkpagenamee':
2926 if ( $this->mTitle
->canHaveTalkPage() ) {
2927 $talkPage = $this->mTitle
->getTalkPage();
2928 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2933 case 'subjectpagename':
2934 $subjPage = $this->mTitle
->getSubjectPage();
2935 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2937 case 'subjectpagenamee':
2938 $subjPage = $this->mTitle
->getSubjectPage();
2939 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2941 case 'pageid': // requested in T25427
2942 # Inform the edit saving system that getting the canonical output
2943 # after page insertion requires a parse that used that exact page ID
2944 $this->setOutputFlag( 'vary-page-id', '{{PAGEID}} used' );
2945 $value = $this->mTitle
->getArticleID();
2947 $value = $this->mOptions
->getSpeculativePageId();
2949 $this->mOutput
->setSpeculativePageIdUsed( $value );
2955 $this->svcOptions
->get( 'MiserMode' ) &&
2956 !$this->mOptions
->getInterfaceMessage() &&
2957 // @TODO: disallow this word on all namespaces
2958 $this->nsInfo
->isContent( $this->mTitle
->getNamespace() )
2960 // Use a stub result instead of the actual revision ID in order to avoid
2961 // double parses on page save but still allow preview detection (T137900)
2962 if ( $this->getRevisionId() ||
$this->mOptions
->getSpeculativeRevId() ) {
2965 $this->setOutputFlag( 'vary-revision-exists', '{{REVISIONID}} used' );
2969 # Inform the edit saving system that getting the canonical output after
2970 # revision insertion requires a parse that used that exact revision ID
2971 $this->setOutputFlag( 'vary-revision-id', '{{REVISIONID}} used' );
2972 $value = $this->getRevisionId();
2973 if ( $value === 0 ) {
2974 $rev = $this->getRevisionObject();
2975 $value = $rev ?
$rev->getId() : $value;
2978 $value = $this->mOptions
->getSpeculativeRevId();
2980 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2986 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2988 case 'revisionday2':
2989 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2991 case 'revisionmonth':
2992 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2994 case 'revisionmonth1':
2995 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2997 case 'revisionyear':
2998 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
3000 case 'revisiontimestamp':
3001 $value = $this->getRevisionTimestampSubstring( 0, 14, self
::MAX_TTS
, $index );
3003 case 'revisionuser':
3004 # Inform the edit saving system that getting the canonical output after
3005 # revision insertion requires a parse that used the actual user ID
3006 $this->setOutputFlag( 'vary-user', '{{REVISIONUSER}} used' );
3007 $value = $this->getRevisionUser();
3009 case 'revisionsize':
3010 $value = $this->getRevisionSize();
3013 $value = str_replace( '_', ' ',
3014 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
3017 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
3019 case 'namespacenumber':
3020 $value = $this->mTitle
->getNamespace();
3023 $value = $this->mTitle
->canHaveTalkPage()
3024 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3028 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3030 case 'subjectspace':
3031 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3033 case 'subjectspacee':
3034 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3036 case 'currentdayname':
3037 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3040 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3043 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3046 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3049 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
3050 # int to remove the padding
3051 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3054 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3056 case 'localdayname':
3057 $value = $pageLang->getWeekdayName(
3058 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3062 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3065 $value = $pageLang->time(
3066 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3072 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3075 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
3076 # int to remove the padding
3077 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3080 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3082 case 'numberofarticles':
3083 $value = $pageLang->formatNum( SiteStats
::articles() );
3085 case 'numberoffiles':
3086 $value = $pageLang->formatNum( SiteStats
::images() );
3088 case 'numberofusers':
3089 $value = $pageLang->formatNum( SiteStats
::users() );
3091 case 'numberofactiveusers':
3092 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3094 case 'numberofpages':
3095 $value = $pageLang->formatNum( SiteStats
::pages() );
3097 case 'numberofadmins':
3098 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3100 case 'numberofedits':
3101 $value = $pageLang->formatNum( SiteStats
::edits() );
3103 case 'currenttimestamp':
3104 $value = wfTimestamp( TS_MW
, $ts );
3106 case 'localtimestamp':
3107 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3109 case 'currentversion':
3110 $value = SpecialVersion
::getVersion();
3113 return $this->svcOptions
->get( 'ArticlePath' );
3115 return $this->svcOptions
->get( 'Sitename' );
3117 return $this->svcOptions
->get( 'Server' );
3119 return $this->svcOptions
->get( 'ServerName' );
3121 return $this->svcOptions
->get( 'ScriptPath' );
3123 return $this->svcOptions
->get( 'StylePath' );
3124 case 'directionmark':
3125 return $pageLang->getDirMark();
3126 case 'contentlanguage':
3127 return $this->svcOptions
->get( 'LanguageCode' );
3128 case 'pagelanguage':
3129 $value = $pageLang->getCode();
3131 case 'cascadingsources':
3132 $value = CoreParserFunctions
::cascadingsources( $this );
3137 'ParserGetVariableValueSwitch',
3138 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
3145 $this->mVarCache
[$index] = $value;
3154 * @param int $mtts Max time-till-save; sets vary-revision-timestamp if result changes by then
3155 * @param string $variable Parser variable name
3158 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
3159 # Get the timezone-adjusted timestamp to be used for this revision
3160 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
3161 # Possibly set vary-revision if there is not yet an associated revision
3162 if ( !$this->getRevisionObject() ) {
3163 # Get the timezone-adjusted timestamp $mtts seconds in the future.
3164 # This future is relative to the current time and not that of the
3165 # parser options. The rendered timestamp can be compared to that
3166 # of the timestamp specified by the parser options.
3168 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
3173 if ( $resNow !== $resThen ) {
3174 # Inform the edit saving system that getting the canonical output after
3175 # revision insertion requires a parse that used an actual revision timestamp
3176 $this->setOutputFlag( 'vary-revision-timestamp', "$variable used" );
3184 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3187 * @deprecated since 1.34; should not be used outside parser class.
3189 public function initialiseVariables() {
3190 wfDeprecated( __METHOD__
, '1.34' );
3191 $this->initializeVariables();
3195 * Initialize the magic variables (like CURRENTMONTHNAME) and
3196 * substitution modifiers.
3198 private function initializeVariables() {
3199 $variableIDs = $this->magicWordFactory
->getVariableIDs();
3200 $substIDs = $this->magicWordFactory
->getSubstIDs();
3202 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
3203 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
3207 * Preprocess some wikitext and return the document tree.
3208 * This is the ghost of replace_variables().
3210 * @param string $text The text to parse
3211 * @param int $flags Bitwise combination of:
3212 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3213 * included. Default is to assume a direct page view.
3215 * The generated DOM tree must depend only on the input text and the flags.
3216 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
3218 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3219 * change in the DOM tree for a given text, must be passed through the section identifier
3220 * in the section edit link and thus back to extractSections().
3222 * The output of this function is currently only cached in process memory, but a persistent
3223 * cache may be implemented at a later date which takes further advantage of these strict
3224 * dependency requirements.
3228 public function preprocessToDom( $text, $flags = 0 ) {
3229 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3234 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3239 * @deprecated since 1.34; appears to be unused.
3241 public static function splitWhitespace( $s ) {
3242 wfDeprecated( __METHOD__
, '1.34' );
3243 $ltrimmed = ltrim( $s );
3244 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3245 $trimmed = rtrim( $ltrimmed );
3246 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3248 $w2 = substr( $ltrimmed, -$diff );
3252 return [ $w1, $trimmed, $w2 ];
3256 * Replace magic variables, templates, and template arguments
3257 * with the appropriate text. Templates are substituted recursively,
3258 * taking care to avoid infinite loops.
3260 * Note that the substitution depends on value of $mOutputType:
3261 * self::OT_WIKI: only {{subst:}} templates
3262 * self::OT_PREPROCESS: templates but not extension tags
3263 * self::OT_HTML: all templates and extension tags
3265 * @param string $text The text to transform
3266 * @param false|PPFrame|array $frame Object describing the arguments passed to the
3267 * template. Arguments may also be provided as an associative array, as
3268 * was the usual case before MW1.12. Providing arguments this way may be
3269 * useful for extensions wishing to perform variable replacement
3271 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3272 * double-brace expansion.
3275 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3276 # Is there any text? Also, Prevent too big inclusions!
3277 $textSize = strlen( $text );
3278 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3282 if ( $frame === false ) {
3283 $frame = $this->getPreprocessor()->newFrame();
3284 } elseif ( !( $frame instanceof PPFrame
) ) {
3285 $this->logger
->debug(
3286 __METHOD__
. " called using plain parameters instead of " .
3287 "a PPFrame instance. Creating custom frame."
3289 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3292 $dom = $this->preprocessToDom( $text );
3293 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3294 $text = $frame->expand( $dom, $flags );
3300 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3302 * @param array $args
3305 * @deprecated since 1.34; appears to be unused in core.
3307 public static function createAssocArgs( $args ) {
3308 wfDeprecated( __METHOD__
, '1.34' );
3311 foreach ( $args as $arg ) {
3312 $eqpos = strpos( $arg, '=' );
3313 if ( $eqpos === false ) {
3314 $assocArgs[$index++
] = $arg;
3316 $name = trim( substr( $arg, 0, $eqpos ) );
3317 $value = trim( substr( $arg, $eqpos +
1 ) );
3318 if ( $value === false ) {
3321 if ( $name !== false ) {
3322 $assocArgs[$name] = $value;
3331 * Warn the user when a parser limitation is reached
3332 * Will warn at most once the user per limitation type
3334 * The results are shown during preview and run through the Parser (See EditPage.php)
3336 * @param string $limitationType Should be one of:
3337 * 'expensive-parserfunction' (corresponding messages:
3338 * 'expensive-parserfunction-warning',
3339 * 'expensive-parserfunction-category')
3340 * 'post-expand-template-argument' (corresponding messages:
3341 * 'post-expand-template-argument-warning',
3342 * 'post-expand-template-argument-category')
3343 * 'post-expand-template-inclusion' (corresponding messages:
3344 * 'post-expand-template-inclusion-warning',
3345 * 'post-expand-template-inclusion-category')
3346 * 'node-count-exceeded' (corresponding messages:
3347 * 'node-count-exceeded-warning',
3348 * 'node-count-exceeded-category')
3349 * 'expansion-depth-exceeded' (corresponding messages:
3350 * 'expansion-depth-exceeded-warning',
3351 * 'expansion-depth-exceeded-category')
3352 * @param string|int|null $current Current value
3353 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3354 * exceeded, provide the values (optional)
3356 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3357 # does no harm if $current and $max are present but are unnecessary for the message
3358 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3359 # only during preview, and that would split the parser cache unnecessarily.
3360 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3362 $this->mOutput
->addWarning( $warning );
3363 $this->addTrackingCategory( "$limitationType-category" );
3367 * Return the text of a template, after recursively
3368 * replacing any variables or templates within the template.
3370 * @param array $piece The parts of the template
3371 * $piece['title']: the title, i.e. the part before the |
3372 * $piece['parts']: the parameter array
3373 * $piece['lineStart']: whether the brace was at the start of a line
3374 * @param PPFrame $frame The current frame, contains template arguments
3376 * @return string|array The text of the template
3379 public function braceSubstitution( $piece, $frame ) {
3382 // $text has been filled
3384 // wiki markup in $text should be escaped
3386 // $text is HTML, armour it against wikitext transformation
3388 // Force interwiki transclusion to be done in raw mode not rendered
3389 $forceRawInterwiki = false;
3390 // $text is a DOM node needing expansion in a child frame
3391 $isChildObj = false;
3392 // $text is a DOM node needing expansion in the current frame
3393 $isLocalObj = false;
3395 # Title object, where $text came from
3398 # $part1 is the bit before the first |, and must contain only title characters.
3399 # Various prefixes will be stripped from it later.
3400 $titleWithSpaces = $frame->expand( $piece['title'] );
3401 $part1 = trim( $titleWithSpaces );
3404 # Original title text preserved for various purposes
3405 $originalTitle = $part1;
3407 # $args is a list of argument nodes, starting from index 0, not including $part1
3408 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3409 # below won't work b/c this $args isn't an object
3410 $args = ( $piece['parts'] == null ) ?
[] : $piece['parts'];
3412 $profileSection = null; // profile templates
3416 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3418 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3419 # Decide whether to expand template or keep wikitext as-is.
3420 if ( $this->ot
['wiki'] ) {
3421 if ( $substMatch === false ) {
3422 $literal = true; # literal when in PST with no prefix
3424 $literal = false; # expand when in PST with subst: or safesubst:
3427 if ( $substMatch == 'subst' ) {
3428 $literal = true; # literal when not in PST with plain subst:
3430 $literal = false; # expand when not in PST with safesubst: or no prefix
3434 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3441 if ( !$found && $args->getLength() == 0 ) {
3442 $id = $this->mVariables
->matchStartToEnd( $part1 );
3443 if ( $id !== false ) {
3444 $text = $this->expandMagicVariable( $id, $frame );
3445 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3446 $this->mOutput
->updateCacheExpiry(
3447 $this->magicWordFactory
->getCacheTTL( $id ) );
3453 # MSG, MSGNW and RAW
3456 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3457 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3460 # Remove obsolete MSG:
3461 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3462 $mwMsg->matchStartAndRemove( $part1 );
3466 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3467 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3468 $forceRawInterwiki = true;
3474 $colonPos = strpos( $part1, ':' );
3475 if ( $colonPos !== false ) {
3476 $func = substr( $part1, 0, $colonPos );
3477 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3478 $argsLength = $args->getLength();
3479 for ( $i = 0; $i < $argsLength; $i++
) {
3480 $funcArgs[] = $args->item( $i );
3483 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3485 // Extract any forwarded flags
3486 if ( isset( $result['title'] ) ) {
3487 $title = $result['title'];
3489 if ( isset( $result['found'] ) ) {
3490 $found = $result['found'];
3492 if ( array_key_exists( 'text', $result ) ) {
3494 $text = $result['text'];
3496 if ( isset( $result['nowiki'] ) ) {
3497 $nowiki = $result['nowiki'];
3499 if ( isset( $result['isHTML'] ) ) {
3500 $isHTML = $result['isHTML'];
3502 if ( isset( $result['forceRawInterwiki'] ) ) {
3503 $forceRawInterwiki = $result['forceRawInterwiki'];
3505 if ( isset( $result['isChildObj'] ) ) {
3506 $isChildObj = $result['isChildObj'];
3508 if ( isset( $result['isLocalObj'] ) ) {
3509 $isLocalObj = $result['isLocalObj'];
3514 # Finish mangling title and then check for loops.
3515 # Set $title to a Title object and $titleText to the PDBK
3518 # Split the title into page and subpage
3520 $relative = Linker
::normalizeSubpageLink(
3521 $this->mTitle
, $part1, $subpage
3523 if ( $part1 !== $relative ) {
3525 $ns = $this->mTitle
->getNamespace();
3527 $title = Title
::newFromText( $part1, $ns );
3529 $titleText = $title->getPrefixedText();
3530 # Check for language variants if the template is not found
3531 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3532 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3534 # Do recursion depth check
3535 $limit = $this->mOptions
->getMaxTemplateDepth();
3536 if ( $frame->depth
>= $limit ) {
3538 $text = '<span class="error">'
3539 . wfMessage( 'parser-template-recursion-depth-warning' )
3540 ->numParams( $limit )->inContentLanguage()->text()
3546 # Load from database
3547 if ( !$found && $title ) {
3548 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3549 if ( !$title->isExternal() ) {
3550 if ( $title->isSpecialPage()
3551 && $this->mOptions
->getAllowSpecialInclusion()
3552 && $this->ot
['html']
3554 $specialPage = $this->specialPageFactory
->getPage( $title->getDBkey() );
3555 // Pass the template arguments as URL parameters.
3556 // "uselang" will have no effect since the Language object
3557 // is forced to the one defined in ParserOptions.
3559 $argsLength = $args->getLength();
3560 for ( $i = 0; $i < $argsLength; $i++
) {
3561 $bits = $args->item( $i )->splitArg();
3562 if ( strval( $bits['index'] ) === '' ) {
3563 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3564 $value = trim( $frame->expand( $bits['value'] ) );
3565 $pageArgs[$name] = $value;
3569 // Create a new context to execute the special page
3570 $context = new RequestContext
;
3571 $context->setTitle( $title );
3572 $context->setRequest( new FauxRequest( $pageArgs ) );
3573 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3574 $context->setUser( $this->getUser() );
3576 // If this page is cached, then we better not be per user.
3577 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3579 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3580 $ret = $this->specialPageFactory
->capturePath( $title, $context, $this->getLinkRenderer() );
3582 $text = $context->getOutput()->getHTML();
3583 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3586 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3587 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3588 $specialPage->maxIncludeCacheTime()
3592 } elseif ( $this->nsInfo
->isNonincludable( $title->getNamespace() ) ) {
3593 $found = false; # access denied
3594 $this->logger
->debug(
3596 ": template inclusion denied for " . $title->getPrefixedDBkey()
3599 list( $text, $title ) = $this->getTemplateDom( $title );
3600 if ( $text !== false ) {
3606 # If the title is valid but undisplayable, make a link to it
3607 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3608 $text = "[[:$titleText]]";
3611 } elseif ( $title->isTrans() ) {
3612 # Interwiki transclusion
3613 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3614 $text = $this->interwikiTransclude( $title, 'render' );
3617 $text = $this->interwikiTransclude( $title, 'raw' );
3618 # Preprocess it like a template
3619 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3625 # Do infinite loop check
3626 # This has to be done after redirect resolution to avoid infinite loops via redirects
3627 if ( !$frame->loopCheck( $title ) ) {
3629 $text = '<span class="error">'
3630 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3632 $this->addTrackingCategory( 'template-loop-category' );
3633 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3634 wfEscapeWikiText( $titleText ) )->text() );
3635 $this->logger
->debug( __METHOD__
. ": template loop broken at '$titleText'" );
3639 # If we haven't found text to substitute by now, we're done
3640 # Recover the source wikitext and return it
3642 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3643 if ( $profileSection ) {
3644 $this->mProfiler
->scopedProfileOut( $profileSection );
3646 return [ 'object' => $text ];
3649 # Expand DOM-style return values in a child frame
3650 if ( $isChildObj ) {
3651 # Clean up argument array
3652 $newFrame = $frame->newChild( $args, $title );
3655 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3656 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3657 # Expansion is eligible for the empty-frame cache
3658 $text = $newFrame->cachedExpand( $titleText, $text );
3660 # Uncached expansion
3661 $text = $newFrame->expand( $text );
3664 if ( $isLocalObj && $nowiki ) {
3665 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3666 $isLocalObj = false;
3669 if ( $profileSection ) {
3670 $this->mProfiler
->scopedProfileOut( $profileSection );
3673 # Replace raw HTML by a placeholder
3675 $text = $this->insertStripItem( $text );
3676 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3677 # Escape nowiki-style return values
3678 $text = wfEscapeWikiText( $text );
3679 } elseif ( is_string( $text )
3680 && !$piece['lineStart']
3681 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3683 # T2529: if the template begins with a table or block-level
3684 # element, it should be treated as beginning a new line.
3685 # This behavior is somewhat controversial.
3686 $text = "\n" . $text;
3689 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3690 # Error, oversize inclusion
3691 if ( $titleText !== false ) {
3692 # Make a working, properly escaped link if possible (T25588)
3693 $text = "[[:$titleText]]";
3695 # This will probably not be a working link, but at least it may
3696 # provide some hint of where the problem is
3697 preg_replace( '/^:/', '', $originalTitle );
3698 $text = "[[:$originalTitle]]";
3700 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3701 . 'post-expand include size too large -->' );
3702 $this->limitationWarn( 'post-expand-template-inclusion' );
3705 if ( $isLocalObj ) {
3706 $ret = [ 'object' => $text ];
3708 $ret = [ 'text' => $text ];
3715 * Call a parser function and return an array with text and flags.
3717 * The returned array will always contain a boolean 'found', indicating
3718 * whether the parser function was found or not. It may also contain the
3720 * text: string|object, resulting wikitext or PP DOM object
3721 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3722 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3723 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3724 * nowiki: bool, wiki markup in $text should be escaped
3727 * @param PPFrame $frame The current frame, contains template arguments
3728 * @param string $function Function name
3729 * @param array $args Arguments to the function
3730 * @throws MWException
3733 public function callParserFunction( $frame, $function, array $args = [] ) {
3734 # Case sensitive functions
3735 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3736 $function = $this->mFunctionSynonyms
[1][$function];
3738 # Case insensitive functions
3739 $function = $this->contLang
->lc( $function );
3740 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3741 $function = $this->mFunctionSynonyms
[0][$function];
3743 return [ 'found' => false ];
3747 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3749 // Avoid PHP 7.1 warning from passing $this by reference
3752 $allArgs = [ &$parser ];
3753 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3754 # Convert arguments to PPNodes and collect for appending to $allArgs
3756 foreach ( $args as $k => $v ) {
3757 if ( $v instanceof PPNode ||
$k === 0 ) {
3760 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3764 # Add a frame parameter, and pass the arguments as an array
3765 $allArgs[] = $frame;
3766 $allArgs[] = $funcArgs;
3768 # Convert arguments to plain text and append to $allArgs
3769 foreach ( $args as $k => $v ) {
3770 if ( $v instanceof PPNode
) {
3771 $allArgs[] = trim( $frame->expand( $v ) );
3772 } elseif ( is_int( $k ) && $k >= 0 ) {
3773 $allArgs[] = trim( $v );
3775 $allArgs[] = trim( "$k=$v" );
3780 $result = $callback( ...$allArgs );
3782 # The interface for function hooks allows them to return a wikitext
3783 # string or an array containing the string and any flags. This mungs
3784 # things around to match what this method should return.
3785 if ( !is_array( $result ) ) {
3791 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3792 $result['text'] = $result[0];
3794 unset( $result[0] );
3801 $preprocessFlags = 0;
3802 if ( isset( $result['noparse'] ) ) {
3803 $noparse = $result['noparse'];
3805 if ( isset( $result['preprocessFlags'] ) ) {
3806 $preprocessFlags = $result['preprocessFlags'];
3810 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3811 $result['isChildObj'] = true;
3818 * Get the semi-parsed DOM representation of a template with a given title,
3819 * and its redirect destination title. Cached.
3821 * @param Title $title
3825 public function getTemplateDom( $title ) {
3826 $cacheTitle = $title;
3827 $titleText = $title->getPrefixedDBkey();
3829 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3830 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3831 $title = Title
::makeTitle( $ns, $dbk );
3832 $titleText = $title->getPrefixedDBkey();
3834 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3835 return [ $this->mTplDomCache
[$titleText], $title ];
3838 # Cache miss, go to the database
3839 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3841 if ( $text === false ) {
3842 $this->mTplDomCache
[$titleText] = false;
3843 return [ false, $title ];
3846 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3847 $this->mTplDomCache
[$titleText] = $dom;
3849 if ( !$title->equals( $cacheTitle ) ) {
3850 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3851 [ $title->getNamespace(), $title->getDBkey() ];
3854 return [ $dom, $title ];
3858 * Fetch the current revision of a given title. Note that the revision
3859 * (and even the title) may not exist in the database, so everything
3860 * contributing to the output of the parser should use this method
3861 * where possible, rather than getting the revisions themselves. This
3862 * method also caches its results, so using it benefits performance.
3865 * @param Title $title
3868 public function fetchCurrentRevisionOfTitle( $title ) {
3869 $cacheKey = $title->getPrefixedDBkey();
3870 if ( !$this->currentRevisionCache
) {
3871 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3873 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3874 $this->currentRevisionCache
->set( $cacheKey,
3875 // Defaults to Parser::statelessFetchRevision()
3876 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3879 return $this->currentRevisionCache
->get( $cacheKey );
3883 * @param Title $title
3887 public function isCurrentRevisionOfTitleCached( $title ) {
3889 $this->currentRevisionCache
&&
3890 $this->currentRevisionCache
->has( $title->getPrefixedText() )
3895 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3896 * without passing them on to it.
3899 * @param Title $title
3900 * @param Parser|bool $parser
3901 * @return Revision|bool False if missing
3903 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3904 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3910 * Fetch the unparsed text of a template and register a reference to it.
3911 * @param Title $title
3912 * @return array ( string or false, Title )
3914 public function fetchTemplateAndTitle( $title ) {
3915 // Defaults to Parser::statelessFetchTemplate()
3916 $templateCb = $this->mOptions
->getTemplateCallback();
3917 $stuff = call_user_func( $templateCb, $title, $this );
3918 $rev = $stuff['revision'] ??
null;
3919 $text = $stuff['text'];
3920 if ( is_string( $stuff['text'] ) ) {
3921 // We use U+007F DELETE to distinguish strip markers from regular text
3922 $text = strtr( $text, "\x7f", "?" );
3924 $finalTitle = $stuff['finalTitle'] ??
$title;
3925 foreach ( ( $stuff['deps'] ??
[] ) as $dep ) {
3926 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3927 if ( $dep['title']->equals( $this->getTitle() ) && $rev instanceof Revision
) {
3928 // Self-transclusion; final result may change based on the new page version
3929 $this->setOutputFlag( 'vary-revision-sha1', 'Self transclusion' );
3930 $this->getOutput()->setRevisionUsedSha1Base36( $rev->getSha1() );
3934 return [ $text, $finalTitle ];
3938 * Fetch the unparsed text of a template and register a reference to it.
3939 * @param Title $title
3940 * @return string|bool
3942 public function fetchTemplate( $title ) {
3943 return $this->fetchTemplateAndTitle( $title )[0];
3947 * Static function to get a template
3948 * Can be overridden via ParserOptions::setTemplateCallback().
3950 * @param Title $title
3951 * @param bool|Parser $parser
3955 public static function statelessFetchTemplate( $title, $parser = false ) {
3956 $text = $skip = false;
3957 $finalTitle = $title;
3961 # Loop to fetch the article, with up to 1 redirect
3962 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3963 # Give extensions a chance to select the revision instead
3964 $id = false; # Assume current
3965 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3966 [ $parser, $title, &$skip, &$id ] );
3972 'page_id' => $title->getArticleID(),
3979 $rev = Revision
::newFromId( $id );
3980 } elseif ( $parser ) {
3981 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3983 $rev = Revision
::newFromTitle( $title );
3985 $rev_id = $rev ?
$rev->getId() : 0;
3986 # If there is no current revision, there is no page
3987 if ( $id === false && !$rev ) {
3988 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3989 $linkCache->addBadLinkObj( $title );
3994 'page_id' => $title->getArticleID(),
3997 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3998 # We fetched a rev from a different title; register it too...
4000 'title' => $rev->getTitle(),
4001 'page_id' => $rev->getPage(),
4007 $content = $rev->getContent();
4008 $text = $content ?
$content->getWikitextForTransclusion() : null;
4010 Hooks
::run( 'ParserFetchTemplate',
4011 [ $parser, $title, $rev, &$text, &$deps ] );
4013 if ( $text === false ||
$text === null ) {
4017 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4018 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
4019 lcfirst( $title->getText() ) )->inContentLanguage();
4020 if ( !$message->exists() ) {
4024 $content = $message->content();
4025 $text = $message->plain();
4033 $finalTitle = $title;
4034 $title = $content->getRedirectTarget();
4039 'finalTitle' => $finalTitle,
4045 * Fetch a file and its title and register a reference to it.
4046 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4047 * @param Title $title
4048 * @param array $options Array of options to RepoGroup::findFile
4049 * @return array ( File or false, Title of file )
4051 public function fetchFileAndTitle( $title, $options = [] ) {
4052 $file = $this->fetchFileNoRegister( $title, $options );
4054 $time = $file ?
$file->getTimestamp() : false;
4055 $sha1 = $file ?
$file->getSha1() : false;
4056 # Register the file as a dependency...
4057 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4058 if ( $file && !$title->equals( $file->getTitle() ) ) {
4059 # Update fetched file title
4060 $title = $file->getTitle();
4061 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4063 return [ $file, $title ];
4067 * Helper function for fetchFileAndTitle.
4069 * Also useful if you need to fetch a file but not use it yet,
4070 * for example to get the file's handler.
4072 * @param Title $title
4073 * @param array $options Array of options to RepoGroup::findFile
4076 protected function fetchFileNoRegister( $title, $options = [] ) {
4077 if ( isset( $options['broken'] ) ) {
4078 $file = false; // broken thumbnail forced by hook
4079 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4080 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4081 } else { // get by (name,timestamp)
4082 $file = MediaWikiServices
::getInstance()->getRepoGroup()->findFile( $title, $options );
4088 * Transclude an interwiki link.
4090 * @param Title $title
4091 * @param string $action Usually one of (raw, render)
4095 public function interwikiTransclude( $title, $action ) {
4096 if ( !$this->svcOptions
->get( 'EnableScaryTranscluding' ) ) {
4097 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4100 $url = $title->getFullURL( [ 'action' => $action ] );
4101 if ( strlen( $url ) > 1024 ) {
4102 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4105 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
4107 $fname = __METHOD__
;
4108 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
4110 $data = $cache->getWithSetCallback(
4111 $cache->makeGlobalKey(
4112 'interwiki-transclude',
4113 ( $wikiId !== false ) ?
$wikiId : 'external',
4116 $this->svcOptions
->get( 'TranscludeCacheExpiry' ),
4117 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
4118 $req = MWHttpRequest
::factory( $url, [], $fname );
4120 $status = $req->execute(); // Status object
4121 if ( !$status->isOK() ) {
4122 $ttl = $cache::TTL_UNCACHEABLE
;
4123 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
4124 $ttl = min( $cache::TTL_LAGGED
, $ttl );
4128 'text' => $status->isOK() ?
$req->getContent() : null,
4129 'code' => $req->getStatus()
4133 'checkKeys' => ( $wikiId !== false )
4134 ?
[ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
4136 'pcGroup' => 'interwiki-transclude:5',
4137 'pcTTL' => $cache::TTL_PROC_LONG
4141 if ( is_string( $data['text'] ) ) {
4142 $text = $data['text'];
4143 } elseif ( $data['code'] != 200 ) {
4144 // Though we failed to fetch the content, this status is useless.
4145 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
4146 ->params( $url, $data['code'] )->inContentLanguage()->text();
4148 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4155 * Triple brace replacement -- used for template arguments
4158 * @param array $piece
4159 * @param PPFrame $frame
4163 public function argSubstitution( $piece, $frame ) {
4165 $parts = $piece['parts'];
4166 $nameWithSpaces = $frame->expand( $piece['title'] );
4167 $argName = trim( $nameWithSpaces );
4169 $text = $frame->getArgument( $argName );
4170 if ( $text === false && $parts->getLength() > 0
4171 && ( $this->ot
['html']
4173 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4176 # No match in frame, use the supplied default
4177 $object = $parts->item( 0 )->getChildren();
4179 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4180 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4181 $this->limitationWarn( 'post-expand-template-argument' );
4184 if ( $text === false && $object === false ) {
4186 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4188 if ( $error !== false ) {
4191 if ( $object !== false ) {
4192 $ret = [ 'object' => $object ];
4194 $ret = [ 'text' => $text ];
4201 * Return the text to be used for a given extension tag.
4202 * This is the ghost of strip().
4204 * @param array $params Associative array of parameters:
4205 * name PPNode for the tag name
4206 * attr PPNode for unparsed text where tag attributes are thought to be
4207 * attributes Optional associative array of parsed attributes
4208 * inner Contents of extension element
4209 * noClose Original text did not have a close tag
4210 * @param PPFrame $frame
4212 * @throws MWException
4216 public function extensionSubstitution( $params, $frame ) {
4217 static $errorStr = '<span class="error">';
4218 static $errorLen = 20;
4220 $name = $frame->expand( $params['name'] );
4221 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
4222 // Probably expansion depth or node count exceeded. Just punt the
4227 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4228 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
4233 // We can't safely check if the expansion for $content resulted in an
4234 // error, because the content could happen to be the error string
4236 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4238 $marker = self
::MARKER_PREFIX
. "-$name-"
4239 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4241 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4242 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4243 if ( $isFunctionTag ) {
4244 $markerType = 'none';
4246 $markerType = 'general';
4248 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4249 $name = strtolower( $name );
4250 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4251 if ( isset( $params['attributes'] ) ) {
4252 $attributes +
= $params['attributes'];
4255 if ( isset( $this->mTagHooks
[$name] ) ) {
4256 $output = call_user_func_array( $this->mTagHooks
[$name],
4257 [ $content, $attributes, $this, $frame ] );
4258 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4259 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4261 // Avoid PHP 7.1 warning from passing $this by reference
4263 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
4265 $output = '<span class="error">Invalid tag extension name: ' .
4266 htmlspecialchars( $name ) . '</span>';
4269 if ( is_array( $output ) ) {
4272 $output = $flags[0];
4273 if ( isset( $flags['markerType'] ) ) {
4274 $markerType = $flags['markerType'];
4278 if ( is_null( $attrText ) ) {
4281 if ( isset( $params['attributes'] ) ) {
4282 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4283 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4284 htmlspecialchars( $attrValue ) . '"';
4287 if ( $content === null ) {
4288 $output = "<$name$attrText/>";
4290 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4291 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4295 $output = "<$name$attrText>$content$close";
4299 if ( $markerType === 'none' ) {
4301 } elseif ( $markerType === 'nowiki' ) {
4302 $this->mStripState
->addNoWiki( $marker, $output );
4303 } elseif ( $markerType === 'general' ) {
4304 $this->mStripState
->addGeneral( $marker, $output );
4306 throw new MWException( __METHOD__
. ': invalid marker type' );
4312 * Increment an include size counter
4314 * @param string $type The type of expansion
4315 * @param int $size The size of the text
4316 * @return bool False if this inclusion would take it over the maximum, true otherwise
4318 public function incrementIncludeSize( $type, $size ) {
4319 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4322 $this->mIncludeSizes
[$type] +
= $size;
4328 * Increment the expensive function count
4330 * @return bool False if the limit has been exceeded
4332 public function incrementExpensiveFunctionCount() {
4333 $this->mExpensiveFunctionCount++
;
4334 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4338 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4339 * Fills $this->mDoubleUnderscores, returns the modified text
4341 * @param string $text
4343 * @deprecated since 1.34; should not be used outside parser class.
4345 public function doDoubleUnderscore( $text ) {
4346 wfDeprecated( __METHOD__
, '1.34' );
4347 return $this->handleDoubleUnderscore( $text );
4351 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4352 * Fills $this->mDoubleUnderscores, returns the modified text
4354 * @param string $text
4357 private function handleDoubleUnderscore( $text ) {
4358 # The position of __TOC__ needs to be recorded
4359 $mw = $this->magicWordFactory
->get( 'toc' );
4360 if ( $mw->match( $text ) ) {
4361 $this->mShowToc
= true;
4362 $this->mForceTocPosition
= true;
4364 # Set a placeholder. At the end we'll fill it in with the TOC.
4365 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4367 # Only keep the first one.
4368 $text = $mw->replace( '', $text );
4371 # Now match and remove the rest of them
4372 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4373 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4375 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4376 $this->mOutput
->mNoGallery
= true;
4378 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4379 $this->mShowToc
= false;
4381 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4382 && $this->mTitle
->getNamespace() == NS_CATEGORY
4384 $this->addTrackingCategory( 'hidden-category-category' );
4386 # (T10068) Allow control over whether robots index a page.
4387 # __INDEX__ always overrides __NOINDEX__, see T16899
4388 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4389 $this->mOutput
->setIndexPolicy( 'noindex' );
4390 $this->addTrackingCategory( 'noindex-category' );
4392 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4393 $this->mOutput
->setIndexPolicy( 'index' );
4394 $this->addTrackingCategory( 'index-category' );
4397 # Cache all double underscores in the database
4398 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4399 $this->mOutput
->setProperty( $key, '' );
4406 * @see ParserOutput::addTrackingCategory()
4407 * @param string $msg Message key
4408 * @return bool Whether the addition was successful
4410 public function addTrackingCategory( $msg ) {
4411 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4415 * This function accomplishes several tasks:
4416 * 1) Auto-number headings if that option is enabled
4417 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4418 * 3) Add a Table of contents on the top for users who have enabled the option
4419 * 4) Auto-anchor headings
4421 * It loops through all headlines, collects the necessary data, then splits up the
4422 * string and re-inserts the newly formatted headlines.
4424 * @param string $text
4425 * @param string $origText Original, untouched wikitext
4426 * @param bool $isMain
4427 * @return mixed|string
4429 * @deprecated since 1.34; should not be used outside parser class.
4431 public function formatHeadings( $text, $origText, $isMain = true ) {
4432 wfDeprecated( __METHOD__
, '1.34' );
4433 return $this->finalizeHeadings( $text, $origText, $isMain );
4437 * This function accomplishes several tasks:
4438 * 1) Auto-number headings if that option is enabled
4439 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4440 * 3) Add a Table of contents on the top for users who have enabled the option
4441 * 4) Auto-anchor headings
4443 * It loops through all headlines, collects the necessary data, then splits up the
4444 * string and re-inserts the newly formatted headlines.
4446 * @param string $text
4447 * @param string $origText Original, untouched wikitext
4448 * @param bool $isMain
4449 * @return mixed|string
4451 private function finalizeHeadings( $text, $origText, $isMain = true ) {
4452 # Inhibit editsection links if requested in the page
4453 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4454 $maybeShowEditLink = false;
4456 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4459 # Get all headlines for numbering them and adding funky stuff like [edit]
4460 # links - this is for later, but we need the number of headlines right now
4461 # NOTE: white space in headings have been trimmed in handleHeadings. They shouldn't
4462 # be trimmed here since whitespace in HTML headings is significant.
4464 $numMatches = preg_match_all(
4465 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4470 # if there are fewer than 4 headlines in the article, do not show TOC
4471 # unless it's been explicitly enabled.
4472 $enoughToc = $this->mShowToc
&&
4473 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4475 # Allow user to stipulate that a page should have a "new section"
4476 # link added via __NEWSECTIONLINK__
4477 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4478 $this->mOutput
->setNewSection( true );
4481 # Allow user to remove the "new section"
4482 # link via __NONEWSECTIONLINK__
4483 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4484 $this->mOutput
->hideNewSection( true );
4487 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4488 # override above conditions and always show TOC above first header
4489 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4490 $this->mShowToc
= true;
4498 # Ugh .. the TOC should have neat indentation levels which can be
4499 # passed to the skin functions. These are determined here
4503 $sublevelCount = [];
4509 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4510 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4511 $oldType = $this->mOutputType
;
4512 $this->setOutputType( self
::OT_WIKI
);
4513 $frame = $this->getPreprocessor()->newFrame();
4514 $root = $this->preprocessToDom( $origText );
4515 $node = $root->getFirstChild();
4520 $headlines = $numMatches !== false ?
$matches[3] : [];
4522 $maxTocLevel = $this->svcOptions
->get( 'MaxTocLevel' );
4523 foreach ( $headlines as $headline ) {
4524 $isTemplate = false;
4526 $sectionIndex = false;
4528 $markerMatches = [];
4529 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4530 $serial = $markerMatches[1];
4531 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4532 $isTemplate = ( $titleText != $baseTitleText );
4533 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4537 $prevlevel = $level;
4539 $level = $matches[1][$headlineCount];
4541 if ( $level > $prevlevel ) {
4542 # Increase TOC level
4544 $sublevelCount[$toclevel] = 0;
4545 if ( $toclevel < $maxTocLevel ) {
4546 $prevtoclevel = $toclevel;
4547 $toc .= Linker
::tocIndent();
4550 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4551 # Decrease TOC level, find level to jump to
4553 for ( $i = $toclevel; $i > 0; $i-- ) {
4554 if ( $levelCount[$i] == $level ) {
4555 # Found last matching level
4558 } elseif ( $levelCount[$i] < $level ) {
4559 # Found first matching level below current level
4567 if ( $toclevel < $maxTocLevel ) {
4568 if ( $prevtoclevel < $maxTocLevel ) {
4569 # Unindent only if the previous toc level was shown :p
4570 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4571 $prevtoclevel = $toclevel;
4573 $toc .= Linker
::tocLineEnd();
4577 # No change in level, end TOC line
4578 if ( $toclevel < $maxTocLevel ) {
4579 $toc .= Linker
::tocLineEnd();
4583 $levelCount[$toclevel] = $level;
4585 # count number of headlines for each level
4586 $sublevelCount[$toclevel]++
;
4588 for ( $i = 1; $i <= $toclevel; $i++
) {
4589 if ( !empty( $sublevelCount[$i] ) ) {
4593 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4598 # The safe header is a version of the header text safe to use for links
4600 # Remove link placeholders by the link text.
4601 # <!--LINK number-->
4603 # link text with suffix
4604 # Do this before unstrip since link text can contain strip markers
4605 $safeHeadline = $this->replaceLinkHoldersTextPrivate( $headline );
4607 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4608 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4610 # Remove any <style> or <script> tags (T198618)
4611 $safeHeadline = preg_replace(
4612 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4617 # Strip out HTML (first regex removes any tag not allowed)
4619 # * <sup> and <sub> (T10393)
4623 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4624 # * <s> and <strike> (T35715)
4625 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4626 # to allow setting directionality in toc items.
4627 $tocline = preg_replace(
4629 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4630 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4636 # Strip '<span></span>', which is the result from the above if
4637 # <span id="foo"></span> is used to produce an additional anchor
4639 $tocline = str_replace( '<span></span>', '', $tocline );
4641 $tocline = trim( $tocline );
4643 # For the anchor, strip out HTML-y stuff period
4644 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4645 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4647 # Save headline for section edit hint before it's escaped
4648 $headlineHint = $safeHeadline;
4650 # Decode HTML entities
4651 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4653 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4655 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4656 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4657 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4658 if ( $fallbackHeadline === $safeHeadline ) {
4659 # No reason to have both (in fact, we can't)
4660 $fallbackHeadline = false;
4663 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4664 # @todo FIXME: We may be changing them depending on the current locale.
4665 $arrayKey = strtolower( $safeHeadline );
4666 if ( $fallbackHeadline === false ) {
4667 $fallbackArrayKey = false;
4669 $fallbackArrayKey = strtolower( $fallbackHeadline );
4672 # Create the anchor for linking from the TOC to the section
4673 $anchor = $safeHeadline;
4674 $fallbackAnchor = $fallbackHeadline;
4675 if ( isset( $refers[$arrayKey] ) ) {
4676 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4677 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4679 $linkAnchor .= "_$i";
4680 $refers["${arrayKey}_$i"] = true;
4682 $refers[$arrayKey] = true;
4684 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4685 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4686 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4687 $fallbackAnchor .= "_$i";
4688 $refers["${fallbackArrayKey}_$i"] = true;
4690 $refers[$fallbackArrayKey] = true;
4693 # Don't number the heading if it is the only one (looks silly)
4694 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4695 # the two are different if the line contains a link
4696 $headline = Html
::element(
4698 [ 'class' => 'mw-headline-number' ],
4700 ) . ' ' . $headline;
4703 if ( $enoughToc && ( !isset( $maxTocLevel ) ||
$toclevel < $maxTocLevel ) ) {
4704 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4705 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4708 # Add the section to the section tree
4709 # Find the DOM node for this header
4710 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4711 while ( $node && !$noOffset ) {
4712 if ( $node->getName() === 'h' ) {
4713 $bits = $node->splitHeading();
4714 if ( $bits['i'] == $sectionIndex ) {
4718 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4719 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4720 $node = $node->getNextSibling();
4723 'toclevel' => $toclevel,
4726 'number' => $numbering,
4727 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4728 'fromtitle' => $titleText,
4729 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4730 'anchor' => $anchor,
4733 # give headline the correct <h#> tag
4734 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4735 // Output edit section links as markers with styles that can be customized by skins
4736 if ( $isTemplate ) {
4737 # Put a T flag in the section identifier, to indicate to extractSections()
4738 # that sections inside <includeonly> should be counted.
4739 $editsectionPage = $titleText;
4740 $editsectionSection = "T-$sectionIndex";
4741 $editsectionContent = null;
4743 $editsectionPage = $this->mTitle
->getPrefixedText();
4744 $editsectionSection = $sectionIndex;
4745 $editsectionContent = $headlineHint;
4747 // We use a bit of pesudo-xml for editsection markers. The
4748 // language converter is run later on. Using a UNIQ style marker
4749 // leads to the converter screwing up the tokens when it
4750 // converts stuff. And trying to insert strip tags fails too. At
4751 // this point all real inputted tags have already been escaped,
4752 // so we don't have to worry about a user trying to input one of
4753 // these markers directly. We use a page and section attribute
4754 // to stop the language converter from converting these
4755 // important bits of data, but put the headline hint inside a
4756 // content block because the language converter is supposed to
4757 // be able to convert that piece of data.
4758 // Gets replaced with html in ParserOutput::getText
4759 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4760 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4761 if ( $editsectionContent !== null ) {
4762 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4769 $head[$headlineCount] = Linker
::makeHeadline( $level,
4770 $matches['attrib'][$headlineCount], $anchor, $headline,
4771 $editlink, $fallbackAnchor );
4776 $this->setOutputType( $oldType );
4778 # Never ever show TOC if no headers
4779 if ( $numVisible < 1 ) {
4784 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4785 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4787 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4788 $this->mOutput
->setTOCHTML( $toc );
4789 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4793 $this->mOutput
->setSections( $tocraw );
4796 # split up and insert constructed headlines
4797 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4800 // build an array of document sections
4802 foreach ( $blocks as $block ) {
4803 // $head is zero-based, sections aren't.
4804 if ( empty( $head[$i - 1] ) ) {
4805 $sections[$i] = $block;
4807 $sections[$i] = $head[$i - 1] . $block;
4811 * Send a hook, one per section.
4812 * The idea here is to be able to make section-level DIVs, but to do so in a
4813 * lower-impact, more correct way than r50769
4816 * $section : the section number
4817 * &$sectionContent : ref to the content of the section
4818 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4820 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4825 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4826 // append the TOC at the beginning
4827 // Top anchor now in skin
4828 $sections[0] .= $toc . "\n";
4831 $full .= implode( '', $sections );
4833 if ( $this->mForceTocPosition
) {
4834 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4841 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4842 * conversion, substituting signatures, {{subst:}} templates, etc.
4844 * @param string $text The text to transform
4845 * @param Title $title The Title object for the current article
4846 * @param User $user The User object describing the current user
4847 * @param ParserOptions $options Parsing options
4848 * @param bool $clearState Whether to clear the parser state first
4849 * @return string The altered wiki markup
4851 public function preSaveTransform( $text, Title
$title, User
$user,
4852 ParserOptions
$options, $clearState = true
4854 if ( $clearState ) {
4855 $magicScopeVariable = $this->lock();
4857 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4858 $this->setUser( $user );
4860 // Strip U+0000 NULL (T159174)
4861 $text = str_replace( "\000", '', $text );
4863 // We still normalize line endings for backwards-compatibility
4864 // with other code that just calls PST, but this should already
4865 // be handled in TextContent subclasses
4866 $text = TextContent
::normalizeLineEndings( $text );
4868 if ( $options->getPreSaveTransform() ) {
4869 $text = $this->pstPass2( $text, $user );
4871 $text = $this->mStripState
->unstripBoth( $text );
4873 $this->setUser( null ); # Reset
4879 * Pre-save transform helper function
4881 * @param string $text
4886 private function pstPass2( $text, $user ) {
4887 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4888 # $this->contLang here in order to give everyone the same signature and use the default one
4889 # rather than the one selected in each user's preferences. (see also T14815)
4890 $ts = $this->mOptions
->getTimestamp();
4891 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4892 $ts = $timestamp->format( 'YmdHis' );
4893 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4895 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4897 # Variable replacement
4898 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4899 $text = $this->replaceVariables( $text );
4901 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4902 # which may corrupt this parser instance via its wfMessage()->text() call-
4905 if ( strpos( $text, '~~~' ) !== false ) {
4906 $sigText = $this->getUserSig( $user );
4907 $text = strtr( $text, [
4909 '~~~~' => "$sigText $d",
4912 # The main two signature forms used above are time-sensitive
4913 $this->setOutputFlag( 'user-signature', 'User signature detected' );
4916 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4917 $tc = '[' . Title
::legalChars() . ']';
4918 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4920 // [[ns:page (context)|]]
4921 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4922 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4923 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4924 // [[ns:page (context), context|]] (using either single or double-width comma)
4925 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4926 // [[|page]] (reverse pipe trick: add context from page title)
4927 $p2 = "/\[\[\\|($tc+)]]/";
4929 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4930 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4931 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4932 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4934 $t = $this->mTitle
->getText();
4936 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4937 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4938 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4939 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4941 # if there's no context, don't bother duplicating the title
4942 $text = preg_replace( $p2, '[[\\1]]', $text );
4949 * Fetch the user's signature text, if any, and normalize to
4950 * validated, ready-to-insert wikitext.
4951 * If you have pre-fetched the nickname or the fancySig option, you can
4952 * specify them here to save a database query.
4953 * Do not reuse this parser instance after calling getUserSig(),
4954 * as it may have changed.
4956 * @param User &$user
4957 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4958 * @param bool|null $fancySig whether the nicknname is the complete signature
4959 * or null to use default value
4962 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4963 $username = $user->getName();
4965 # If not given, retrieve from the user object.
4966 if ( $nickname === false ) {
4967 $nickname = $user->getOption( 'nickname' );
4970 if ( is_null( $fancySig ) ) {
4971 $fancySig = $user->getBoolOption( 'fancysig' );
4974 $nickname = $nickname == null ?
$username : $nickname;
4976 if ( mb_strlen( $nickname ) > $this->svcOptions
->get( 'MaxSigChars' ) ) {
4977 $nickname = $username;
4978 $this->logger
->debug( __METHOD__
. ": $username has overlong signature." );
4979 } elseif ( $fancySig !== false ) {
4980 # Sig. might contain markup; validate this
4981 if ( $this->validateSig( $nickname ) !== false ) {
4982 # Validated; clean up (if needed) and return it
4983 return $this->cleanSig( $nickname, true );
4985 # Failed to validate; fall back to the default
4986 $nickname = $username;
4987 $this->logger
->debug( __METHOD__
. ": $username has bad XML tags in signature." );
4991 # Make sure nickname doesnt get a sig in a sig
4992 $nickname = self
::cleanSigInSig( $nickname );
4994 # If we're still here, make it a link to the user page
4995 $userText = wfEscapeWikiText( $username );
4996 $nickText = wfEscapeWikiText( $nickname );
4997 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4999 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
5000 ->title( $this->getTitle() )->text();
5004 * Check that the user's signature contains no bad XML
5006 * @param string $text
5007 * @return string|bool An expanded string, or false if invalid.
5009 public function validateSig( $text ) {
5010 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
5014 * Clean up signature text
5016 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
5017 * 2) Substitute all transclusions
5019 * @param string $text
5020 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
5021 * @return string Signature text
5023 public function cleanSig( $text, $parsing = false ) {
5026 $magicScopeVariable = $this->lock();
5027 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
5030 # Option to disable this feature
5031 if ( !$this->mOptions
->getCleanSignatures() ) {
5035 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5036 # => Move this logic to braceSubstitution()
5037 $substWord = $this->magicWordFactory
->get( 'subst' );
5038 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5039 $substText = '{{' . $substWord->getSynonym( 0 );
5041 $text = preg_replace( $substRegex, $substText, $text );
5042 $text = self
::cleanSigInSig( $text );
5043 $dom = $this->preprocessToDom( $text );
5044 $frame = $this->getPreprocessor()->newFrame();
5045 $text = $frame->expand( $dom );
5048 $text = $this->mStripState
->unstripBoth( $text );
5055 * Strip 3, 4 or 5 tildes out of signatures.
5057 * @param string $text
5058 * @return string Signature text with /~{3,5}/ removed
5060 public static function cleanSigInSig( $text ) {
5061 $text = preg_replace( '/~{3,5}/', '', $text );
5066 * Set up some variables which are usually set up in parse()
5067 * so that an external function can call some class members with confidence
5069 * @param Title|null $title
5070 * @param ParserOptions $options
5071 * @param int $outputType
5072 * @param bool $clearState
5073 * @param int|null $revId
5075 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5076 $outputType, $clearState = true, $revId = null
5078 $this->startParse( $title, $options, $outputType, $clearState );
5079 if ( $revId !== null ) {
5080 $this->mRevisionId
= $revId;
5085 * @param Title|null $title
5086 * @param ParserOptions $options
5087 * @param int $outputType
5088 * @param bool $clearState
5090 private function startParse( Title
$title = null, ParserOptions
$options,
5091 $outputType, $clearState = true
5093 $this->setTitle( $title );
5094 $this->mOptions
= $options;
5095 $this->setOutputType( $outputType );
5096 if ( $clearState ) {
5097 $this->clearState();
5102 * Wrapper for preprocess()
5104 * @param string $text The text to preprocess
5105 * @param ParserOptions $options
5106 * @param Title|null $title Title object or null to use $wgTitle
5109 public function transformMsg( $text, $options, $title = null ) {
5110 static $executing = false;
5112 # Guard against infinite recursion
5123 $text = $this->preprocess( $text, $title, $options );
5130 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5131 * The callback should have the following form:
5132 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5134 * Transform and return $text. Use $parser for any required context, e.g. use
5135 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5137 * Hooks may return extended information by returning an array, of which the
5138 * first numbered element (index 0) must be the return string, and all other
5139 * entries are extracted into local variables within an internal function
5140 * in the Parser class.
5142 * This interface (introduced r61913) appears to be undocumented, but
5143 * 'markerType' is used by some core tag hooks to override which strip
5144 * array their results are placed in. **Use great caution if attempting
5145 * this interface, as it is not documented and injudicious use could smash
5146 * private variables.**
5148 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5149 * @param callable $callback The callback function (and object) to use for the tag
5150 * @throws MWException
5151 * @return callable|null The old value of the mTagHooks array associated with the hook
5153 public function setHook( $tag, callable
$callback ) {
5154 $tag = strtolower( $tag );
5155 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5156 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5158 $oldVal = $this->mTagHooks
[$tag] ??
null;
5159 $this->mTagHooks
[$tag] = $callback;
5160 if ( !in_array( $tag, $this->mStripList
) ) {
5161 $this->mStripList
[] = $tag;
5168 * As setHook(), but letting the contents be parsed.
5170 * Transparent tag hooks are like regular XML-style tag hooks, except they
5171 * operate late in the transformation sequence, on HTML instead of wikitext.
5173 * This is probably obsoleted by things dealing with parser frames?
5174 * The only extension currently using it is geoserver.
5177 * @todo better document or deprecate this
5179 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5180 * @param callable $callback The callback function (and object) to use for the tag
5181 * @throws MWException
5182 * @return callable|null The old value of the mTagHooks array associated with the hook
5184 public function setTransparentTagHook( $tag, callable
$callback ) {
5185 $tag = strtolower( $tag );
5186 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5187 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5189 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
5190 $this->mTransparentTagHooks
[$tag] = $callback;
5196 * Remove all tag hooks
5198 public function clearTagHooks() {
5199 $this->mTagHooks
= [];
5200 $this->mFunctionTagHooks
= [];
5201 $this->mStripList
= $this->mDefaultStripList
;
5205 * Create a function, e.g. {{sum:1|2|3}}
5206 * The callback function should have the form:
5207 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5209 * Or with Parser::SFH_OBJECT_ARGS:
5210 * function myParserFunction( $parser, $frame, $args ) { ... }
5212 * The callback may either return the text result of the function, or an array with the text
5213 * in element 0, and a number of flags in the other elements. The names of the flags are
5214 * specified in the keys. Valid flags are:
5215 * found The text returned is valid, stop processing the template. This
5217 * nowiki Wiki markup in the return value should be escaped
5218 * isHTML The returned text is HTML, armour it against wikitext transformation
5220 * @param string $id The magic word ID
5221 * @param callable $callback The callback function (and object) to use
5222 * @param int $flags A combination of the following flags:
5223 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5225 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5226 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5227 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5228 * the arguments, and to control the way they are expanded.
5230 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5231 * arguments, for instance:
5232 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5234 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5235 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5236 * working if/when this is changed.
5238 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5241 * Please read the documentation in includes/parser/Preprocessor.php for more information
5242 * about the methods available in PPFrame and PPNode.
5244 * @throws MWException
5245 * @return string|callable The old callback function for this name, if any
5247 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
5248 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5249 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
5251 # Add to function cache
5252 $mw = $this->magicWordFactory
->get( $id );
5254 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5257 $synonyms = $mw->getSynonyms();
5258 $sensitive = intval( $mw->isCaseSensitive() );
5260 foreach ( $synonyms as $syn ) {
5262 if ( !$sensitive ) {
5263 $syn = $this->contLang
->lc( $syn );
5266 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5269 # Remove trailing colon
5270 if ( substr( $syn, -1, 1 ) === ':' ) {
5271 $syn = substr( $syn, 0, -1 );
5273 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5279 * Get all registered function hook identifiers
5283 public function getFunctionHooks() {
5284 $this->firstCallInit();
5285 return array_keys( $this->mFunctionHooks
);
5289 * Create a tag function, e.g. "<test>some stuff</test>".
5290 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5291 * Unlike parser functions, their content is not preprocessed.
5292 * @param string $tag
5293 * @param callable $callback
5295 * @throws MWException
5298 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
5299 $tag = strtolower( $tag );
5300 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5301 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5303 $old = $this->mFunctionTagHooks
[$tag] ??
null;
5304 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
5306 if ( !in_array( $tag, $this->mStripList
) ) {
5307 $this->mStripList
[] = $tag;
5314 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5315 * Placeholders created in Linker::link()
5317 * @param string &$text
5318 * @param int $options
5319 * @deprecated since 1.34; should not be used outside parser class.
5321 public function replaceLinkHolders( &$text, $options = 0 ) {
5322 $this->replaceLinkHoldersPrivate( $text, $options );
5326 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5327 * Placeholders created in Linker::link()
5329 * @param string &$text
5330 * @param int $options
5332 private function replaceLinkHoldersPrivate( &$text, $options = 0 ) {
5333 $this->mLinkHolders
->replace( $text );
5337 * Replace "<!--LINK-->" link placeholders with plain text of links
5338 * (not HTML-formatted).
5340 * @param string $text
5342 * @deprecated since 1.34; should not be used outside parser class.
5344 public function replaceLinkHoldersText( $text ) {
5345 wfDeprecated( __METHOD__
, '1.34' );
5346 return $this->replaceLinkHoldersTextPrivate( $text );
5350 * Replace "<!--LINK-->" link placeholders with plain text of links
5351 * (not HTML-formatted).
5353 * @param string $text
5356 private function replaceLinkHoldersTextPrivate( $text ) {
5357 return $this->mLinkHolders
->replaceText( $text );
5361 * Renders an image gallery from a text with one line per image.
5362 * text labels may be given by using |-style alternative text. E.g.
5363 * Image:one.jpg|The number "1"
5364 * Image:tree.jpg|A tree
5365 * given as text will return the HTML of a gallery with two images,
5366 * labeled 'The number "1"' and
5369 * @param string $text
5370 * @param array $params
5371 * @return string HTML
5373 public function renderImageGallery( $text, $params ) {
5375 if ( isset( $params['mode'] ) ) {
5376 $mode = $params['mode'];
5380 $ig = ImageGalleryBase
::factory( $mode );
5381 } catch ( Exception
$e ) {
5382 // If invalid type set, fallback to default.
5383 $ig = ImageGalleryBase
::factory( false );
5386 $ig->setContextTitle( $this->mTitle
);
5387 $ig->setShowBytes( false );
5388 $ig->setShowDimensions( false );
5389 $ig->setShowFilename( false );
5390 $ig->setParser( $this );
5391 $ig->setHideBadImages();
5392 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5394 if ( isset( $params['showfilename'] ) ) {
5395 $ig->setShowFilename( true );
5397 $ig->setShowFilename( false );
5399 if ( isset( $params['caption'] ) ) {
5400 // NOTE: We aren't passing a frame here or below. Frame info
5401 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5402 // See T107332#4030581
5403 $caption = $this->recursiveTagParse( $params['caption'] );
5404 $ig->setCaptionHtml( $caption );
5406 if ( isset( $params['perrow'] ) ) {
5407 $ig->setPerRow( $params['perrow'] );
5409 if ( isset( $params['widths'] ) ) {
5410 $ig->setWidths( $params['widths'] );
5412 if ( isset( $params['heights'] ) ) {
5413 $ig->setHeights( $params['heights'] );
5415 $ig->setAdditionalOptions( $params );
5417 // Avoid PHP 7.1 warning from passing $this by reference
5419 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5421 $lines = StringUtils
::explode( "\n", $text );
5422 foreach ( $lines as $line ) {
5423 # match lines like these:
5424 # Image:someimage.jpg|This is some image
5426 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5428 if ( count( $matches ) == 0 ) {
5432 if ( strpos( $matches[0], '%' ) !== false ) {
5433 $matches[1] = rawurldecode( $matches[1] );
5435 $title = Title
::newFromText( $matches[1], NS_FILE
);
5436 if ( is_null( $title ) ) {
5437 # Bogus title. Ignore these so we don't bomb out later.
5441 # We need to get what handler the file uses, to figure out parameters.
5442 # Note, a hook can overide the file name, and chose an entirely different
5443 # file (which potentially could be of a different type and have different handler).
5446 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5447 [ $this, $title, &$options, &$descQuery ] );
5448 # Don't register it now, as TraditionalImageGallery does that later.
5449 $file = $this->fetchFileNoRegister( $title, $options );
5450 $handler = $file ?
$file->getHandler() : false;
5453 'img_alt' => 'gallery-internal-alt',
5454 'img_link' => 'gallery-internal-link',
5457 $paramMap +
= $handler->getParamMap();
5458 // We don't want people to specify per-image widths.
5459 // Additionally the width parameter would need special casing anyhow.
5460 unset( $paramMap['img_width'] );
5463 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5468 $handlerOptions = [];
5469 if ( isset( $matches[3] ) ) {
5470 // look for an |alt= definition while trying not to break existing
5471 // captions with multiple pipes (|) in it, until a more sensible grammar
5472 // is defined for images in galleries
5474 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5475 // splitting on '|' is a bit odd, and different from makeImage.
5476 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5477 // Protect LanguageConverter markup
5478 $parameterMatches = StringUtils
::delimiterExplode(
5479 '-{', '}-', '|', $matches[3], true /* nested */
5482 foreach ( $parameterMatches as $parameterMatch ) {
5483 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5485 $paramName = $paramMap[$magicName];
5487 switch ( $paramName ) {
5488 case 'gallery-internal-alt':
5489 $alt = $this->stripAltText( $match, false );
5491 case 'gallery-internal-link':
5492 $linkValue = $this->stripAltText( $match, false );
5493 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5494 // Result of LanguageConverter::markNoConversion
5495 // invoked on an external link.
5496 $linkValue = substr( $linkValue, 4, -2 );
5498 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5499 if ( $type === 'link-url' ) {
5501 $this->mOutput
->addExternalLink( $target );
5502 } elseif ( $type === 'link-title' ) {
5503 $link = $target->getLinkURL();
5504 $this->mOutput
->addLink( $target );
5508 // Must be a handler specific parameter.
5509 if ( $handler->validateParam( $paramName, $match ) ) {
5510 $handlerOptions[$paramName] = $match;
5512 // Guess not, consider it as caption.
5513 $this->logger
->debug(
5514 "$parameterMatch failed parameter validation" );
5515 $label = $parameterMatch;
5521 $label = $parameterMatch;
5526 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5528 $html = $ig->toHTML();
5529 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5534 * @param MediaHandler $handler
5537 public function getImageParams( $handler ) {
5539 $handlerClass = get_class( $handler );
5543 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5544 # Initialise static lists
5545 static $internalParamNames = [
5546 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5547 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5548 'bottom', 'text-bottom' ],
5549 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5550 'upright', 'border', 'link', 'alt', 'class' ],
5552 static $internalParamMap;
5553 if ( !$internalParamMap ) {
5554 $internalParamMap = [];
5555 foreach ( $internalParamNames as $type => $names ) {
5556 foreach ( $names as $name ) {
5557 // For grep: img_left, img_right, img_center, img_none,
5558 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5559 // img_bottom, img_text_bottom,
5560 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5561 // img_border, img_link, img_alt, img_class
5562 $magicName = str_replace( '-', '_', "img_$name" );
5563 $internalParamMap[$magicName] = [ $type, $name ];
5568 # Add handler params
5569 $paramMap = $internalParamMap;
5571 $handlerParamMap = $handler->getParamMap();
5572 foreach ( $handlerParamMap as $magic => $paramName ) {
5573 $paramMap[$magic] = [ 'handler', $paramName ];
5576 $this->mImageParams
[$handlerClass] = $paramMap;
5577 $this->mImageParamsMagicArray
[$handlerClass] =
5578 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5580 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5584 * Parse image options text and use it to make an image
5586 * @param Title $title
5587 * @param string $options
5588 * @param LinkHolderArray|bool $holders
5589 * @return string HTML
5591 public function makeImage( $title, $options, $holders = false ) {
5592 # Check if the options text is of the form "options|alt text"
5594 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5595 # * left no resizing, just left align. label is used for alt= only
5596 # * right same, but right aligned
5597 # * none same, but not aligned
5598 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5599 # * center center the image
5600 # * frame Keep original image size, no magnify-button.
5601 # * framed Same as "frame"
5602 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5603 # * upright reduce width for upright images, rounded to full __0 px
5604 # * border draw a 1px border around the image
5605 # * alt Text for HTML alt attribute (defaults to empty)
5606 # * class Set a class for img node
5607 # * link Set the target of the image link. Can be external, interwiki, or local
5608 # vertical-align values (no % or length right now):
5618 # Protect LanguageConverter markup when splitting into parts
5619 $parts = StringUtils
::delimiterExplode(
5620 '-{', '}-', '|', $options, true /* allow nesting */
5623 # Give extensions a chance to select the file revision for us
5626 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5627 [ $this, $title, &$options, &$descQuery ] );
5628 # Fetch and register the file (file title may be different via hooks)
5629 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5632 $handler = $file ?
$file->getHandler() : false;
5634 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5637 $this->addTrackingCategory( 'broken-file-category' );
5640 # Process the input parameters
5642 $params = [ 'frame' => [], 'handler' => [],
5643 'horizAlign' => [], 'vertAlign' => [] ];
5644 $seenformat = false;
5645 foreach ( $parts as $part ) {
5646 $part = trim( $part );
5647 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5649 if ( isset( $paramMap[$magicName] ) ) {
5650 list( $type, $paramName ) = $paramMap[$magicName];
5652 # Special case; width and height come in one variable together
5653 if ( $type === 'handler' && $paramName === 'width' ) {
5654 $parsedWidthParam = self
::parseWidthParam( $value );
5655 if ( isset( $parsedWidthParam['width'] ) ) {
5656 $width = $parsedWidthParam['width'];
5657 if ( $handler->validateParam( 'width', $width ) ) {
5658 $params[$type]['width'] = $width;
5662 if ( isset( $parsedWidthParam['height'] ) ) {
5663 $height = $parsedWidthParam['height'];
5664 if ( $handler->validateParam( 'height', $height ) ) {
5665 $params[$type]['height'] = $height;
5669 # else no validation -- T15436
5671 if ( $type === 'handler' ) {
5672 # Validate handler parameter
5673 $validated = $handler->validateParam( $paramName, $value );
5675 # Validate internal parameters
5676 switch ( $paramName ) {
5680 # @todo FIXME: Possibly check validity here for
5681 # manualthumb? downstream behavior seems odd with
5682 # missing manual thumbs.
5684 $value = $this->stripAltText( $value, $holders );
5687 list( $paramName, $value ) =
5688 $this->parseLinkParameter(
5689 $this->stripAltText( $value, $holders )
5693 if ( $paramName === 'no-link' ) {
5696 if ( ( $paramName === 'link-url' ) && $this->mOptions
->getExternalLinkTarget() ) {
5697 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5704 // use first appearing option, discard others.
5705 $validated = !$seenformat;
5709 # Most other things appear to be empty or numeric...
5710 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5715 $params[$type][$paramName] = $value;
5719 if ( !$validated ) {
5724 # Process alignment parameters
5725 if ( $params['horizAlign'] ) {
5726 $params['frame']['align'] = key( $params['horizAlign'] );
5728 if ( $params['vertAlign'] ) {
5729 $params['frame']['valign'] = key( $params['vertAlign'] );
5732 $params['frame']['caption'] = $caption;
5734 # Will the image be presented in a frame, with the caption below?
5735 $imageIsFramed = isset( $params['frame']['frame'] )
5736 ||
isset( $params['frame']['framed'] )
5737 ||
isset( $params['frame']['thumbnail'] )
5738 ||
isset( $params['frame']['manualthumb'] );
5740 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5741 # came to also set the caption, ordinary text after the image -- which
5742 # makes no sense, because that just repeats the text multiple times in
5743 # screen readers. It *also* came to set the title attribute.
5744 # Now that we have an alt attribute, we should not set the alt text to
5745 # equal the caption: that's worse than useless, it just repeats the
5746 # text. This is the framed/thumbnail case. If there's no caption, we
5747 # use the unnamed parameter for alt text as well, just for the time be-
5748 # ing, if the unnamed param is set and the alt param is not.
5749 # For the future, we need to figure out if we want to tweak this more,
5750 # e.g., introducing a title= parameter for the title; ignoring the un-
5751 # named parameter entirely for images without a caption; adding an ex-
5752 # plicit caption= parameter and preserving the old magic unnamed para-
5754 if ( $imageIsFramed ) { # Framed image
5755 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5756 # No caption or alt text, add the filename as the alt text so
5757 # that screen readers at least get some description of the image
5758 $params['frame']['alt'] = $title->getText();
5760 # Do not set $params['frame']['title'] because tooltips don't make sense
5762 } else { # Inline image
5763 if ( !isset( $params['frame']['alt'] ) ) {
5764 # No alt text, use the "caption" for the alt text
5765 if ( $caption !== '' ) {
5766 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5768 # No caption, fall back to using the filename for the
5770 $params['frame']['alt'] = $title->getText();
5773 # Use the "caption" for the tooltip text
5774 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5776 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5778 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5780 # Linker does the rest
5781 $time = $options['time'] ??
false;
5782 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5783 $time, $descQuery, $this->mOptions
->getThumbSize() );
5785 # Give the handler a chance to modify the parser object
5787 $handler->parserTransformHook( $this, $file );
5794 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5796 * Adds an entry to appropriate link tables.
5799 * @param string $value
5800 * @return array of `[ type, target ]`, where:
5801 * - `type` is one of:
5802 * - `null`: Given value is not a valid link target, use default
5803 * - `'no-link'`: Given value is empty, do not generate a link
5804 * - `'link-url'`: Given value is a valid external link
5805 * - `'link-title'`: Given value is a valid internal link
5807 * - When `type` is `null` or `'no-link'`: `false`
5808 * - When `type` is `'link-url'`: URL string corresponding to given value
5809 * - When `type` is `'link-title'`: Title object corresponding to given value
5811 public function parseLinkParameter( $value ) {
5812 $chars = self
::EXT_LINK_URL_CLASS
;
5813 $addr = self
::EXT_LINK_ADDR
;
5814 $prots = $this->mUrlProtocols
;
5817 if ( $value === '' ) {
5819 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5820 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5821 $this->mOutput
->addExternalLink( $value );
5826 $linkTitle = Title
::newFromText( $value );
5828 $this->mOutput
->addLink( $linkTitle );
5829 $type = 'link-title';
5830 $target = $linkTitle;
5833 return [ $type, $target ];
5837 * @param string $caption
5838 * @param LinkHolderArray|bool $holders
5839 * @return mixed|string
5841 protected function stripAltText( $caption, $holders ) {
5842 # Strip bad stuff out of the title (tooltip). We can't just use
5843 # replaceLinkHoldersText() here, because if this function is called
5844 # from handleInternalLinks2(), mLinkHolders won't be up-to-date.
5846 $tooltip = $holders->replaceText( $caption );
5848 $tooltip = $this->replaceLinkHoldersTextPrivate( $caption );
5851 # make sure there are no placeholders in thumbnail attributes
5852 # that are later expanded to html- so expand them now and
5854 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5855 # Compatibility hack! In HTML certain entity references not terminated
5856 # by a semicolon are decoded (but not if we're in an attribute; that's
5857 # how link URLs get away without properly escaping & in queries).
5858 # But wikitext has always required semicolon-termination of entities,
5859 # so encode & where needed to avoid decode of semicolon-less entities.
5861 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5862 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5863 $tooltip = preg_replace( "/
5864 & # 1. entity prefix
5865 (?= # 2. followed by:
5866 (?: # a. one of the legacy semicolon-less named entities
5867 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5868 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5869 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5870 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5871 U(?:acute|circ|grave|uml)|Yacute|
5872 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5873 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5874 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5875 frac(?:1(?:2|4)|34)|
5876 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5877 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5878 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5879 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5880 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5881 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5882 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5883 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5884 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5886 (?:[^;]|$)) # b. and not followed by a semicolon
5887 # S = study, for efficiency
5888 /Sx", '&', $tooltip );
5889 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5895 * Set a flag in the output object indicating that the content is dynamic and
5896 * shouldn't be cached.
5897 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5899 public function disableCache() {
5900 $this->logger
->debug( "Parser output marked as uncacheable." );
5901 if ( !$this->mOutput
) {
5902 throw new MWException( __METHOD__
.
5903 " can only be called when actually parsing something" );
5905 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5909 * Callback from the Sanitizer for expanding items found in HTML attribute
5910 * values, so they can be safely tested and escaped.
5912 * @param string &$text
5913 * @param bool|PPFrame $frame
5916 public function attributeStripCallback( &$text, $frame = false ) {
5917 $text = $this->replaceVariables( $text, $frame );
5918 $text = $this->mStripState
->unstripBoth( $text );
5927 public function getTags() {
5928 $this->firstCallInit();
5930 array_keys( $this->mTransparentTagHooks
),
5931 array_keys( $this->mTagHooks
),
5932 array_keys( $this->mFunctionTagHooks
)
5940 public function getFunctionSynonyms() {
5941 $this->firstCallInit();
5942 return $this->mFunctionSynonyms
;
5949 public function getUrlProtocols() {
5950 return $this->mUrlProtocols
;
5954 * Replace transparent tags in $text with the values given by the callbacks.
5956 * Transparent tag hooks are like regular XML-style tag hooks, except they
5957 * operate late in the transformation sequence, on HTML instead of wikitext.
5959 * @param string $text
5963 public function replaceTransparentTags( $text ) {
5965 $elements = array_keys( $this->mTransparentTagHooks
);
5966 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5969 foreach ( $matches as $marker => $data ) {
5970 list( $element, $content, $params, $tag ) = $data;
5971 $tagName = strtolower( $element );
5972 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5973 $output = call_user_func_array(
5974 $this->mTransparentTagHooks
[$tagName],
5975 [ $content, $params, $this ]
5980 $replacements[$marker] = $output;
5982 return strtr( $text, $replacements );
5986 * Break wikitext input into sections, and either pull or replace
5987 * some particular section's text.
5989 * External callers should use the getSection and replaceSection methods.
5991 * @param string $text Page wikitext
5992 * @param string|int $sectionId A section identifier string of the form:
5993 * "<flag1> - <flag2> - ... - <section number>"
5995 * Currently the only recognised flag is "T", which means the target section number
5996 * was derived during a template inclusion parse, in other words this is a template
5997 * section edit link. If no flags are given, it was an ordinary section edit link.
5998 * This flag is required to avoid a section numbering mismatch when a section is
5999 * enclosed by "<includeonly>" (T8563).
6001 * The section number 0 pulls the text before the first heading; other numbers will
6002 * pull the given section along with its lower-level subsections. If the section is
6003 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
6005 * Section 0 is always considered to exist, even if it only contains the empty
6006 * string. If $text is the empty string and section 0 is replaced, $newText is
6009 * @param string $mode One of "get" or "replace"
6010 * @param string $newText Replacement text for section data.
6011 * @return string For "get", the extracted section text.
6012 * for "replace", the whole page with the section replaced.
6014 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
6015 global $wgTitle; # not generally used but removes an ugly failure mode
6017 $magicScopeVariable = $this->lock();
6018 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
6020 $frame = $this->getPreprocessor()->newFrame();
6022 # Process section extraction flags
6024 $sectionParts = explode( '-', $sectionId );
6025 $sectionIndex = array_pop( $sectionParts );
6026 foreach ( $sectionParts as $part ) {
6027 if ( $part === 'T' ) {
6028 $flags |
= self
::PTD_FOR_INCLUSION
;
6032 # Check for empty input
6033 if ( strval( $text ) === '' ) {
6034 # Only sections 0 and T-0 exist in an empty document
6035 if ( $sectionIndex == 0 ) {
6036 if ( $mode === 'get' ) {
6042 if ( $mode === 'get' ) {
6050 # Preprocess the text
6051 $root = $this->preprocessToDom( $text, $flags );
6053 # <h> nodes indicate section breaks
6054 # They can only occur at the top level, so we can find them by iterating the root's children
6055 $node = $root->getFirstChild();
6057 # Find the target section
6058 if ( $sectionIndex == 0 ) {
6059 # Section zero doesn't nest, level=big
6060 $targetLevel = 1000;
6063 if ( $node->getName() === 'h' ) {
6064 $bits = $node->splitHeading();
6065 if ( $bits['i'] == $sectionIndex ) {
6066 $targetLevel = $bits['level'];
6070 if ( $mode === 'replace' ) {
6071 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6073 $node = $node->getNextSibling();
6079 if ( $mode === 'get' ) {
6086 # Find the end of the section, including nested sections
6088 if ( $node->getName() === 'h' ) {
6089 $bits = $node->splitHeading();
6090 $curLevel = $bits['level'];
6091 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
6095 if ( $mode === 'get' ) {
6096 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6098 $node = $node->getNextSibling();
6101 # Write out the remainder (in replace mode only)
6102 if ( $mode === 'replace' ) {
6103 # Output the replacement text
6104 # Add two newlines on -- trailing whitespace in $newText is conventionally
6105 # stripped by the editor, so we need both newlines to restore the paragraph gap
6106 # Only add trailing whitespace if there is newText
6107 if ( $newText != "" ) {
6108 $outText .= $newText . "\n\n";
6112 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6113 $node = $node->getNextSibling();
6117 if ( is_string( $outText ) ) {
6118 # Re-insert stripped tags
6119 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
6126 * This function returns the text of a section, specified by a number ($section).
6127 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
6128 * the first section before any such heading (section 0).
6130 * If a section contains subsections, these are also returned.
6132 * @param string $text Text to look in
6133 * @param string|int $sectionId Section identifier as a number or string
6134 * (e.g. 0, 1 or 'T-1').
6135 * @param string $defaultText Default to return if section is not found
6137 * @return string Text of the requested section
6139 public function getSection( $text, $sectionId, $defaultText = '' ) {
6140 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
6144 * This function returns $oldtext after the content of the section
6145 * specified by $section has been replaced with $text. If the target
6146 * section does not exist, $oldtext is returned unchanged.
6148 * @param string $oldText Former text of the article
6149 * @param string|int $sectionId Section identifier as a number or string
6150 * (e.g. 0, 1 or 'T-1').
6151 * @param string $newText Replacing text
6153 * @return string Modified text
6155 public function replaceSection( $oldText, $sectionId, $newText ) {
6156 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6160 * Get the ID of the revision we are parsing
6162 * The return value will be either:
6163 * - a) Positive, indicating a specific revision ID (current or old)
6164 * - b) Zero, meaning the revision ID is specified by getCurrentRevisionCallback()
6165 * - c) Null, meaning the parse is for preview mode and there is no revision
6169 public function getRevisionId() {
6170 return $this->mRevisionId
;
6174 * Get the revision object for $this->mRevisionId
6176 * @return Revision|null Either a Revision object or null
6177 * @since 1.23 (public since 1.23)
6179 public function getRevisionObject() {
6180 if ( $this->mRevisionObject
) {
6181 return $this->mRevisionObject
;
6184 // NOTE: try to get the RevisionObject even if mRevisionId is null.
6185 // This is useful when parsing a revision that has not yet been saved.
6186 // However, if we get back a saved revision even though we are in
6187 // preview mode, we'll have to ignore it, see below.
6188 // NOTE: This callback may be used to inject an OLD revision that was
6189 // already loaded, so "current" is a bit of a misnomer. We can't just
6190 // skip it if mRevisionId is set.
6191 $rev = call_user_func(
6192 $this->mOptions
->getCurrentRevisionCallback(),
6197 if ( $this->mRevisionId
=== null && $rev && $rev->getId() ) {
6198 // We are in preview mode (mRevisionId is null), and the current revision callback
6199 // returned an existing revision. Ignore it and return null, it's probably the page's
6200 // current revision, which is not what we want here. Note that we do want to call the
6201 // callback to allow the unsaved revision to be injected here, e.g. for
6202 // self-transclusion previews.
6206 // If the parse is for a new revision, then the callback should have
6207 // already been set to force the object and should match mRevisionId.
6208 // If not, try to fetch by mRevisionId for sanity.
6209 if ( $this->mRevisionId
&& $rev && $rev->getId() != $this->mRevisionId
) {
6210 $rev = Revision
::newFromId( $this->mRevisionId
);
6213 $this->mRevisionObject
= $rev;
6215 return $this->mRevisionObject
;
6219 * Get the timestamp associated with the current revision, adjusted for
6220 * the default server-local timestamp
6221 * @return string TS_MW timestamp
6223 public function getRevisionTimestamp() {
6224 if ( $this->mRevisionTimestamp
!== null ) {
6225 return $this->mRevisionTimestamp
;
6228 # Use specified revision timestamp, falling back to the current timestamp
6229 $revObject = $this->getRevisionObject();
6230 $timestamp = $revObject ?
$revObject->getTimestamp() : $this->mOptions
->getTimestamp();
6231 $this->mOutput
->setRevisionTimestampUsed( $timestamp ); // unadjusted time zone
6233 # The cryptic '' timezone parameter tells to use the site-default
6234 # timezone offset instead of the user settings.
6235 # Since this value will be saved into the parser cache, served
6236 # to other users, and potentially even used inside links and such,
6237 # it needs to be consistent for all visitors.
6238 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
6240 return $this->mRevisionTimestamp
;
6244 * Get the name of the user that edited the last revision
6246 * @return string User name
6248 public function getRevisionUser() {
6249 if ( is_null( $this->mRevisionUser
) ) {
6250 $revObject = $this->getRevisionObject();
6252 # if this template is subst: the revision id will be blank,
6253 # so just use the current user's name
6255 $this->mRevisionUser
= $revObject->getUserText();
6256 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6257 $this->mRevisionUser
= $this->getUser()->getName();
6260 return $this->mRevisionUser
;
6264 * Get the size of the revision
6266 * @return int|null Revision size
6268 public function getRevisionSize() {
6269 if ( is_null( $this->mRevisionSize
) ) {
6270 $revObject = $this->getRevisionObject();
6272 # if this variable is subst: the revision id will be blank,
6273 # so just use the parser input size, because the own substituation
6274 # will change the size.
6276 $this->mRevisionSize
= $revObject->getSize();
6278 $this->mRevisionSize
= $this->mInputSize
;
6281 return $this->mRevisionSize
;
6285 * Mutator for $mDefaultSort
6287 * @param string $sort New value
6289 public function setDefaultSort( $sort ) {
6290 $this->mDefaultSort
= $sort;
6291 $this->mOutput
->setProperty( 'defaultsort', $sort );
6295 * Accessor for $mDefaultSort
6296 * Will use the empty string if none is set.
6298 * This value is treated as a prefix, so the
6299 * empty string is equivalent to sorting by
6304 public function getDefaultSort() {
6305 if ( $this->mDefaultSort
!== false ) {
6306 return $this->mDefaultSort
;
6313 * Accessor for $mDefaultSort
6314 * Unlike getDefaultSort(), will return false if none is set
6316 * @return string|bool
6318 public function getCustomDefaultSort() {
6319 return $this->mDefaultSort
;
6322 private static function getSectionNameFromStrippedText( $text ) {
6323 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6324 $text = Sanitizer
::decodeCharReferences( $text );
6325 $text = self
::normalizeSectionName( $text );
6329 private static function makeAnchor( $sectionName ) {
6330 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
6333 private function makeLegacyAnchor( $sectionName ) {
6334 $fragmentMode = $this->svcOptions
->get( 'FragmentMode' );
6335 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
6336 // ForAttribute() and ForLink() are the same for legacy encoding
6337 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
6339 $id = Sanitizer
::escapeIdForLink( $sectionName );
6346 * Try to guess the section anchor name based on a wikitext fragment
6347 * presumably extracted from a heading, for example "Header" from
6350 * @param string $text
6351 * @return string Anchor (starting with '#')
6353 public function guessSectionNameFromWikiText( $text ) {
6354 # Strip out wikitext links(they break the anchor)
6355 $text = $this->stripSectionName( $text );
6356 $sectionName = self
::getSectionNameFromStrippedText( $text );
6357 return self
::makeAnchor( $sectionName );
6361 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6362 * instead, if possible. For use in redirects, since various versions
6363 * of Microsoft browsers interpret Location: headers as something other
6364 * than UTF-8, resulting in breakage.
6366 * @param string $text The section name
6367 * @return string Anchor (starting with '#')
6369 public function guessLegacySectionNameFromWikiText( $text ) {
6370 # Strip out wikitext links(they break the anchor)
6371 $text = $this->stripSectionName( $text );
6372 $sectionName = self
::getSectionNameFromStrippedText( $text );
6373 return $this->makeLegacyAnchor( $sectionName );
6377 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6378 * @param string $text Section name (plain text)
6379 * @return string Anchor (starting with '#')
6381 public static function guessSectionNameFromStrippedText( $text ) {
6382 $sectionName = self
::getSectionNameFromStrippedText( $text );
6383 return self
::makeAnchor( $sectionName );
6387 * Apply the same normalization as code making links to this section would
6389 * @param string $text
6392 private static function normalizeSectionName( $text ) {
6393 # T90902: ensure the same normalization is applied for IDs as to links
6394 /** @var MediaWikiTitleCodec $titleParser */
6395 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
6396 '@phan-var MediaWikiTitleCodec $titleParser';
6399 $parts = $titleParser->splitTitleString( "#$text" );
6400 } catch ( MalformedTitleException
$ex ) {
6403 return $parts['fragment'];
6407 * Strips a text string of wikitext for use in a section anchor
6409 * Accepts a text string and then removes all wikitext from the
6410 * string and leaves only the resultant text (i.e. the result of
6411 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6412 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6413 * to create valid section anchors by mimicing the output of the
6414 * parser when headings are parsed.
6416 * @param string $text Text string to be stripped of wikitext
6417 * for use in a Section anchor
6418 * @return string Filtered text string
6420 public function stripSectionName( $text ) {
6421 # Strip internal link markup
6422 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6423 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6425 # Strip external link markup
6426 # @todo FIXME: Not tolerant to blank link text
6427 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6428 # on how many empty links there are on the page - need to figure that out.
6429 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6431 # Parse wikitext quotes (italics & bold)
6432 $text = $this->doQuotes( $text );
6435 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6440 * strip/replaceVariables/unstrip for preprocessor regression testing
6442 * @param string $text
6443 * @param Title $title
6444 * @param ParserOptions $options
6445 * @param int $outputType
6448 * @deprecated since 1.34; should not be used outside parser class.
6450 public function testSrvus( $text, Title
$title, ParserOptions
$options,
6451 $outputType = self
::OT_HTML
6453 wfDeprecated( __METHOD__
, '1.34' );
6454 return $this->fuzzTestSrvus( $text, $title, $options, $outputType );
6458 * Strip/replaceVariables/unstrip for preprocessor regression testing
6460 * @param string $text
6461 * @param Title $title
6462 * @param ParserOptions $options
6463 * @param int $outputType
6467 private function fuzzTestSrvus( $text, Title
$title, ParserOptions
$options,
6468 $outputType = self
::OT_HTML
6470 $magicScopeVariable = $this->lock();
6471 $this->startParse( $title, $options, $outputType, true );
6473 $text = $this->replaceVariables( $text );
6474 $text = $this->mStripState
->unstripBoth( $text );
6475 $text = Sanitizer
::removeHTMLtags( $text );
6480 * @param string $text
6481 * @param Title $title
6482 * @param ParserOptions $options
6484 * @deprecated since 1.34; should not be used outside parser class.
6486 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6487 wfDeprecated( __METHOD__
, '1.34' );
6488 return $this->fuzzTestPst( $text, $title, $options );
6492 * @param string $text
6493 * @param Title $title
6494 * @param ParserOptions $options
6497 private function fuzzTestPst( $text, Title
$title, ParserOptions
$options ) {
6498 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6502 * @param string $text
6503 * @param Title $title
6504 * @param ParserOptions $options
6506 * @deprecated since 1.34; should not be used outside parser class.
6508 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6509 wfDeprecated( __METHOD__
, '1.34' );
6510 return $this->fuzzTestPreprocess( $text, $title, $options );
6514 * @param string $text
6515 * @param Title $title
6516 * @param ParserOptions $options
6519 private function fuzzTestPreprocess( $text, Title
$title, ParserOptions
$options ) {
6520 return $this->fuzzTestSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6524 * Call a callback function on all regions of the given text that are not
6525 * inside strip markers, and replace those regions with the return value
6526 * of the callback. For example, with input:
6530 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6531 * two strings will be replaced with the value returned by the callback in
6535 * @param callable $callback
6539 public function markerSkipCallback( $s, $callback ) {
6542 while ( $i < strlen( $s ) ) {
6543 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6544 if ( $markerStart === false ) {
6545 $out .= call_user_func( $callback, substr( $s, $i ) );
6548 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6549 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6550 if ( $markerEnd === false ) {
6551 $out .= substr( $s, $markerStart );
6554 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6555 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6564 * Remove any strip markers found in the given text.
6566 * @param string $text
6569 public function killMarkers( $text ) {
6570 return $this->mStripState
->killMarkers( $text );
6574 * Save the parser state required to convert the given half-parsed text to
6575 * HTML. "Half-parsed" in this context means the output of
6576 * recursiveTagParse() or internalParse(). This output has strip markers
6577 * from replaceVariables (extensionSubstitution() etc.), and link
6578 * placeholders from replaceLinkHolders().
6580 * Returns an array which can be serialized and stored persistently. This
6581 * array can later be loaded into another parser instance with
6582 * unserializeHalfParsedText(). The text can then be safely incorporated into
6583 * the return value of a parser hook.
6585 * @deprecated since 1.31
6586 * @param string $text
6590 public function serializeHalfParsedText( $text ) {
6591 wfDeprecated( __METHOD__
, '1.31' );
6594 'version' => self
::HALF_PARSED_VERSION
,
6595 'stripState' => $this->mStripState
->getSubState( $text ),
6596 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6602 * Load the parser state given in the $data array, which is assumed to
6603 * have been generated by serializeHalfParsedText(). The text contents is
6604 * extracted from the array, and its markers are transformed into markers
6605 * appropriate for the current Parser instance. This transformed text is
6606 * returned, and can be safely included in the return value of a parser
6609 * If the $data array has been stored persistently, the caller should first
6610 * check whether it is still valid, by calling isValidHalfParsedText().
6612 * @deprecated since 1.31
6613 * @param array $data Serialized data
6614 * @throws MWException
6617 public function unserializeHalfParsedText( $data ) {
6618 wfDeprecated( __METHOD__
, '1.31' );
6619 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6620 throw new MWException( __METHOD__
. ': invalid version' );
6623 # First, extract the strip state.
6624 $texts = [ $data['text'] ];
6625 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6627 # Now renumber links
6628 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6630 # Should be good to go.
6635 * Returns true if the given array, presumed to be generated by
6636 * serializeHalfParsedText(), is compatible with the current version of the
6639 * @deprecated since 1.31
6640 * @param array $data
6644 public function isValidHalfParsedText( $data ) {
6645 wfDeprecated( __METHOD__
, '1.31' );
6646 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6650 * Parsed a width param of imagelink like 300px or 200x300px
6652 * @param string $value
6653 * @param bool $parseHeight
6658 public static function parseWidthParam( $value, $parseHeight = true ) {
6659 $parsedWidthParam = [];
6660 if ( $value === '' ) {
6661 return $parsedWidthParam;
6664 # (T15500) In both cases (width/height and width only),
6665 # permit trailing "px" for backward compatibility.
6666 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6667 $width = intval( $m[1] );
6668 $height = intval( $m[2] );
6669 $parsedWidthParam['width'] = $width;
6670 $parsedWidthParam['height'] = $height;
6671 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6672 $width = intval( $value );
6673 $parsedWidthParam['width'] = $width;
6675 return $parsedWidthParam;
6679 * Lock the current instance of the parser.
6681 * This is meant to stop someone from calling the parser
6682 * recursively and messing up all the strip state.
6684 * @throws MWException If parser is in a parse
6685 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6687 protected function lock() {
6688 if ( $this->mInParse
) {
6689 throw new MWException( "Parser state cleared while parsing. "
6690 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6693 // Save the backtrace when locking, so that if some code tries locking again,
6694 // we can print the lock owner's backtrace for easier debugging
6696 $this->mInParse
= $e->getTraceAsString();
6698 $recursiveCheck = new ScopedCallback( function () {
6699 $this->mInParse
= false;
6702 return $recursiveCheck;
6706 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6708 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6709 * or if there is more than one <p/> tag in the input HTML.
6711 * @param string $html
6715 public static function stripOuterParagraph( $html ) {
6717 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '</p>' ) === false ) {
6725 * Return this parser if it is not doing anything, otherwise
6726 * get a fresh parser. You can use this method by doing
6727 * $newParser = $oldParser->getFreshParser(), or more simply
6728 * $oldParser->getFreshParser()->parse( ... );
6729 * if you're unsure if $oldParser is safe to use.
6732 * @return Parser A parser object that is not parsing anything
6734 public function getFreshParser() {
6735 if ( $this->mInParse
) {
6736 return $this->factory
->create();
6743 * Set's up the PHP implementation of OOUI for use in this request
6744 * and instructs OutputPage to enable OOUI for itself.
6748 public function enableOOUI() {
6749 OutputPage
::setupOOUI();
6750 $this->mOutput
->setEnableOOUI( true );
6754 * @param string $flag
6755 * @param string $reason
6757 protected function setOutputFlag( $flag, $reason ) {
6758 $this->mOutput
->setFlag( $flag );
6759 $name = $this->mTitle
->getPrefixedText();
6760 $this->logger
->debug( __METHOD__
. ": set $flag flag on '$name'; $reason" );