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 initialiseVariables()
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->initialiseVariables();
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()
1056 public function getConverterLanguage() {
1057 wfDeprecated( __METHOD__
, '1.32' );
1058 return $this->getTargetLanguage();
1062 * Get a User object either from $this->mUser, if set, or from the
1063 * ParserOptions object otherwise
1067 public function getUser() {
1068 if ( !is_null( $this->mUser
) ) {
1069 return $this->mUser
;
1071 return $this->mOptions
->getUser();
1075 * Get a preprocessor object
1077 * @return Preprocessor
1079 public function getPreprocessor() {
1080 if ( !isset( $this->mPreprocessor
) ) {
1081 $class = $this->svcOptions
->get( 'preprocessorClass' );
1082 $this->mPreprocessor
= new $class( $this );
1084 return $this->mPreprocessor
;
1088 * Get a LinkRenderer instance to make links with
1091 * @return LinkRenderer
1093 public function getLinkRenderer() {
1094 // XXX We make the LinkRenderer with current options and then cache it forever
1095 if ( !$this->mLinkRenderer
) {
1096 $this->mLinkRenderer
= $this->linkRendererFactory
->create();
1097 $this->mLinkRenderer
->setStubThreshold(
1098 $this->getOptions()->getStubThreshold()
1102 return $this->mLinkRenderer
;
1106 * Get the MagicWordFactory that this Parser is using
1109 * @return MagicWordFactory
1111 public function getMagicWordFactory() {
1112 return $this->magicWordFactory
;
1116 * Get the content language that this Parser is using
1121 public function getContentLanguage() {
1122 return $this->contLang
;
1126 * Replaces all occurrences of HTML-style comments and the given tags
1127 * in the text with a random marker and returns the next text. The output
1128 * parameter $matches will be an associative array filled with data in
1135 * [ 'param' => 'x' ],
1136 * '<element param="x">tag content</element>' ]
1139 * @param array $elements List of element names. Comments are always extracted.
1140 * @param string $text Source text string.
1141 * @param array &$matches Out parameter, Array: extracted tags
1142 * @return string Stripped text
1144 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1149 $taglist = implode( '|', $elements );
1150 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
1152 while ( $text != '' ) {
1153 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1155 if ( count( $p ) < 5 ) {
1158 if ( count( $p ) > 5 ) {
1166 list( , $element, $attributes, $close, $inside ) = $p;
1169 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1170 $stripped .= $marker;
1172 if ( $close === '/>' ) {
1173 # Empty element tag, <tag />
1178 if ( $element === '!--' ) {
1181 $end = "/(<\\/$element\\s*>)/i";
1183 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1185 if ( count( $q ) < 3 ) {
1186 # No end tag -- let it run out to the end of the text.
1190 list( , $tail, $text ) = $q;
1194 $matches[$marker] = [ $element,
1196 Sanitizer
::decodeTagAttributes( $attributes ),
1197 "<$element$attributes$close$content$tail" ];
1203 * Get a list of strippable XML-like elements
1207 public function getStripList() {
1208 return $this->mStripList
;
1212 * Get the StripState
1214 * @return StripState
1216 public function getStripState() {
1217 return $this->mStripState
;
1221 * Add an item to the strip state
1222 * Returns the unique tag which must be inserted into the stripped text
1223 * The tag will be replaced with the original text in unstrip()
1225 * @param string $text
1229 public function insertStripItem( $text ) {
1230 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1231 $this->mMarkerIndex++
;
1232 $this->mStripState
->addGeneral( $marker, $text );
1237 * parse the wiki syntax used to render tables
1240 * @param string $text
1243 public function doTableStuff( $text ) {
1244 $lines = StringUtils
::explode( "\n", $text );
1246 $td_history = []; # Is currently a td tag open?
1247 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1248 $tr_history = []; # Is currently a tr tag open?
1249 $tr_attributes = []; # history of tr attributes
1250 $has_opened_tr = []; # Did this table open a <tr> element?
1251 $indent_level = 0; # indent level of the table
1253 foreach ( $lines as $outLine ) {
1254 $line = trim( $outLine );
1256 if ( $line === '' ) { # empty line, go to next line
1257 $out .= $outLine . "\n";
1261 $first_character = $line[0];
1262 $first_two = substr( $line, 0, 2 );
1265 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1266 # First check if we are starting a new table
1267 $indent_level = strlen( $matches[1] );
1269 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1270 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1272 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1273 array_push( $td_history, false );
1274 array_push( $last_tag_history, '' );
1275 array_push( $tr_history, false );
1276 array_push( $tr_attributes, '' );
1277 array_push( $has_opened_tr, false );
1278 } elseif ( count( $td_history ) == 0 ) {
1279 # Don't do any of the following
1280 $out .= $outLine . "\n";
1282 } elseif ( $first_two === '|}' ) {
1283 # We are ending a table
1284 $line = '</table>' . substr( $line, 2 );
1285 $last_tag = array_pop( $last_tag_history );
1287 if ( !array_pop( $has_opened_tr ) ) {
1288 $line = "<tr><td></td></tr>{$line}";
1291 if ( array_pop( $tr_history ) ) {
1292 $line = "</tr>{$line}";
1295 if ( array_pop( $td_history ) ) {
1296 $line = "</{$last_tag}>{$line}";
1298 array_pop( $tr_attributes );
1299 if ( $indent_level > 0 ) {
1300 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1304 } elseif ( $first_two === '|-' ) {
1305 # Now we have a table row
1306 $line = preg_replace( '#^\|-+#', '', $line );
1308 # Whats after the tag is now only attributes
1309 $attributes = $this->mStripState
->unstripBoth( $line );
1310 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1311 array_pop( $tr_attributes );
1312 array_push( $tr_attributes, $attributes );
1315 $last_tag = array_pop( $last_tag_history );
1316 array_pop( $has_opened_tr );
1317 array_push( $has_opened_tr, true );
1319 if ( array_pop( $tr_history ) ) {
1323 if ( array_pop( $td_history ) ) {
1324 $line = "</{$last_tag}>{$line}";
1328 array_push( $tr_history, false );
1329 array_push( $td_history, false );
1330 array_push( $last_tag_history, '' );
1331 } elseif ( $first_character === '|'
1332 ||
$first_character === '!'
1333 ||
$first_two === '|+'
1335 # This might be cell elements, td, th or captions
1336 if ( $first_two === '|+' ) {
1337 $first_character = '+';
1338 $line = substr( $line, 2 );
1340 $line = substr( $line, 1 );
1343 // Implies both are valid for table headings.
1344 if ( $first_character === '!' ) {
1345 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1348 # Split up multiple cells on the same line.
1349 # FIXME : This can result in improper nesting of tags processed
1350 # by earlier parser steps.
1351 $cells = explode( '||', $line );
1355 # Loop through each table cell
1356 foreach ( $cells as $cell ) {
1358 if ( $first_character !== '+' ) {
1359 $tr_after = array_pop( $tr_attributes );
1360 if ( !array_pop( $tr_history ) ) {
1361 $previous = "<tr{$tr_after}>\n";
1363 array_push( $tr_history, true );
1364 array_push( $tr_attributes, '' );
1365 array_pop( $has_opened_tr );
1366 array_push( $has_opened_tr, true );
1369 $last_tag = array_pop( $last_tag_history );
1371 if ( array_pop( $td_history ) ) {
1372 $previous = "</{$last_tag}>\n{$previous}";
1375 if ( $first_character === '|' ) {
1377 } elseif ( $first_character === '!' ) {
1379 } elseif ( $first_character === '+' ) {
1380 $last_tag = 'caption';
1385 array_push( $last_tag_history, $last_tag );
1387 # A cell could contain both parameters and data
1388 $cell_data = explode( '|', $cell, 2 );
1390 # T2553: Note that a '|' inside an invalid link should not
1391 # be mistaken as delimiting cell parameters
1392 # Bug T153140: Neither should language converter markup.
1393 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1394 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1395 } elseif ( count( $cell_data ) == 1 ) {
1396 // Whitespace in cells is trimmed
1397 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1399 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1400 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1401 // Whitespace in cells is trimmed
1402 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1406 array_push( $td_history, true );
1409 $out .= $outLine . "\n";
1412 # Closing open td, tr && table
1413 while ( count( $td_history ) > 0 ) {
1414 if ( array_pop( $td_history ) ) {
1417 if ( array_pop( $tr_history ) ) {
1420 if ( !array_pop( $has_opened_tr ) ) {
1421 $out .= "<tr><td></td></tr>\n";
1424 $out .= "</table>\n";
1427 # Remove trailing line-ending (b/c)
1428 if ( substr( $out, -1 ) === "\n" ) {
1429 $out = substr( $out, 0, -1 );
1432 # special case: don't return empty table
1433 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1441 * Helper function for parse() that transforms wiki markup into half-parsed
1442 * HTML. Only called for $mOutputType == self::OT_HTML.
1446 * @param string $text The text to parse
1447 * @param-taint $text escapes_html
1448 * @param bool $isMain Whether this is being called from the main parse() function
1449 * @param PPFrame|bool $frame A pre-processor frame
1453 public function internalParse( $text, $isMain = true, $frame = false ) {
1456 // Avoid PHP 7.1 warning from passing $this by reference
1459 # Hook to suspend the parser in this state
1460 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1464 # if $frame is provided, then use $frame for replacing any variables
1466 # use frame depth to infer how include/noinclude tags should be handled
1467 # depth=0 means this is the top-level document; otherwise it's an included document
1468 if ( !$frame->depth
) {
1471 $flag = self
::PTD_FOR_INCLUSION
;
1473 $dom = $this->preprocessToDom( $text, $flag );
1474 $text = $frame->expand( $dom );
1476 # if $frame is not provided, then use old-style replaceVariables
1477 $text = $this->replaceVariables( $text );
1480 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1481 $text = Sanitizer
::removeHTMLtags(
1483 [ $this, 'attributeStripCallback' ],
1485 array_keys( $this->mTransparentTagHooks
),
1487 [ $this, 'addTrackingCategory' ]
1489 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1491 # Tables need to come after variable replacement for things to work
1492 # properly; putting them before other transformations should keep
1493 # exciting things like link expansions from showing up in surprising
1495 $text = $this->doTableStuff( $text );
1497 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1499 $text = $this->doDoubleUnderscore( $text );
1501 $text = $this->doHeadings( $text );
1502 $text = $this->replaceInternalLinks( $text );
1503 $text = $this->doAllQuotes( $text );
1504 $text = $this->replaceExternalLinks( $text );
1506 # replaceInternalLinks may sometimes leave behind
1507 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1508 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1510 $text = $this->doMagicLinks( $text );
1511 $text = $this->formatHeadings( $text, $origText, $isMain );
1517 * Helper function for parse() that transforms half-parsed HTML into fully
1520 * @param string $text
1521 * @param bool $isMain
1522 * @param bool $linestart
1525 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1526 $text = $this->mStripState
->unstripGeneral( $text );
1528 // Avoid PHP 7.1 warning from passing $this by reference
1532 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1535 # Clean up special characters, only run once, next-to-last before doBlockLevels
1536 $text = Sanitizer
::armorFrenchSpaces( $text );
1538 $text = $this->doBlockLevels( $text, $linestart );
1540 $this->replaceLinkHolders( $text );
1543 * The input doesn't get language converted if
1545 * b) Content isn't converted
1546 * c) It's a conversion table
1547 * d) it is an interface message (which is in the user language)
1549 if ( !( $this->mOptions
->getDisableContentConversion()
1550 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1551 && !$this->mOptions
->getInterfaceMessage()
1553 # The position of the convert() call should not be changed. it
1554 # assumes that the links are all replaced and the only thing left
1555 # is the <nowiki> mark.
1556 $text = $this->getTargetLanguage()->convert( $text );
1559 $text = $this->mStripState
->unstripNoWiki( $text );
1562 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1565 $text = $this->replaceTransparentTags( $text );
1566 $text = $this->mStripState
->unstripGeneral( $text );
1568 $text = Sanitizer
::normalizeCharReferences( $text );
1570 if ( MWTidy
::isEnabled() ) {
1571 if ( $this->mOptions
->getTidy() ) {
1572 $text = MWTidy
::tidy( $text );
1575 # attempt to sanitize at least some nesting problems
1576 # (T4702 and quite a few others)
1577 # This code path is buggy and deprecated!
1578 wfDeprecated( 'disabling tidy', '1.33' );
1580 # ''Something [http://www.cool.com cool''] -->
1581 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1582 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1583 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1584 # fix up an anchor inside another anchor, only
1585 # at least for a single single nested link (T5695)
1586 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1587 '\\1\\2</a>\\3</a>\\1\\4</a>',
1588 # fix div inside inline elements- doBlockLevels won't wrap a line which
1589 # contains a div, so fix it up here; replace
1590 # div with escaped text
1591 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1592 '\\1\\3<div\\5>\\6</div>\\8\\9',
1593 # remove empty italic or bold tag pairs, some
1594 # introduced by rules above
1595 '/<([bi])><\/\\1>/' => '',
1598 $text = preg_replace(
1599 array_keys( $tidyregs ),
1600 array_values( $tidyregs ),
1605 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1612 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1613 * magic external links.
1618 * @param string $text
1622 public function doMagicLinks( $text ) {
1623 $prots = wfUrlProtocolsWithoutProtRel();
1624 $urlChar = self
::EXT_LINK_URL_CLASS
;
1625 $addr = self
::EXT_LINK_ADDR
;
1626 $space = self
::SPACE_NOT_NL
; # non-newline space
1627 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1628 $spaces = "$space++"; # possessive match of 1 or more spaces
1629 $text = preg_replace_callback(
1631 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1632 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1633 (\b # m[3]: Free external links
1635 ($addr$urlChar*) # m[4]: Post-protocol path
1637 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1639 \bISBN $spaces ( # m[6]: ISBN, capture number
1640 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1641 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1642 [0-9Xx] # check digit
1644 )!xu", [ $this, 'magicLinkCallback' ], $text );
1649 * @throws MWException
1651 * @return string HTML
1653 public function magicLinkCallback( $m ) {
1654 if ( isset( $m[1] ) && $m[1] !== '' ) {
1657 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1660 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1661 # Free external link
1662 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1663 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1665 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1666 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1671 $cssClass = 'mw-magiclink-rfc';
1672 $trackingCat = 'magiclink-tracking-rfc';
1674 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1675 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1679 $urlmsg = 'pubmedurl';
1680 $cssClass = 'mw-magiclink-pmid';
1681 $trackingCat = 'magiclink-tracking-pmid';
1684 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1685 substr( $m[0], 0, 20 ) . '"' );
1687 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1688 $this->addTrackingCategory( $trackingCat );
1689 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1690 } elseif ( isset( $m[6] ) && $m[6] !== ''
1691 && $this->mOptions
->getMagicISBNLinks()
1695 $space = self
::SPACE_NOT_NL
; # non-newline space
1696 $isbn = preg_replace( "/$space/", ' ', $isbn );
1697 $num = strtr( $isbn, [
1702 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1703 return $this->getLinkRenderer()->makeKnownLink(
1704 SpecialPage
::getTitleFor( 'Booksources', $num ),
1707 'class' => 'internal mw-magiclink-isbn',
1708 'title' => false // suppress title attribute
1717 * Make a free external link, given a user-supplied URL
1719 * @param string $url
1720 * @param int $numPostProto
1721 * The number of characters after the protocol.
1722 * @return string HTML
1725 public function makeFreeExternalLink( $url, $numPostProto ) {
1728 # The characters '<' and '>' (which were escaped by
1729 # removeHTMLtags()) should not be included in
1730 # URLs, per RFC 2396.
1731 # Make terminate a URL as well (bug T84937)
1734 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1739 $trail = substr( $url, $m2[0][1] ) . $trail;
1740 $url = substr( $url, 0, $m2[0][1] );
1743 # Move trailing punctuation to $trail
1745 # If there is no left bracket, then consider right brackets fair game too
1746 if ( strpos( $url, '(' ) === false ) {
1750 $urlRev = strrev( $url );
1751 $numSepChars = strspn( $urlRev, $sep );
1752 # Don't break a trailing HTML entity by moving the ; into $trail
1753 # This is in hot code, so use substr_compare to avoid having to
1754 # create a new string object for the comparison
1755 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1756 # more optimization: instead of running preg_match with a $
1757 # anchor, which can be slow, do the match on the reversed
1758 # string starting at the desired offset.
1759 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1760 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1764 if ( $numSepChars ) {
1765 $trail = substr( $url, -$numSepChars ) . $trail;
1766 $url = substr( $url, 0, -$numSepChars );
1769 # Verify that we still have a real URL after trail removal, and
1770 # not just lone protocol
1771 if ( strlen( $trail ) >= $numPostProto ) {
1772 return $url . $trail;
1775 $url = Sanitizer
::cleanUrl( $url );
1777 # Is this an external image?
1778 $text = $this->maybeMakeExternalImage( $url );
1779 if ( $text === false ) {
1780 # Not an image, make a link
1781 $text = Linker
::makeExternalLink( $url,
1782 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1784 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1785 # Register it in the output object...
1786 $this->mOutput
->addExternalLink( $url );
1788 return $text . $trail;
1792 * Parse headers and return html
1796 * @param string $text
1800 public function doHeadings( $text ) {
1801 for ( $i = 6; $i >= 1; --$i ) {
1802 $h = str_repeat( '=', $i );
1803 // Trim non-newline whitespace from headings
1804 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1805 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1811 * Replace single quotes with HTML markup
1814 * @param string $text
1816 * @return string The altered text
1818 public function doAllQuotes( $text ) {
1820 $lines = StringUtils
::explode( "\n", $text );
1821 foreach ( $lines as $line ) {
1822 $outtext .= $this->doQuotes( $line ) . "\n";
1824 $outtext = substr( $outtext, 0, -1 );
1829 * Helper function for doAllQuotes()
1831 * @param string $text
1835 public function doQuotes( $text ) {
1836 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1837 $countarr = count( $arr );
1838 if ( $countarr == 1 ) {
1842 // First, do some preliminary work. This may shift some apostrophes from
1843 // being mark-up to being text. It also counts the number of occurrences
1844 // of bold and italics mark-ups.
1847 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1848 $thislen = strlen( $arr[$i] );
1849 // If there are ever four apostrophes, assume the first is supposed to
1850 // be text, and the remaining three constitute mark-up for bold text.
1851 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1852 if ( $thislen == 4 ) {
1853 $arr[$i - 1] .= "'";
1856 } elseif ( $thislen > 5 ) {
1857 // If there are more than 5 apostrophes in a row, assume they're all
1858 // text except for the last 5.
1859 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1860 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1864 // Count the number of occurrences of bold and italics mark-ups.
1865 if ( $thislen == 2 ) {
1867 } elseif ( $thislen == 3 ) {
1869 } elseif ( $thislen == 5 ) {
1875 // If there is an odd number of both bold and italics, it is likely
1876 // that one of the bold ones was meant to be an apostrophe followed
1877 // by italics. Which one we cannot know for certain, but it is more
1878 // likely to be one that has a single-letter word before it.
1879 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1880 $firstsingleletterword = -1;
1881 $firstmultiletterword = -1;
1883 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1884 if ( strlen( $arr[$i] ) == 3 ) {
1885 $x1 = substr( $arr[$i - 1], -1 );
1886 $x2 = substr( $arr[$i - 1], -2, 1 );
1887 if ( $x1 === ' ' ) {
1888 if ( $firstspace == -1 ) {
1891 } elseif ( $x2 === ' ' ) {
1892 $firstsingleletterword = $i;
1893 // if $firstsingleletterword is set, we don't
1894 // look at the other options, so we can bail early.
1896 } elseif ( $firstmultiletterword == -1 ) {
1897 $firstmultiletterword = $i;
1902 // If there is a single-letter word, use it!
1903 if ( $firstsingleletterword > -1 ) {
1904 $arr[$firstsingleletterword] = "''";
1905 $arr[$firstsingleletterword - 1] .= "'";
1906 } elseif ( $firstmultiletterword > -1 ) {
1907 // If not, but there's a multi-letter word, use that one.
1908 $arr[$firstmultiletterword] = "''";
1909 $arr[$firstmultiletterword - 1] .= "'";
1910 } elseif ( $firstspace > -1 ) {
1911 // ... otherwise use the first one that has neither.
1912 // (notice that it is possible for all three to be -1 if, for example,
1913 // there is only one pentuple-apostrophe in the line)
1914 $arr[$firstspace] = "''";
1915 $arr[$firstspace - 1] .= "'";
1919 // Now let's actually convert our apostrophic mush to HTML!
1924 foreach ( $arr as $r ) {
1925 if ( ( $i %
2 ) == 0 ) {
1926 if ( $state === 'both' ) {
1932 $thislen = strlen( $r );
1933 if ( $thislen == 2 ) {
1934 if ( $state === 'i' ) {
1937 } elseif ( $state === 'bi' ) {
1940 } elseif ( $state === 'ib' ) {
1941 $output .= '</b></i><b>';
1943 } elseif ( $state === 'both' ) {
1944 $output .= '<b><i>' . $buffer . '</i>';
1946 } else { // $state can be 'b' or ''
1950 } elseif ( $thislen == 3 ) {
1951 if ( $state === 'b' ) {
1954 } elseif ( $state === 'bi' ) {
1955 $output .= '</i></b><i>';
1957 } elseif ( $state === 'ib' ) {
1960 } elseif ( $state === 'both' ) {
1961 $output .= '<i><b>' . $buffer . '</b>';
1963 } else { // $state can be 'i' or ''
1967 } elseif ( $thislen == 5 ) {
1968 if ( $state === 'b' ) {
1969 $output .= '</b><i>';
1971 } elseif ( $state === 'i' ) {
1972 $output .= '</i><b>';
1974 } elseif ( $state === 'bi' ) {
1975 $output .= '</i></b>';
1977 } elseif ( $state === 'ib' ) {
1978 $output .= '</b></i>';
1980 } elseif ( $state === 'both' ) {
1981 $output .= '<i><b>' . $buffer . '</b></i>';
1983 } else { // ($state == '')
1991 // Now close all remaining tags. Notice that the order is important.
1992 if ( $state === 'b' ||
$state === 'ib' ) {
1995 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1998 if ( $state === 'bi' ) {
2001 // There might be lonely ''''', so make sure we have a buffer
2002 if ( $state === 'both' && $buffer ) {
2003 $output .= '<b><i>' . $buffer . '</i></b>';
2009 * Replace external links (REL)
2011 * Note: this is all very hackish and the order of execution matters a lot.
2012 * Make sure to run tests/parser/parserTests.php if you change this code.
2016 * @param string $text
2018 * @throws MWException
2021 public function replaceExternalLinks( $text ) {
2022 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
2023 // @phan-suppress-next-line PhanTypeComparisonFromArray See phan issue #3161
2024 if ( $bits === false ) {
2025 throw new MWException( "PCRE needs to be compiled with "
2026 . "--enable-unicode-properties in order for MediaWiki to function" );
2028 $s = array_shift( $bits );
2031 while ( $i < count( $bits ) ) {
2034 $text = $bits[$i++
];
2035 $trail = $bits[$i++
];
2037 # The characters '<' and '>' (which were escaped by
2038 # removeHTMLtags()) should not be included in
2039 # URLs, per RFC 2396.
2041 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
2042 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
2043 $url = substr( $url, 0, $m2[0][1] );
2046 # If the link text is an image URL, replace it with an <img> tag
2047 # This happened by accident in the original parser, but some people used it extensively
2048 $img = $this->maybeMakeExternalImage( $text );
2049 if ( $img !== false ) {
2055 # Set linktype for CSS
2058 # No link text, e.g. [http://domain.tld/some.link]
2059 if ( $text == '' ) {
2061 $langObj = $this->getTargetLanguage();
2062 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
2063 $linktype = 'autonumber';
2065 # Have link text, e.g. [http://domain.tld/some.link text]s
2067 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
2070 // Excluding protocol-relative URLs may avoid many false positives.
2071 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
2072 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
2075 $url = Sanitizer
::cleanUrl( $url );
2077 # Use the encoded URL
2078 # This means that users can paste URLs directly into the text
2079 # Funny characters like ö aren't valid in URLs anyway
2080 # This was changed in August 2004
2081 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
2082 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
2084 # Register link in the output object.
2085 $this->mOutput
->addExternalLink( $url );
2092 * Get the rel attribute for a particular external link.
2095 * @param string|bool $url Optional URL, to extract the domain from for rel =>
2096 * nofollow if appropriate
2097 * @param LinkTarget|null $title Optional LinkTarget, for wgNoFollowNsExceptions lookups
2098 * @return string|null Rel attribute for $url
2100 public static function getExternalLinkRel( $url = false, $title = null ) {
2101 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
2102 $ns = $title ?
$title->getNamespace() : false;
2103 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
2104 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
2112 * Get an associative array of additional HTML attributes appropriate for a
2113 * particular external link. This currently may include rel => nofollow
2114 * (depending on configuration, namespace, and the URL's domain) and/or a
2115 * target attribute (depending on configuration).
2117 * @param string $url URL to extract the domain from for rel =>
2118 * nofollow if appropriate
2119 * @return array Associative array of HTML attributes
2121 public function getExternalLinkAttribs( $url ) {
2123 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
2125 $target = $this->mOptions
->getExternalLinkTarget();
2127 $attribs['target'] = $target;
2128 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
2129 // T133507. New windows can navigate parent cross-origin.
2130 // Including noreferrer due to lacking browser
2131 // support of noopener. Eventually noreferrer should be removed.
2132 if ( $rel !== '' ) {
2135 $rel .= 'noreferrer noopener';
2138 $attribs['rel'] = $rel;
2143 * Replace unusual escape codes in a URL with their equivalent characters
2145 * This generally follows the syntax defined in RFC 3986, with special
2146 * consideration for HTTP query strings.
2148 * @param string $url
2151 public static function normalizeLinkUrl( $url ) {
2152 # Test for RFC 3986 IPv6 syntax
2153 $scheme = '[a-z][a-z0-9+.-]*:';
2154 $userinfo = '(?:[a-z0-9\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*';
2155 $ipv6Host = '\\[((?:[0-9a-f:]|%3[0-A]|%[46][1-6])+)\\]';
2156 if ( preg_match( "<^(?:{$scheme})?//(?:{$userinfo}@)?{$ipv6Host}(?:[:/?#].*|)$>i", $url, $m ) &&
2157 IP
::isValid( rawurldecode( $m[1] ) )
2159 $isIPv6 = rawurldecode( $m[1] );
2164 # Make sure unsafe characters are encoded
2165 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2167 return rawurlencode( $m[0] );
2173 $end = strlen( $url );
2175 # Fragment part - 'fragment'
2176 $start = strpos( $url, '#' );
2177 if ( $start !== false && $start < $end ) {
2178 $ret = self
::normalizeUrlComponent(
2179 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2183 # Query part - 'query' minus &=+;
2184 $start = strpos( $url, '?' );
2185 if ( $start !== false && $start < $end ) {
2186 $ret = self
::normalizeUrlComponent(
2187 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2191 # Scheme and path part - 'pchar'
2192 # (we assume no userinfo or encoded colons in the host)
2193 $ret = self
::normalizeUrlComponent(
2194 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2197 if ( $isIPv6 !== false ) {
2198 $ipv6Host = "%5B({$isIPv6})%5D";
2199 $ret = preg_replace(
2200 "<^((?:{$scheme})?//(?:{$userinfo}@)?){$ipv6Host}(?=[:/?#]|$)>i",
2209 private static function normalizeUrlComponent( $component, $unsafe ) {
2210 $callback = function ( $matches ) use ( $unsafe ) {
2211 $char = urldecode( $matches[0] );
2212 $ord = ord( $char );
2213 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2217 # Leave it escaped, but use uppercase for a-f
2218 return strtoupper( $matches[0] );
2221 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2225 * make an image if it's allowed, either through the global
2226 * option, through the exception, or through the on-wiki whitelist
2228 * @param string $url
2232 private function maybeMakeExternalImage( $url ) {
2233 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2234 $imagesexception = !empty( $imagesfrom );
2236 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2237 if ( $imagesexception && is_array( $imagesfrom ) ) {
2238 $imagematch = false;
2239 foreach ( $imagesfrom as $match ) {
2240 if ( strpos( $url, $match ) === 0 ) {
2245 } elseif ( $imagesexception ) {
2246 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2248 $imagematch = false;
2251 if ( $this->mOptions
->getAllowExternalImages()
2252 ||
( $imagesexception && $imagematch )
2254 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2256 $text = Linker
::makeExternalImage( $url );
2259 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2260 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2262 $whitelist = explode(
2264 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2267 foreach ( $whitelist as $entry ) {
2268 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2269 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2272 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2273 # Image matches a whitelist entry
2274 $text = Linker
::makeExternalImage( $url );
2283 * Process [[ ]] wikilinks
2287 * @return string Processed text
2291 public function replaceInternalLinks( $s ) {
2292 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2297 * Process [[ ]] wikilinks (RIL)
2299 * @throws MWException
2300 * @return LinkHolderArray
2304 public function replaceInternalLinks2( &$s ) {
2305 static $tc = false, $e1, $e1_img;
2306 # the % is needed to support urlencoded titles as well
2308 $tc = Title
::legalChars() . '#%';
2309 # Match a link having the form [[namespace:link|alternate]]trail
2310 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2311 # Match cases where there is no "]]", which might still be images
2312 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2315 $holders = new LinkHolderArray( $this );
2317 # split the entire text string on occurrences of [[
2318 $a = StringUtils
::explode( '[[', ' ' . $s );
2319 # get the first element (all text up to first [[), and remove the space we added
2322 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2323 $s = substr( $s, 1 );
2325 if ( is_null( $this->mTitle
) ) {
2326 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2328 $nottalk = !$this->mTitle
->isTalkPage();
2330 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2332 if ( $useLinkPrefixExtension ) {
2333 # Match the end of a line for a word that's not followed by whitespace,
2334 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2335 $charset = $this->contLang
->linkPrefixCharset();
2336 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2338 if ( preg_match( $e2, $s, $m ) ) {
2339 $first_prefix = $m[2];
2341 $first_prefix = false;
2347 $useSubpages = $this->areSubpagesAllowed();
2349 # Loop for each link
2350 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2351 # Check for excessive memory usage
2352 if ( $holders->isBig() ) {
2354 # Do the existence check, replace the link holders and clear the array
2355 $holders->replace( $s );
2359 if ( $useLinkPrefixExtension ) {
2360 if ( preg_match( $e2, $s, $m ) ) {
2361 list( , $s, $prefix ) = $m;
2366 if ( $first_prefix ) {
2367 $prefix = $first_prefix;
2368 $first_prefix = false;
2372 $might_be_img = false;
2374 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2376 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2377 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2378 # the real problem is with the $e1 regex
2380 # Still some problems for cases where the ] is meant to be outside punctuation,
2381 # and no image is in sight. See T4095.
2383 && substr( $m[3], 0, 1 ) === ']'
2384 && strpos( $text, '[' ) !== false
2386 $text .= ']'; # so that replaceExternalLinks($text) works later
2387 $m[3] = substr( $m[3], 1 );
2389 # fix up urlencoded title texts
2390 if ( strpos( $m[1], '%' ) !== false ) {
2391 # Should anchors '#' also be rejected?
2392 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2395 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2396 # Invalid, but might be an image with a link in its caption
2397 $might_be_img = true;
2399 if ( strpos( $m[1], '%' ) !== false ) {
2400 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2403 } else { # Invalid form; output directly
2404 $s .= $prefix . '[[' . $line;
2408 $origLink = ltrim( $m[1], ' ' );
2410 # Don't allow internal links to pages containing
2411 # PROTO: where PROTO is a valid URL protocol; these
2412 # should be external links.
2413 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2414 $s .= $prefix . '[[' . $line;
2418 # Make subpage if necessary
2419 if ( $useSubpages ) {
2420 $link = $this->maybeDoSubpageLink( $origLink, $text );
2425 // \x7f isn't a default legal title char, so most likely strip
2426 // markers will force us into the "invalid form" path above. But,
2427 // just in case, let's assert that xmlish tags aren't valid in
2428 // the title position.
2429 $unstrip = $this->mStripState
->killMarkers( $link );
2430 $noMarkers = ( $unstrip === $link );
2432 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2433 if ( $nt === null ) {
2434 $s .= $prefix . '[[' . $line;
2438 $ns = $nt->getNamespace();
2439 $iw = $nt->getInterwiki();
2441 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2443 if ( $might_be_img ) { # if this is actually an invalid link
2444 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2447 # look at the next 'line' to see if we can close it there
2449 $next_line = $a->current();
2450 if ( $next_line === false ||
$next_line === null ) {
2453 $m = explode( ']]', $next_line, 3 );
2454 if ( count( $m ) == 3 ) {
2455 # the first ]] closes the inner link, the second the image
2457 $text .= "[[{$m[0]}]]{$m[1]}";
2460 } elseif ( count( $m ) == 2 ) {
2461 # if there's exactly one ]] that's fine, we'll keep looking
2462 $text .= "[[{$m[0]}]]{$m[1]}";
2464 # if $next_line is invalid too, we need look no further
2465 $text .= '[[' . $next_line;
2470 # we couldn't find the end of this imageLink, so output it raw
2471 # but don't ignore what might be perfectly normal links in the text we've examined
2472 $holders->merge( $this->replaceInternalLinks2( $text ) );
2473 $s .= "{$prefix}[[$link|$text";
2474 # note: no $trail, because without an end, there *is* no trail
2477 } else { # it's not an image, so output it raw
2478 $s .= "{$prefix}[[$link|$text";
2479 # note: no $trail, because without an end, there *is* no trail
2484 $wasblank = ( $text == '' );
2488 # Strip off leading ':'
2489 $text = substr( $text, 1 );
2492 # T6598 madness. Handle the quotes only if they come from the alternate part
2493 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2494 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2495 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2496 $text = $this->doQuotes( $text );
2499 # Link not escaped by : , create the various objects
2500 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2503 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2504 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2505 in_array( $iw, $this->svcOptions
->get( 'ExtraInterlanguageLinkPrefixes' ) )
2508 # T26502: filter duplicates
2509 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2510 $this->mLangLinkLanguages
[$iw] = true;
2511 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2515 * Strip the whitespace interwiki links produce, see T10897
2517 $s = rtrim( $s . $prefix ) . $trail; # T175416
2521 if ( $ns == NS_FILE
) {
2522 if ( !$this->badFileLookup
->isBadFile( $nt->getDBkey(), $this->mTitle
) ) {
2524 # if no parameters were passed, $text
2525 # becomes something like "File:Foo.png",
2526 # which we don't want to pass on to the
2530 # recursively parse links inside the image caption
2531 # actually, this will parse them in any other parameters, too,
2532 # but it might be hard to fix that, and it doesn't matter ATM
2533 $text = $this->replaceExternalLinks( $text );
2534 $holders->merge( $this->replaceInternalLinks2( $text ) );
2536 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2537 $s .= $prefix . $this->armorLinks(
2538 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2541 } elseif ( $ns == NS_CATEGORY
) {
2543 * Strip the whitespace Category links produce, see T2087
2545 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2548 $sortkey = $this->getDefaultSort();
2552 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2553 $sortkey = str_replace( "\n", '', $sortkey );
2554 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2555 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2561 # Self-link checking. For some languages, variants of the title are checked in
2562 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2563 # for linking to a different variant.
2564 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2565 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2569 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2570 # @todo FIXME: Should do batch file existence checks, see comment below
2571 if ( $ns == NS_MEDIA
) {
2572 # Give extensions a chance to select the file revision for us
2575 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2576 [ $this, $nt, &$options, &$descQuery ] );
2577 # Fetch and register the file (file title may be different via hooks)
2578 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2579 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2580 $s .= $prefix . $this->armorLinks(
2581 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2585 # Some titles, such as valid special pages or files in foreign repos, should
2586 # be shown as bluelinks even though they're not included in the page table
2587 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2588 # batch file existence checks for NS_FILE and NS_MEDIA
2589 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2590 $this->mOutput
->addLink( $nt );
2591 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2593 # Links will be added to the output link list after checking
2594 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2601 * Render a forced-blue link inline; protect against double expansion of
2602 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2603 * Since this little disaster has to split off the trail text to avoid
2604 * breaking URLs in the following text without breaking trails on the
2605 * wiki links, it's been made into a horrible function.
2608 * @param string $text
2609 * @param string $trail
2610 * @param string $prefix
2611 * @return string HTML-wikitext mix oh yuck
2613 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2614 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2616 if ( $text == '' ) {
2617 $text = htmlspecialchars( $nt->getPrefixedText() );
2620 $link = $this->getLinkRenderer()->makeKnownLink(
2621 $nt, new HtmlArmor( "$prefix$text$inside" )
2624 return $this->armorLinks( $link ) . $trail;
2628 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2629 * going to go through further parsing steps before inline URL expansion.
2631 * Not needed quite as much as it used to be since free links are a bit
2632 * more sensible these days. But bracketed links are still an issue.
2634 * @param string $text More-or-less HTML
2635 * @return string Less-or-more HTML with NOPARSE bits
2637 public function armorLinks( $text ) {
2638 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2639 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2643 * Return true if subpage links should be expanded on this page.
2646 public function areSubpagesAllowed() {
2647 # Some namespaces don't allow subpages
2648 return $this->nsInfo
->hasSubpages( $this->mTitle
->getNamespace() );
2652 * Handle link to subpage if necessary
2654 * @param string $target The source of the link
2655 * @param string &$text The link text, modified as necessary
2656 * @return string The full name of the link
2659 public function maybeDoSubpageLink( $target, &$text ) {
2660 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2664 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2666 * @param string $text
2667 * @param bool $linestart Whether or not this is at the start of a line.
2669 * @return string The lists rendered as HTML
2671 public function doBlockLevels( $text, $linestart ) {
2672 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2676 * Return value of a magic variable (like PAGENAME)
2680 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2681 * @param bool|PPFrame $frame
2683 * @throws MWException
2686 public function getVariableValue( $index, $frame = false ) {
2687 if ( is_null( $this->mTitle
) ) {
2688 // If no title set, bad things are going to happen
2689 // later. Title should always be set since this
2690 // should only be called in the middle of a parse
2691 // operation (but the unit-tests do funky stuff)
2692 throw new MWException( __METHOD__
. ' Should only be '
2693 . ' called while parsing (no title set)' );
2696 // Avoid PHP 7.1 warning from passing $this by reference
2700 * Some of these require message or data lookups and can be
2701 * expensive to check many times.
2704 Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) &&
2705 isset( $this->mVarCache
[$index] )
2707 return $this->mVarCache
[$index];
2710 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2711 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2713 $pageLang = $this->getFunctionLang();
2719 case 'currentmonth':
2720 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2722 case 'currentmonth1':
2723 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2725 case 'currentmonthname':
2726 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2728 case 'currentmonthnamegen':
2729 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2731 case 'currentmonthabbrev':
2732 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2735 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2738 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2741 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2744 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2746 case 'localmonthname':
2747 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2749 case 'localmonthnamegen':
2750 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2752 case 'localmonthabbrev':
2753 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2756 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2759 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2762 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2765 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2767 case 'fullpagename':
2768 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2770 case 'fullpagenamee':
2771 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2774 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2776 case 'subpagenamee':
2777 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2779 case 'rootpagename':
2780 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2782 case 'rootpagenamee':
2783 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2786 $this->mTitle
->getRootText()
2789 case 'basepagename':
2790 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2792 case 'basepagenamee':
2793 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2796 $this->mTitle
->getBaseText()
2799 case 'talkpagename':
2800 if ( $this->mTitle
->canHaveTalkPage() ) {
2801 $talkPage = $this->mTitle
->getTalkPage();
2802 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2807 case 'talkpagenamee':
2808 if ( $this->mTitle
->canHaveTalkPage() ) {
2809 $talkPage = $this->mTitle
->getTalkPage();
2810 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2815 case 'subjectpagename':
2816 $subjPage = $this->mTitle
->getSubjectPage();
2817 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2819 case 'subjectpagenamee':
2820 $subjPage = $this->mTitle
->getSubjectPage();
2821 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2823 case 'pageid': // requested in T25427
2824 # Inform the edit saving system that getting the canonical output
2825 # after page insertion requires a parse that used that exact page ID
2826 $this->setOutputFlag( 'vary-page-id', '{{PAGEID}} used' );
2827 $value = $this->mTitle
->getArticleID();
2829 $value = $this->mOptions
->getSpeculativePageId();
2831 $this->mOutput
->setSpeculativePageIdUsed( $value );
2837 $this->svcOptions
->get( 'MiserMode' ) &&
2838 !$this->mOptions
->getInterfaceMessage() &&
2839 // @TODO: disallow this word on all namespaces
2840 $this->nsInfo
->isContent( $this->mTitle
->getNamespace() )
2842 // Use a stub result instead of the actual revision ID in order to avoid
2843 // double parses on page save but still allow preview detection (T137900)
2844 if ( $this->getRevisionId() ||
$this->mOptions
->getSpeculativeRevId() ) {
2847 $this->setOutputFlag( 'vary-revision-exists', '{{REVISIONID}} used' );
2851 # Inform the edit saving system that getting the canonical output after
2852 # revision insertion requires a parse that used that exact revision ID
2853 $this->setOutputFlag( 'vary-revision-id', '{{REVISIONID}} used' );
2854 $value = $this->getRevisionId();
2855 if ( $value === 0 ) {
2856 $rev = $this->getRevisionObject();
2857 $value = $rev ?
$rev->getId() : $value;
2860 $value = $this->mOptions
->getSpeculativeRevId();
2862 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2868 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2870 case 'revisionday2':
2871 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2873 case 'revisionmonth':
2874 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2876 case 'revisionmonth1':
2877 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2879 case 'revisionyear':
2880 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2882 case 'revisiontimestamp':
2883 $value = $this->getRevisionTimestampSubstring( 0, 14, self
::MAX_TTS
, $index );
2885 case 'revisionuser':
2886 # Inform the edit saving system that getting the canonical output after
2887 # revision insertion requires a parse that used the actual user ID
2888 $this->setOutputFlag( 'vary-user', '{{REVISIONUSER}} used' );
2889 $value = $this->getRevisionUser();
2891 case 'revisionsize':
2892 $value = $this->getRevisionSize();
2895 $value = str_replace( '_', ' ',
2896 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2899 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2901 case 'namespacenumber':
2902 $value = $this->mTitle
->getNamespace();
2905 $value = $this->mTitle
->canHaveTalkPage()
2906 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2910 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2912 case 'subjectspace':
2913 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2915 case 'subjectspacee':
2916 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2918 case 'currentdayname':
2919 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2922 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2925 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2928 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2931 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2932 # int to remove the padding
2933 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2936 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2938 case 'localdayname':
2939 $value = $pageLang->getWeekdayName(
2940 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2944 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2947 $value = $pageLang->time(
2948 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2954 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2957 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2958 # int to remove the padding
2959 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2962 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2964 case 'numberofarticles':
2965 $value = $pageLang->formatNum( SiteStats
::articles() );
2967 case 'numberoffiles':
2968 $value = $pageLang->formatNum( SiteStats
::images() );
2970 case 'numberofusers':
2971 $value = $pageLang->formatNum( SiteStats
::users() );
2973 case 'numberofactiveusers':
2974 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2976 case 'numberofpages':
2977 $value = $pageLang->formatNum( SiteStats
::pages() );
2979 case 'numberofadmins':
2980 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2982 case 'numberofedits':
2983 $value = $pageLang->formatNum( SiteStats
::edits() );
2985 case 'currenttimestamp':
2986 $value = wfTimestamp( TS_MW
, $ts );
2988 case 'localtimestamp':
2989 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2991 case 'currentversion':
2992 $value = SpecialVersion
::getVersion();
2995 return $this->svcOptions
->get( 'ArticlePath' );
2997 return $this->svcOptions
->get( 'Sitename' );
2999 return $this->svcOptions
->get( 'Server' );
3001 return $this->svcOptions
->get( 'ServerName' );
3003 return $this->svcOptions
->get( 'ScriptPath' );
3005 return $this->svcOptions
->get( 'StylePath' );
3006 case 'directionmark':
3007 return $pageLang->getDirMark();
3008 case 'contentlanguage':
3009 return $this->svcOptions
->get( 'LanguageCode' );
3010 case 'pagelanguage':
3011 $value = $pageLang->getCode();
3013 case 'cascadingsources':
3014 $value = CoreParserFunctions
::cascadingsources( $this );
3019 'ParserGetVariableValueSwitch',
3020 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
3027 $this->mVarCache
[$index] = $value;
3036 * @param int $mtts Max time-till-save; sets vary-revision-timestamp if result changes by then
3037 * @param string $variable Parser variable name
3040 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
3041 # Get the timezone-adjusted timestamp to be used for this revision
3042 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
3043 # Possibly set vary-revision if there is not yet an associated revision
3044 if ( !$this->getRevisionObject() ) {
3045 # Get the timezone-adjusted timestamp $mtts seconds in the future.
3046 # This future is relative to the current time and not that of the
3047 # parser options. The rendered timestamp can be compared to that
3048 # of the timestamp specified by the parser options.
3050 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
3055 if ( $resNow !== $resThen ) {
3056 # Inform the edit saving system that getting the canonical output after
3057 # revision insertion requires a parse that used an actual revision timestamp
3058 $this->setOutputFlag( 'vary-revision-timestamp', "$variable used" );
3066 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3070 public function initialiseVariables() {
3071 $variableIDs = $this->magicWordFactory
->getVariableIDs();
3072 $substIDs = $this->magicWordFactory
->getSubstIDs();
3074 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
3075 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
3079 * Preprocess some wikitext and return the document tree.
3080 * This is the ghost of replace_variables().
3082 * @param string $text The text to parse
3083 * @param int $flags Bitwise combination of:
3084 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3085 * included. Default is to assume a direct page view.
3087 * The generated DOM tree must depend only on the input text and the flags.
3088 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
3090 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3091 * change in the DOM tree for a given text, must be passed through the section identifier
3092 * in the section edit link and thus back to extractSections().
3094 * The output of this function is currently only cached in process memory, but a persistent
3095 * cache may be implemented at a later date which takes further advantage of these strict
3096 * dependency requirements.
3100 public function preprocessToDom( $text, $flags = 0 ) {
3101 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3106 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3112 public static function splitWhitespace( $s ) {
3113 $ltrimmed = ltrim( $s );
3114 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3115 $trimmed = rtrim( $ltrimmed );
3116 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3118 $w2 = substr( $ltrimmed, -$diff );
3122 return [ $w1, $trimmed, $w2 ];
3126 * Replace magic variables, templates, and template arguments
3127 * with the appropriate text. Templates are substituted recursively,
3128 * taking care to avoid infinite loops.
3130 * Note that the substitution depends on value of $mOutputType:
3131 * self::OT_WIKI: only {{subst:}} templates
3132 * self::OT_PREPROCESS: templates but not extension tags
3133 * self::OT_HTML: all templates and extension tags
3135 * @param string $text The text to transform
3136 * @param false|PPFrame|array $frame Object describing the arguments passed to the
3137 * template. Arguments may also be provided as an associative array, as
3138 * was the usual case before MW1.12. Providing arguments this way may be
3139 * useful for extensions wishing to perform variable replacement
3141 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3142 * double-brace expansion.
3145 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3146 # Is there any text? Also, Prevent too big inclusions!
3147 $textSize = strlen( $text );
3148 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3152 if ( $frame === false ) {
3153 $frame = $this->getPreprocessor()->newFrame();
3154 } elseif ( !( $frame instanceof PPFrame
) ) {
3155 $this->logger
->debug(
3156 __METHOD__
. " called using plain parameters instead of " .
3157 "a PPFrame instance. Creating custom frame."
3159 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3162 $dom = $this->preprocessToDom( $text );
3163 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3164 $text = $frame->expand( $dom, $flags );
3170 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3172 * @param array $args
3176 public static function createAssocArgs( $args ) {
3179 foreach ( $args as $arg ) {
3180 $eqpos = strpos( $arg, '=' );
3181 if ( $eqpos === false ) {
3182 $assocArgs[$index++
] = $arg;
3184 $name = trim( substr( $arg, 0, $eqpos ) );
3185 $value = trim( substr( $arg, $eqpos +
1 ) );
3186 if ( $value === false ) {
3189 if ( $name !== false ) {
3190 $assocArgs[$name] = $value;
3199 * Warn the user when a parser limitation is reached
3200 * Will warn at most once the user per limitation type
3202 * The results are shown during preview and run through the Parser (See EditPage.php)
3204 * @param string $limitationType Should be one of:
3205 * 'expensive-parserfunction' (corresponding messages:
3206 * 'expensive-parserfunction-warning',
3207 * 'expensive-parserfunction-category')
3208 * 'post-expand-template-argument' (corresponding messages:
3209 * 'post-expand-template-argument-warning',
3210 * 'post-expand-template-argument-category')
3211 * 'post-expand-template-inclusion' (corresponding messages:
3212 * 'post-expand-template-inclusion-warning',
3213 * 'post-expand-template-inclusion-category')
3214 * 'node-count-exceeded' (corresponding messages:
3215 * 'node-count-exceeded-warning',
3216 * 'node-count-exceeded-category')
3217 * 'expansion-depth-exceeded' (corresponding messages:
3218 * 'expansion-depth-exceeded-warning',
3219 * 'expansion-depth-exceeded-category')
3220 * @param string|int|null $current Current value
3221 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3222 * exceeded, provide the values (optional)
3224 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3225 # does no harm if $current and $max are present but are unnecessary for the message
3226 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3227 # only during preview, and that would split the parser cache unnecessarily.
3228 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3230 $this->mOutput
->addWarning( $warning );
3231 $this->addTrackingCategory( "$limitationType-category" );
3235 * Return the text of a template, after recursively
3236 * replacing any variables or templates within the template.
3238 * @param array $piece The parts of the template
3239 * $piece['title']: the title, i.e. the part before the |
3240 * $piece['parts']: the parameter array
3241 * $piece['lineStart']: whether the brace was at the start of a line
3242 * @param PPFrame $frame The current frame, contains template arguments
3244 * @return string|array The text of the template
3246 public function braceSubstitution( $piece, $frame ) {
3249 // $text has been filled
3251 // wiki markup in $text should be escaped
3253 // $text is HTML, armour it against wikitext transformation
3255 // Force interwiki transclusion to be done in raw mode not rendered
3256 $forceRawInterwiki = false;
3257 // $text is a DOM node needing expansion in a child frame
3258 $isChildObj = false;
3259 // $text is a DOM node needing expansion in the current frame
3260 $isLocalObj = false;
3262 # Title object, where $text came from
3265 # $part1 is the bit before the first |, and must contain only title characters.
3266 # Various prefixes will be stripped from it later.
3267 $titleWithSpaces = $frame->expand( $piece['title'] );
3268 $part1 = trim( $titleWithSpaces );
3271 # Original title text preserved for various purposes
3272 $originalTitle = $part1;
3274 # $args is a list of argument nodes, starting from index 0, not including $part1
3275 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3276 # below won't work b/c this $args isn't an object
3277 $args = ( $piece['parts'] == null ) ?
[] : $piece['parts'];
3279 $profileSection = null; // profile templates
3283 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3285 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3286 # Decide whether to expand template or keep wikitext as-is.
3287 if ( $this->ot
['wiki'] ) {
3288 if ( $substMatch === false ) {
3289 $literal = true; # literal when in PST with no prefix
3291 $literal = false; # expand when in PST with subst: or safesubst:
3294 if ( $substMatch == 'subst' ) {
3295 $literal = true; # literal when not in PST with plain subst:
3297 $literal = false; # expand when not in PST with safesubst: or no prefix
3301 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3308 if ( !$found && $args->getLength() == 0 ) {
3309 $id = $this->mVariables
->matchStartToEnd( $part1 );
3310 if ( $id !== false ) {
3311 $text = $this->getVariableValue( $id, $frame );
3312 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3313 $this->mOutput
->updateCacheExpiry(
3314 $this->magicWordFactory
->getCacheTTL( $id ) );
3320 # MSG, MSGNW and RAW
3323 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3324 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3327 # Remove obsolete MSG:
3328 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3329 $mwMsg->matchStartAndRemove( $part1 );
3333 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3334 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3335 $forceRawInterwiki = true;
3341 $colonPos = strpos( $part1, ':' );
3342 if ( $colonPos !== false ) {
3343 $func = substr( $part1, 0, $colonPos );
3344 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3345 $argsLength = $args->getLength();
3346 for ( $i = 0; $i < $argsLength; $i++
) {
3347 $funcArgs[] = $args->item( $i );
3350 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3352 // Extract any forwarded flags
3353 if ( isset( $result['title'] ) ) {
3354 $title = $result['title'];
3356 if ( isset( $result['found'] ) ) {
3357 $found = $result['found'];
3359 if ( array_key_exists( 'text', $result ) ) {
3361 $text = $result['text'];
3363 if ( isset( $result['nowiki'] ) ) {
3364 $nowiki = $result['nowiki'];
3366 if ( isset( $result['isHTML'] ) ) {
3367 $isHTML = $result['isHTML'];
3369 if ( isset( $result['forceRawInterwiki'] ) ) {
3370 $forceRawInterwiki = $result['forceRawInterwiki'];
3372 if ( isset( $result['isChildObj'] ) ) {
3373 $isChildObj = $result['isChildObj'];
3375 if ( isset( $result['isLocalObj'] ) ) {
3376 $isLocalObj = $result['isLocalObj'];
3381 # Finish mangling title and then check for loops.
3382 # Set $title to a Title object and $titleText to the PDBK
3385 # Split the title into page and subpage
3387 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3388 if ( $part1 !== $relative ) {
3390 $ns = $this->mTitle
->getNamespace();
3392 $title = Title
::newFromText( $part1, $ns );
3394 $titleText = $title->getPrefixedText();
3395 # Check for language variants if the template is not found
3396 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3397 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3399 # Do recursion depth check
3400 $limit = $this->mOptions
->getMaxTemplateDepth();
3401 if ( $frame->depth
>= $limit ) {
3403 $text = '<span class="error">'
3404 . wfMessage( 'parser-template-recursion-depth-warning' )
3405 ->numParams( $limit )->inContentLanguage()->text()
3411 # Load from database
3412 if ( !$found && $title ) {
3413 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3414 if ( !$title->isExternal() ) {
3415 if ( $title->isSpecialPage()
3416 && $this->mOptions
->getAllowSpecialInclusion()
3417 && $this->ot
['html']
3419 $specialPage = $this->specialPageFactory
->getPage( $title->getDBkey() );
3420 // Pass the template arguments as URL parameters.
3421 // "uselang" will have no effect since the Language object
3422 // is forced to the one defined in ParserOptions.
3424 $argsLength = $args->getLength();
3425 for ( $i = 0; $i < $argsLength; $i++
) {
3426 $bits = $args->item( $i )->splitArg();
3427 if ( strval( $bits['index'] ) === '' ) {
3428 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3429 $value = trim( $frame->expand( $bits['value'] ) );
3430 $pageArgs[$name] = $value;
3434 // Create a new context to execute the special page
3435 $context = new RequestContext
;
3436 $context->setTitle( $title );
3437 $context->setRequest( new FauxRequest( $pageArgs ) );
3438 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3439 $context->setUser( $this->getUser() );
3441 // If this page is cached, then we better not be per user.
3442 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3444 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3445 $ret = $this->specialPageFactory
->capturePath( $title, $context, $this->getLinkRenderer() );
3447 $text = $context->getOutput()->getHTML();
3448 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3451 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3452 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3453 $specialPage->maxIncludeCacheTime()
3457 } elseif ( $this->nsInfo
->isNonincludable( $title->getNamespace() ) ) {
3458 $found = false; # access denied
3459 $this->logger
->debug(
3461 ": template inclusion denied for " . $title->getPrefixedDBkey()
3464 list( $text, $title ) = $this->getTemplateDom( $title );
3465 if ( $text !== false ) {
3471 # If the title is valid but undisplayable, make a link to it
3472 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3473 $text = "[[:$titleText]]";
3476 } elseif ( $title->isTrans() ) {
3477 # Interwiki transclusion
3478 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3479 $text = $this->interwikiTransclude( $title, 'render' );
3482 $text = $this->interwikiTransclude( $title, 'raw' );
3483 # Preprocess it like a template
3484 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3490 # Do infinite loop check
3491 # This has to be done after redirect resolution to avoid infinite loops via redirects
3492 if ( !$frame->loopCheck( $title ) ) {
3494 $text = '<span class="error">'
3495 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3497 $this->addTrackingCategory( 'template-loop-category' );
3498 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3499 wfEscapeWikiText( $titleText ) )->text() );
3500 $this->logger
->debug( __METHOD__
. ": template loop broken at '$titleText'" );
3504 # If we haven't found text to substitute by now, we're done
3505 # Recover the source wikitext and return it
3507 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3508 if ( $profileSection ) {
3509 $this->mProfiler
->scopedProfileOut( $profileSection );
3511 return [ 'object' => $text ];
3514 # Expand DOM-style return values in a child frame
3515 if ( $isChildObj ) {
3516 # Clean up argument array
3517 $newFrame = $frame->newChild( $args, $title );
3520 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3521 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3522 # Expansion is eligible for the empty-frame cache
3523 $text = $newFrame->cachedExpand( $titleText, $text );
3525 # Uncached expansion
3526 $text = $newFrame->expand( $text );
3529 if ( $isLocalObj && $nowiki ) {
3530 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3531 $isLocalObj = false;
3534 if ( $profileSection ) {
3535 $this->mProfiler
->scopedProfileOut( $profileSection );
3538 # Replace raw HTML by a placeholder
3540 $text = $this->insertStripItem( $text );
3541 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3542 # Escape nowiki-style return values
3543 $text = wfEscapeWikiText( $text );
3544 } elseif ( is_string( $text )
3545 && !$piece['lineStart']
3546 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3548 # T2529: if the template begins with a table or block-level
3549 # element, it should be treated as beginning a new line.
3550 # This behavior is somewhat controversial.
3551 $text = "\n" . $text;
3554 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3555 # Error, oversize inclusion
3556 if ( $titleText !== false ) {
3557 # Make a working, properly escaped link if possible (T25588)
3558 $text = "[[:$titleText]]";
3560 # This will probably not be a working link, but at least it may
3561 # provide some hint of where the problem is
3562 preg_replace( '/^:/', '', $originalTitle );
3563 $text = "[[:$originalTitle]]";
3565 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3566 . 'post-expand include size too large -->' );
3567 $this->limitationWarn( 'post-expand-template-inclusion' );
3570 if ( $isLocalObj ) {
3571 $ret = [ 'object' => $text ];
3573 $ret = [ 'text' => $text ];
3580 * Call a parser function and return an array with text and flags.
3582 * The returned array will always contain a boolean 'found', indicating
3583 * whether the parser function was found or not. It may also contain the
3585 * text: string|object, resulting wikitext or PP DOM object
3586 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3587 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3588 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3589 * nowiki: bool, wiki markup in $text should be escaped
3592 * @param PPFrame $frame The current frame, contains template arguments
3593 * @param string $function Function name
3594 * @param array $args Arguments to the function
3595 * @throws MWException
3598 public function callParserFunction( $frame, $function, array $args = [] ) {
3599 # Case sensitive functions
3600 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3601 $function = $this->mFunctionSynonyms
[1][$function];
3603 # Case insensitive functions
3604 $function = $this->contLang
->lc( $function );
3605 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3606 $function = $this->mFunctionSynonyms
[0][$function];
3608 return [ 'found' => false ];
3612 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3614 // Avoid PHP 7.1 warning from passing $this by reference
3617 $allArgs = [ &$parser ];
3618 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3619 # Convert arguments to PPNodes and collect for appending to $allArgs
3621 foreach ( $args as $k => $v ) {
3622 if ( $v instanceof PPNode ||
$k === 0 ) {
3625 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3629 # Add a frame parameter, and pass the arguments as an array
3630 $allArgs[] = $frame;
3631 $allArgs[] = $funcArgs;
3633 # Convert arguments to plain text and append to $allArgs
3634 foreach ( $args as $k => $v ) {
3635 if ( $v instanceof PPNode
) {
3636 $allArgs[] = trim( $frame->expand( $v ) );
3637 } elseif ( is_int( $k ) && $k >= 0 ) {
3638 $allArgs[] = trim( $v );
3640 $allArgs[] = trim( "$k=$v" );
3645 $result = $callback( ...$allArgs );
3647 # The interface for function hooks allows them to return a wikitext
3648 # string or an array containing the string and any flags. This mungs
3649 # things around to match what this method should return.
3650 if ( !is_array( $result ) ) {
3656 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3657 $result['text'] = $result[0];
3659 unset( $result[0] );
3666 $preprocessFlags = 0;
3667 if ( isset( $result['noparse'] ) ) {
3668 $noparse = $result['noparse'];
3670 if ( isset( $result['preprocessFlags'] ) ) {
3671 $preprocessFlags = $result['preprocessFlags'];
3675 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3676 $result['isChildObj'] = true;
3683 * Get the semi-parsed DOM representation of a template with a given title,
3684 * and its redirect destination title. Cached.
3686 * @param Title $title
3690 public function getTemplateDom( $title ) {
3691 $cacheTitle = $title;
3692 $titleText = $title->getPrefixedDBkey();
3694 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3695 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3696 $title = Title
::makeTitle( $ns, $dbk );
3697 $titleText = $title->getPrefixedDBkey();
3699 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3700 return [ $this->mTplDomCache
[$titleText], $title ];
3703 # Cache miss, go to the database
3704 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3706 if ( $text === false ) {
3707 $this->mTplDomCache
[$titleText] = false;
3708 return [ false, $title ];
3711 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3712 $this->mTplDomCache
[$titleText] = $dom;
3714 if ( !$title->equals( $cacheTitle ) ) {
3715 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3716 [ $title->getNamespace(), $title->getDBkey() ];
3719 return [ $dom, $title ];
3723 * Fetch the current revision of a given title. Note that the revision
3724 * (and even the title) may not exist in the database, so everything
3725 * contributing to the output of the parser should use this method
3726 * where possible, rather than getting the revisions themselves. This
3727 * method also caches its results, so using it benefits performance.
3730 * @param Title $title
3733 public function fetchCurrentRevisionOfTitle( $title ) {
3734 $cacheKey = $title->getPrefixedDBkey();
3735 if ( !$this->currentRevisionCache
) {
3736 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3738 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3739 $this->currentRevisionCache
->set( $cacheKey,
3740 // Defaults to Parser::statelessFetchRevision()
3741 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3744 return $this->currentRevisionCache
->get( $cacheKey );
3748 * @param Title $title
3752 public function isCurrentRevisionOfTitleCached( $title ) {
3754 $this->currentRevisionCache
&&
3755 $this->currentRevisionCache
->has( $title->getPrefixedText() )
3760 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3761 * without passing them on to it.
3764 * @param Title $title
3765 * @param Parser|bool $parser
3766 * @return Revision|bool False if missing
3768 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3769 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3775 * Fetch the unparsed text of a template and register a reference to it.
3776 * @param Title $title
3777 * @return array ( string or false, Title )
3779 public function fetchTemplateAndTitle( $title ) {
3780 // Defaults to Parser::statelessFetchTemplate()
3781 $templateCb = $this->mOptions
->getTemplateCallback();
3782 $stuff = call_user_func( $templateCb, $title, $this );
3783 $rev = $stuff['revision'] ??
null;
3784 $text = $stuff['text'];
3785 if ( is_string( $stuff['text'] ) ) {
3786 // We use U+007F DELETE to distinguish strip markers from regular text
3787 $text = strtr( $text, "\x7f", "?" );
3789 $finalTitle = $stuff['finalTitle'] ??
$title;
3790 foreach ( ( $stuff['deps'] ??
[] ) as $dep ) {
3791 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3792 if ( $dep['title']->equals( $this->getTitle() ) && $rev instanceof Revision
) {
3793 // Self-transclusion; final result may change based on the new page version
3794 $this->setOutputFlag( 'vary-revision-sha1', 'Self transclusion' );
3795 $this->getOutput()->setRevisionUsedSha1Base36( $rev->getSha1() );
3799 return [ $text, $finalTitle ];
3803 * Fetch the unparsed text of a template and register a reference to it.
3804 * @param Title $title
3805 * @return string|bool
3807 public function fetchTemplate( $title ) {
3808 return $this->fetchTemplateAndTitle( $title )[0];
3812 * Static function to get a template
3813 * Can be overridden via ParserOptions::setTemplateCallback().
3815 * @param Title $title
3816 * @param bool|Parser $parser
3820 public static function statelessFetchTemplate( $title, $parser = false ) {
3821 $text = $skip = false;
3822 $finalTitle = $title;
3826 # Loop to fetch the article, with up to 1 redirect
3827 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3828 # Give extensions a chance to select the revision instead
3829 $id = false; # Assume current
3830 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3831 [ $parser, $title, &$skip, &$id ] );
3837 'page_id' => $title->getArticleID(),
3844 $rev = Revision
::newFromId( $id );
3845 } elseif ( $parser ) {
3846 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3848 $rev = Revision
::newFromTitle( $title );
3850 $rev_id = $rev ?
$rev->getId() : 0;
3851 # If there is no current revision, there is no page
3852 if ( $id === false && !$rev ) {
3853 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3854 $linkCache->addBadLinkObj( $title );
3859 'page_id' => $title->getArticleID(),
3862 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3863 # We fetched a rev from a different title; register it too...
3865 'title' => $rev->getTitle(),
3866 'page_id' => $rev->getPage(),
3872 $content = $rev->getContent();
3873 $text = $content ?
$content->getWikitextForTransclusion() : null;
3875 Hooks
::run( 'ParserFetchTemplate',
3876 [ $parser, $title, $rev, &$text, &$deps ] );
3878 if ( $text === false ||
$text === null ) {
3882 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3883 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3884 lcfirst( $title->getText() ) )->inContentLanguage();
3885 if ( !$message->exists() ) {
3889 $content = $message->content();
3890 $text = $message->plain();
3898 $finalTitle = $title;
3899 $title = $content->getRedirectTarget();
3904 'finalTitle' => $finalTitle,
3910 * Fetch a file and its title and register a reference to it.
3911 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3912 * @param Title $title
3913 * @param array $options Array of options to RepoGroup::findFile
3914 * @return array ( File or false, Title of file )
3916 public function fetchFileAndTitle( $title, $options = [] ) {
3917 $file = $this->fetchFileNoRegister( $title, $options );
3919 $time = $file ?
$file->getTimestamp() : false;
3920 $sha1 = $file ?
$file->getSha1() : false;
3921 # Register the file as a dependency...
3922 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3923 if ( $file && !$title->equals( $file->getTitle() ) ) {
3924 # Update fetched file title
3925 $title = $file->getTitle();
3926 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3928 return [ $file, $title ];
3932 * Helper function for fetchFileAndTitle.
3934 * Also useful if you need to fetch a file but not use it yet,
3935 * for example to get the file's handler.
3937 * @param Title $title
3938 * @param array $options Array of options to RepoGroup::findFile
3941 protected function fetchFileNoRegister( $title, $options = [] ) {
3942 if ( isset( $options['broken'] ) ) {
3943 $file = false; // broken thumbnail forced by hook
3944 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3945 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3946 } else { // get by (name,timestamp)
3947 $file = MediaWikiServices
::getInstance()->getRepoGroup()->findFile( $title, $options );
3953 * Transclude an interwiki link.
3955 * @param Title $title
3956 * @param string $action Usually one of (raw, render)
3960 public function interwikiTransclude( $title, $action ) {
3961 if ( !$this->svcOptions
->get( 'EnableScaryTranscluding' ) ) {
3962 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3965 $url = $title->getFullURL( [ 'action' => $action ] );
3966 if ( strlen( $url ) > 1024 ) {
3967 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3970 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3972 $fname = __METHOD__
;
3973 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3975 $data = $cache->getWithSetCallback(
3976 $cache->makeGlobalKey(
3977 'interwiki-transclude',
3978 ( $wikiId !== false ) ?
$wikiId : 'external',
3981 $this->svcOptions
->get( 'TranscludeCacheExpiry' ),
3982 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3983 $req = MWHttpRequest
::factory( $url, [], $fname );
3985 $status = $req->execute(); // Status object
3986 if ( !$status->isOK() ) {
3987 $ttl = $cache::TTL_UNCACHEABLE
;
3988 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3989 $ttl = min( $cache::TTL_LAGGED
, $ttl );
3993 'text' => $status->isOK() ?
$req->getContent() : null,
3994 'code' => $req->getStatus()
3998 'checkKeys' => ( $wikiId !== false )
3999 ?
[ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
4001 'pcGroup' => 'interwiki-transclude:5',
4002 'pcTTL' => $cache::TTL_PROC_LONG
4006 if ( is_string( $data['text'] ) ) {
4007 $text = $data['text'];
4008 } elseif ( $data['code'] != 200 ) {
4009 // Though we failed to fetch the content, this status is useless.
4010 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
4011 ->params( $url, $data['code'] )->inContentLanguage()->text();
4013 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4020 * Triple brace replacement -- used for template arguments
4023 * @param array $piece
4024 * @param PPFrame $frame
4028 public function argSubstitution( $piece, $frame ) {
4030 $parts = $piece['parts'];
4031 $nameWithSpaces = $frame->expand( $piece['title'] );
4032 $argName = trim( $nameWithSpaces );
4034 $text = $frame->getArgument( $argName );
4035 if ( $text === false && $parts->getLength() > 0
4036 && ( $this->ot
['html']
4038 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4041 # No match in frame, use the supplied default
4042 $object = $parts->item( 0 )->getChildren();
4044 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4045 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4046 $this->limitationWarn( 'post-expand-template-argument' );
4049 if ( $text === false && $object === false ) {
4051 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4053 if ( $error !== false ) {
4056 if ( $object !== false ) {
4057 $ret = [ 'object' => $object ];
4059 $ret = [ 'text' => $text ];
4066 * Return the text to be used for a given extension tag.
4067 * This is the ghost of strip().
4069 * @param array $params Associative array of parameters:
4070 * name PPNode for the tag name
4071 * attr PPNode for unparsed text where tag attributes are thought to be
4072 * attributes Optional associative array of parsed attributes
4073 * inner Contents of extension element
4074 * noClose Original text did not have a close tag
4075 * @param PPFrame $frame
4077 * @throws MWException
4080 public function extensionSubstitution( $params, $frame ) {
4081 static $errorStr = '<span class="error">';
4082 static $errorLen = 20;
4084 $name = $frame->expand( $params['name'] );
4085 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
4086 // Probably expansion depth or node count exceeded. Just punt the
4091 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4092 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
4097 // We can't safely check if the expansion for $content resulted in an
4098 // error, because the content could happen to be the error string
4100 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4102 $marker = self
::MARKER_PREFIX
. "-$name-"
4103 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4105 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4106 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4107 if ( $isFunctionTag ) {
4108 $markerType = 'none';
4110 $markerType = 'general';
4112 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4113 $name = strtolower( $name );
4114 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4115 if ( isset( $params['attributes'] ) ) {
4116 $attributes +
= $params['attributes'];
4119 if ( isset( $this->mTagHooks
[$name] ) ) {
4120 $output = call_user_func_array( $this->mTagHooks
[$name],
4121 [ $content, $attributes, $this, $frame ] );
4122 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4123 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4125 // Avoid PHP 7.1 warning from passing $this by reference
4127 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
4129 $output = '<span class="error">Invalid tag extension name: ' .
4130 htmlspecialchars( $name ) . '</span>';
4133 if ( is_array( $output ) ) {
4136 $output = $flags[0];
4137 if ( isset( $flags['markerType'] ) ) {
4138 $markerType = $flags['markerType'];
4142 if ( is_null( $attrText ) ) {
4145 if ( isset( $params['attributes'] ) ) {
4146 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4147 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4148 htmlspecialchars( $attrValue ) . '"';
4151 if ( $content === null ) {
4152 $output = "<$name$attrText/>";
4154 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4155 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4159 $output = "<$name$attrText>$content$close";
4163 if ( $markerType === 'none' ) {
4165 } elseif ( $markerType === 'nowiki' ) {
4166 $this->mStripState
->addNoWiki( $marker, $output );
4167 } elseif ( $markerType === 'general' ) {
4168 $this->mStripState
->addGeneral( $marker, $output );
4170 throw new MWException( __METHOD__
. ': invalid marker type' );
4176 * Increment an include size counter
4178 * @param string $type The type of expansion
4179 * @param int $size The size of the text
4180 * @return bool False if this inclusion would take it over the maximum, true otherwise
4182 public function incrementIncludeSize( $type, $size ) {
4183 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4186 $this->mIncludeSizes
[$type] +
= $size;
4192 * Increment the expensive function count
4194 * @return bool False if the limit has been exceeded
4196 public function incrementExpensiveFunctionCount() {
4197 $this->mExpensiveFunctionCount++
;
4198 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4202 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4203 * Fills $this->mDoubleUnderscores, returns the modified text
4205 * @param string $text
4209 public function doDoubleUnderscore( $text ) {
4210 # The position of __TOC__ needs to be recorded
4211 $mw = $this->magicWordFactory
->get( 'toc' );
4212 if ( $mw->match( $text ) ) {
4213 $this->mShowToc
= true;
4214 $this->mForceTocPosition
= true;
4216 # Set a placeholder. At the end we'll fill it in with the TOC.
4217 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4219 # Only keep the first one.
4220 $text = $mw->replace( '', $text );
4223 # Now match and remove the rest of them
4224 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4225 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4227 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4228 $this->mOutput
->mNoGallery
= true;
4230 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4231 $this->mShowToc
= false;
4233 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4234 && $this->mTitle
->getNamespace() == NS_CATEGORY
4236 $this->addTrackingCategory( 'hidden-category-category' );
4238 # (T10068) Allow control over whether robots index a page.
4239 # __INDEX__ always overrides __NOINDEX__, see T16899
4240 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4241 $this->mOutput
->setIndexPolicy( 'noindex' );
4242 $this->addTrackingCategory( 'noindex-category' );
4244 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4245 $this->mOutput
->setIndexPolicy( 'index' );
4246 $this->addTrackingCategory( 'index-category' );
4249 # Cache all double underscores in the database
4250 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4251 $this->mOutput
->setProperty( $key, '' );
4258 * @see ParserOutput::addTrackingCategory()
4259 * @param string $msg Message key
4260 * @return bool Whether the addition was successful
4262 public function addTrackingCategory( $msg ) {
4263 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4267 * This function accomplishes several tasks:
4268 * 1) Auto-number headings if that option is enabled
4269 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4270 * 3) Add a Table of contents on the top for users who have enabled the option
4271 * 4) Auto-anchor headings
4273 * It loops through all headlines, collects the necessary data, then splits up the
4274 * string and re-inserts the newly formatted headlines.
4276 * @param string $text
4277 * @param string $origText Original, untouched wikitext
4278 * @param bool $isMain
4279 * @return mixed|string
4282 public function formatHeadings( $text, $origText, $isMain = true ) {
4283 # Inhibit editsection links if requested in the page
4284 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4285 $maybeShowEditLink = false;
4287 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4290 # Get all headlines for numbering them and adding funky stuff like [edit]
4291 # links - this is for later, but we need the number of headlines right now
4292 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4293 # be trimmed here since whitespace in HTML headings is significant.
4295 $numMatches = preg_match_all(
4296 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4301 # if there are fewer than 4 headlines in the article, do not show TOC
4302 # unless it's been explicitly enabled.
4303 $enoughToc = $this->mShowToc
&&
4304 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4306 # Allow user to stipulate that a page should have a "new section"
4307 # link added via __NEWSECTIONLINK__
4308 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4309 $this->mOutput
->setNewSection( true );
4312 # Allow user to remove the "new section"
4313 # link via __NONEWSECTIONLINK__
4314 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4315 $this->mOutput
->hideNewSection( true );
4318 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4319 # override above conditions and always show TOC above first header
4320 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4321 $this->mShowToc
= true;
4329 # Ugh .. the TOC should have neat indentation levels which can be
4330 # passed to the skin functions. These are determined here
4334 $sublevelCount = [];
4340 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4341 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4342 $oldType = $this->mOutputType
;
4343 $this->setOutputType( self
::OT_WIKI
);
4344 $frame = $this->getPreprocessor()->newFrame();
4345 $root = $this->preprocessToDom( $origText );
4346 $node = $root->getFirstChild();
4351 $headlines = $numMatches !== false ?
$matches[3] : [];
4353 $maxTocLevel = $this->svcOptions
->get( 'MaxTocLevel' );
4354 foreach ( $headlines as $headline ) {
4355 $isTemplate = false;
4357 $sectionIndex = false;
4359 $markerMatches = [];
4360 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4361 $serial = $markerMatches[1];
4362 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4363 $isTemplate = ( $titleText != $baseTitleText );
4364 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4368 $prevlevel = $level;
4370 $level = $matches[1][$headlineCount];
4372 if ( $level > $prevlevel ) {
4373 # Increase TOC level
4375 $sublevelCount[$toclevel] = 0;
4376 if ( $toclevel < $maxTocLevel ) {
4377 $prevtoclevel = $toclevel;
4378 $toc .= Linker
::tocIndent();
4381 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4382 # Decrease TOC level, find level to jump to
4384 for ( $i = $toclevel; $i > 0; $i-- ) {
4385 if ( $levelCount[$i] == $level ) {
4386 # Found last matching level
4389 } elseif ( $levelCount[$i] < $level ) {
4390 # Found first matching level below current level
4398 if ( $toclevel < $maxTocLevel ) {
4399 if ( $prevtoclevel < $maxTocLevel ) {
4400 # Unindent only if the previous toc level was shown :p
4401 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4402 $prevtoclevel = $toclevel;
4404 $toc .= Linker
::tocLineEnd();
4408 # No change in level, end TOC line
4409 if ( $toclevel < $maxTocLevel ) {
4410 $toc .= Linker
::tocLineEnd();
4414 $levelCount[$toclevel] = $level;
4416 # count number of headlines for each level
4417 $sublevelCount[$toclevel]++
;
4419 for ( $i = 1; $i <= $toclevel; $i++
) {
4420 if ( !empty( $sublevelCount[$i] ) ) {
4424 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4429 # The safe header is a version of the header text safe to use for links
4431 # Remove link placeholders by the link text.
4432 # <!--LINK number-->
4434 # link text with suffix
4435 # Do this before unstrip since link text can contain strip markers
4436 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4438 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4439 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4441 # Remove any <style> or <script> tags (T198618)
4442 $safeHeadline = preg_replace(
4443 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4448 # Strip out HTML (first regex removes any tag not allowed)
4450 # * <sup> and <sub> (T10393)
4454 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4455 # * <s> and <strike> (T35715)
4456 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4457 # to allow setting directionality in toc items.
4458 $tocline = preg_replace(
4460 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4461 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4467 # Strip '<span></span>', which is the result from the above if
4468 # <span id="foo"></span> is used to produce an additional anchor
4470 $tocline = str_replace( '<span></span>', '', $tocline );
4472 $tocline = trim( $tocline );
4474 # For the anchor, strip out HTML-y stuff period
4475 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4476 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4478 # Save headline for section edit hint before it's escaped
4479 $headlineHint = $safeHeadline;
4481 # Decode HTML entities
4482 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4484 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4486 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4487 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4488 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4489 if ( $fallbackHeadline === $safeHeadline ) {
4490 # No reason to have both (in fact, we can't)
4491 $fallbackHeadline = false;
4494 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4495 # @todo FIXME: We may be changing them depending on the current locale.
4496 $arrayKey = strtolower( $safeHeadline );
4497 if ( $fallbackHeadline === false ) {
4498 $fallbackArrayKey = false;
4500 $fallbackArrayKey = strtolower( $fallbackHeadline );
4503 # Create the anchor for linking from the TOC to the section
4504 $anchor = $safeHeadline;
4505 $fallbackAnchor = $fallbackHeadline;
4506 if ( isset( $refers[$arrayKey] ) ) {
4507 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4508 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4510 $linkAnchor .= "_$i";
4511 $refers["${arrayKey}_$i"] = true;
4513 $refers[$arrayKey] = true;
4515 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4516 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4517 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4518 $fallbackAnchor .= "_$i";
4519 $refers["${fallbackArrayKey}_$i"] = true;
4521 $refers[$fallbackArrayKey] = true;
4524 # Don't number the heading if it is the only one (looks silly)
4525 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4526 # the two are different if the line contains a link
4527 $headline = Html
::element(
4529 [ 'class' => 'mw-headline-number' ],
4531 ) . ' ' . $headline;
4534 if ( $enoughToc && ( !isset( $maxTocLevel ) ||
$toclevel < $maxTocLevel ) ) {
4535 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4536 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4539 # Add the section to the section tree
4540 # Find the DOM node for this header
4541 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4542 while ( $node && !$noOffset ) {
4543 if ( $node->getName() === 'h' ) {
4544 $bits = $node->splitHeading();
4545 if ( $bits['i'] == $sectionIndex ) {
4549 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4550 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4551 $node = $node->getNextSibling();
4554 'toclevel' => $toclevel,
4557 'number' => $numbering,
4558 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4559 'fromtitle' => $titleText,
4560 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4561 'anchor' => $anchor,
4564 # give headline the correct <h#> tag
4565 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4566 // Output edit section links as markers with styles that can be customized by skins
4567 if ( $isTemplate ) {
4568 # Put a T flag in the section identifier, to indicate to extractSections()
4569 # that sections inside <includeonly> should be counted.
4570 $editsectionPage = $titleText;
4571 $editsectionSection = "T-$sectionIndex";
4572 $editsectionContent = null;
4574 $editsectionPage = $this->mTitle
->getPrefixedText();
4575 $editsectionSection = $sectionIndex;
4576 $editsectionContent = $headlineHint;
4578 // We use a bit of pesudo-xml for editsection markers. The
4579 // language converter is run later on. Using a UNIQ style marker
4580 // leads to the converter screwing up the tokens when it
4581 // converts stuff. And trying to insert strip tags fails too. At
4582 // this point all real inputted tags have already been escaped,
4583 // so we don't have to worry about a user trying to input one of
4584 // these markers directly. We use a page and section attribute
4585 // to stop the language converter from converting these
4586 // important bits of data, but put the headline hint inside a
4587 // content block because the language converter is supposed to
4588 // be able to convert that piece of data.
4589 // Gets replaced with html in ParserOutput::getText
4590 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4591 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4592 if ( $editsectionContent !== null ) {
4593 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4600 $head[$headlineCount] = Linker
::makeHeadline( $level,
4601 $matches['attrib'][$headlineCount], $anchor, $headline,
4602 $editlink, $fallbackAnchor );
4607 $this->setOutputType( $oldType );
4609 # Never ever show TOC if no headers
4610 if ( $numVisible < 1 ) {
4615 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4616 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4618 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4619 $this->mOutput
->setTOCHTML( $toc );
4620 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4624 $this->mOutput
->setSections( $tocraw );
4627 # split up and insert constructed headlines
4628 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4631 // build an array of document sections
4633 foreach ( $blocks as $block ) {
4634 // $head is zero-based, sections aren't.
4635 if ( empty( $head[$i - 1] ) ) {
4636 $sections[$i] = $block;
4638 $sections[$i] = $head[$i - 1] . $block;
4642 * Send a hook, one per section.
4643 * The idea here is to be able to make section-level DIVs, but to do so in a
4644 * lower-impact, more correct way than r50769
4647 * $section : the section number
4648 * &$sectionContent : ref to the content of the section
4649 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4651 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4656 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4657 // append the TOC at the beginning
4658 // Top anchor now in skin
4659 $sections[0] .= $toc . "\n";
4662 $full .= implode( '', $sections );
4664 if ( $this->mForceTocPosition
) {
4665 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4672 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4673 * conversion, substituting signatures, {{subst:}} templates, etc.
4675 * @param string $text The text to transform
4676 * @param Title $title The Title object for the current article
4677 * @param User $user The User object describing the current user
4678 * @param ParserOptions $options Parsing options
4679 * @param bool $clearState Whether to clear the parser state first
4680 * @return string The altered wiki markup
4682 public function preSaveTransform( $text, Title
$title, User
$user,
4683 ParserOptions
$options, $clearState = true
4685 if ( $clearState ) {
4686 $magicScopeVariable = $this->lock();
4688 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4689 $this->setUser( $user );
4691 // Strip U+0000 NULL (T159174)
4692 $text = str_replace( "\000", '', $text );
4694 // We still normalize line endings for backwards-compatibility
4695 // with other code that just calls PST, but this should already
4696 // be handled in TextContent subclasses
4697 $text = TextContent
::normalizeLineEndings( $text );
4699 if ( $options->getPreSaveTransform() ) {
4700 $text = $this->pstPass2( $text, $user );
4702 $text = $this->mStripState
->unstripBoth( $text );
4704 $this->setUser( null ); # Reset
4710 * Pre-save transform helper function
4712 * @param string $text
4717 private function pstPass2( $text, $user ) {
4718 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4719 # $this->contLang here in order to give everyone the same signature and use the default one
4720 # rather than the one selected in each user's preferences. (see also T14815)
4721 $ts = $this->mOptions
->getTimestamp();
4722 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4723 $ts = $timestamp->format( 'YmdHis' );
4724 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4726 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4728 # Variable replacement
4729 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4730 $text = $this->replaceVariables( $text );
4732 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4733 # which may corrupt this parser instance via its wfMessage()->text() call-
4736 if ( strpos( $text, '~~~' ) !== false ) {
4737 $sigText = $this->getUserSig( $user );
4738 $text = strtr( $text, [
4740 '~~~~' => "$sigText $d",
4743 # The main two signature forms used above are time-sensitive
4744 $this->setOutputFlag( 'user-signature', 'User signature detected' );
4747 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4748 $tc = '[' . Title
::legalChars() . ']';
4749 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4751 // [[ns:page (context)|]]
4752 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4753 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4754 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4755 // [[ns:page (context), context|]] (using either single or double-width comma)
4756 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4757 // [[|page]] (reverse pipe trick: add context from page title)
4758 $p2 = "/\[\[\\|($tc+)]]/";
4760 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4761 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4762 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4763 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4765 $t = $this->mTitle
->getText();
4767 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4768 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4769 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4770 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4772 # if there's no context, don't bother duplicating the title
4773 $text = preg_replace( $p2, '[[\\1]]', $text );
4780 * Fetch the user's signature text, if any, and normalize to
4781 * validated, ready-to-insert wikitext.
4782 * If you have pre-fetched the nickname or the fancySig option, you can
4783 * specify them here to save a database query.
4784 * Do not reuse this parser instance after calling getUserSig(),
4785 * as it may have changed.
4787 * @param User &$user
4788 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4789 * @param bool|null $fancySig whether the nicknname is the complete signature
4790 * or null to use default value
4793 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4794 $username = $user->getName();
4796 # If not given, retrieve from the user object.
4797 if ( $nickname === false ) {
4798 $nickname = $user->getOption( 'nickname' );
4801 if ( is_null( $fancySig ) ) {
4802 $fancySig = $user->getBoolOption( 'fancysig' );
4805 $nickname = $nickname == null ?
$username : $nickname;
4807 if ( mb_strlen( $nickname ) > $this->svcOptions
->get( 'MaxSigChars' ) ) {
4808 $nickname = $username;
4809 $this->logger
->debug( __METHOD__
. ": $username has overlong signature." );
4810 } elseif ( $fancySig !== false ) {
4811 # Sig. might contain markup; validate this
4812 if ( $this->validateSig( $nickname ) !== false ) {
4813 # Validated; clean up (if needed) and return it
4814 return $this->cleanSig( $nickname, true );
4816 # Failed to validate; fall back to the default
4817 $nickname = $username;
4818 $this->logger
->debug( __METHOD__
. ": $username has bad XML tags in signature." );
4822 # Make sure nickname doesnt get a sig in a sig
4823 $nickname = self
::cleanSigInSig( $nickname );
4825 # If we're still here, make it a link to the user page
4826 $userText = wfEscapeWikiText( $username );
4827 $nickText = wfEscapeWikiText( $nickname );
4828 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4830 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4831 ->title( $this->getTitle() )->text();
4835 * Check that the user's signature contains no bad XML
4837 * @param string $text
4838 * @return string|bool An expanded string, or false if invalid.
4840 public function validateSig( $text ) {
4841 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4845 * Clean up signature text
4847 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4848 * 2) Substitute all transclusions
4850 * @param string $text
4851 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4852 * @return string Signature text
4854 public function cleanSig( $text, $parsing = false ) {
4857 $magicScopeVariable = $this->lock();
4858 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4861 # Option to disable this feature
4862 if ( !$this->mOptions
->getCleanSignatures() ) {
4866 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4867 # => Move this logic to braceSubstitution()
4868 $substWord = $this->magicWordFactory
->get( 'subst' );
4869 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4870 $substText = '{{' . $substWord->getSynonym( 0 );
4872 $text = preg_replace( $substRegex, $substText, $text );
4873 $text = self
::cleanSigInSig( $text );
4874 $dom = $this->preprocessToDom( $text );
4875 $frame = $this->getPreprocessor()->newFrame();
4876 $text = $frame->expand( $dom );
4879 $text = $this->mStripState
->unstripBoth( $text );
4886 * Strip 3, 4 or 5 tildes out of signatures.
4888 * @param string $text
4889 * @return string Signature text with /~{3,5}/ removed
4891 public static function cleanSigInSig( $text ) {
4892 $text = preg_replace( '/~{3,5}/', '', $text );
4897 * Set up some variables which are usually set up in parse()
4898 * so that an external function can call some class members with confidence
4900 * @param Title|null $title
4901 * @param ParserOptions $options
4902 * @param int $outputType
4903 * @param bool $clearState
4904 * @param int|null $revId
4906 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4907 $outputType, $clearState = true, $revId = null
4909 $this->startParse( $title, $options, $outputType, $clearState );
4910 if ( $revId !== null ) {
4911 $this->mRevisionId
= $revId;
4916 * @param Title|null $title
4917 * @param ParserOptions $options
4918 * @param int $outputType
4919 * @param bool $clearState
4921 private function startParse( Title
$title = null, ParserOptions
$options,
4922 $outputType, $clearState = true
4924 $this->setTitle( $title );
4925 $this->mOptions
= $options;
4926 $this->setOutputType( $outputType );
4927 if ( $clearState ) {
4928 $this->clearState();
4933 * Wrapper for preprocess()
4935 * @param string $text The text to preprocess
4936 * @param ParserOptions $options
4937 * @param Title|null $title Title object or null to use $wgTitle
4940 public function transformMsg( $text, $options, $title = null ) {
4941 static $executing = false;
4943 # Guard against infinite recursion
4954 $text = $this->preprocess( $text, $title, $options );
4961 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4962 * The callback should have the following form:
4963 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4965 * Transform and return $text. Use $parser for any required context, e.g. use
4966 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4968 * Hooks may return extended information by returning an array, of which the
4969 * first numbered element (index 0) must be the return string, and all other
4970 * entries are extracted into local variables within an internal function
4971 * in the Parser class.
4973 * This interface (introduced r61913) appears to be undocumented, but
4974 * 'markerType' is used by some core tag hooks to override which strip
4975 * array their results are placed in. **Use great caution if attempting
4976 * this interface, as it is not documented and injudicious use could smash
4977 * private variables.**
4979 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4980 * @param callable $callback The callback function (and object) to use for the tag
4981 * @throws MWException
4982 * @return callable|null The old value of the mTagHooks array associated with the hook
4984 public function setHook( $tag, callable
$callback ) {
4985 $tag = strtolower( $tag );
4986 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4987 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4989 $oldVal = $this->mTagHooks
[$tag] ??
null;
4990 $this->mTagHooks
[$tag] = $callback;
4991 if ( !in_array( $tag, $this->mStripList
) ) {
4992 $this->mStripList
[] = $tag;
4999 * As setHook(), but letting the contents be parsed.
5001 * Transparent tag hooks are like regular XML-style tag hooks, except they
5002 * operate late in the transformation sequence, on HTML instead of wikitext.
5004 * This is probably obsoleted by things dealing with parser frames?
5005 * The only extension currently using it is geoserver.
5008 * @todo better document or deprecate this
5010 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5011 * @param callable $callback The callback function (and object) to use for the tag
5012 * @throws MWException
5013 * @return callable|null The old value of the mTagHooks array associated with the hook
5015 public function setTransparentTagHook( $tag, callable
$callback ) {
5016 $tag = strtolower( $tag );
5017 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5018 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5020 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
5021 $this->mTransparentTagHooks
[$tag] = $callback;
5027 * Remove all tag hooks
5029 public function clearTagHooks() {
5030 $this->mTagHooks
= [];
5031 $this->mFunctionTagHooks
= [];
5032 $this->mStripList
= $this->mDefaultStripList
;
5036 * Create a function, e.g. {{sum:1|2|3}}
5037 * The callback function should have the form:
5038 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5040 * Or with Parser::SFH_OBJECT_ARGS:
5041 * function myParserFunction( $parser, $frame, $args ) { ... }
5043 * The callback may either return the text result of the function, or an array with the text
5044 * in element 0, and a number of flags in the other elements. The names of the flags are
5045 * specified in the keys. Valid flags are:
5046 * found The text returned is valid, stop processing the template. This
5048 * nowiki Wiki markup in the return value should be escaped
5049 * isHTML The returned text is HTML, armour it against wikitext transformation
5051 * @param string $id The magic word ID
5052 * @param callable $callback The callback function (and object) to use
5053 * @param int $flags A combination of the following flags:
5054 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5056 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5057 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5058 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5059 * the arguments, and to control the way they are expanded.
5061 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5062 * arguments, for instance:
5063 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5065 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5066 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5067 * working if/when this is changed.
5069 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5072 * Please read the documentation in includes/parser/Preprocessor.php for more information
5073 * about the methods available in PPFrame and PPNode.
5075 * @throws MWException
5076 * @return string|callable The old callback function for this name, if any
5078 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
5079 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5080 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
5082 # Add to function cache
5083 $mw = $this->magicWordFactory
->get( $id );
5085 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5088 $synonyms = $mw->getSynonyms();
5089 $sensitive = intval( $mw->isCaseSensitive() );
5091 foreach ( $synonyms as $syn ) {
5093 if ( !$sensitive ) {
5094 $syn = $this->contLang
->lc( $syn );
5097 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5100 # Remove trailing colon
5101 if ( substr( $syn, -1, 1 ) === ':' ) {
5102 $syn = substr( $syn, 0, -1 );
5104 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5110 * Get all registered function hook identifiers
5114 public function getFunctionHooks() {
5115 $this->firstCallInit();
5116 return array_keys( $this->mFunctionHooks
);
5120 * Create a tag function, e.g. "<test>some stuff</test>".
5121 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5122 * Unlike parser functions, their content is not preprocessed.
5123 * @param string $tag
5124 * @param callable $callback
5126 * @throws MWException
5129 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
5130 $tag = strtolower( $tag );
5131 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5132 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5134 $old = $this->mFunctionTagHooks
[$tag] ??
null;
5135 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
5137 if ( !in_array( $tag, $this->mStripList
) ) {
5138 $this->mStripList
[] = $tag;
5145 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5146 * Placeholders created in Linker::link()
5148 * @param string &$text
5149 * @param int $options
5151 public function replaceLinkHolders( &$text, $options = 0 ) {
5152 $this->mLinkHolders
->replace( $text );
5156 * Replace "<!--LINK-->" link placeholders with plain text of links
5157 * (not HTML-formatted).
5159 * @param string $text
5162 public function replaceLinkHoldersText( $text ) {
5163 return $this->mLinkHolders
->replaceText( $text );
5167 * Renders an image gallery from a text with one line per image.
5168 * text labels may be given by using |-style alternative text. E.g.
5169 * Image:one.jpg|The number "1"
5170 * Image:tree.jpg|A tree
5171 * given as text will return the HTML of a gallery with two images,
5172 * labeled 'The number "1"' and
5175 * @param string $text
5176 * @param array $params
5177 * @return string HTML
5179 public function renderImageGallery( $text, $params ) {
5181 if ( isset( $params['mode'] ) ) {
5182 $mode = $params['mode'];
5186 $ig = ImageGalleryBase
::factory( $mode );
5187 } catch ( Exception
$e ) {
5188 // If invalid type set, fallback to default.
5189 $ig = ImageGalleryBase
::factory( false );
5192 $ig->setContextTitle( $this->mTitle
);
5193 $ig->setShowBytes( false );
5194 $ig->setShowDimensions( false );
5195 $ig->setShowFilename( false );
5196 $ig->setParser( $this );
5197 $ig->setHideBadImages();
5198 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5200 if ( isset( $params['showfilename'] ) ) {
5201 $ig->setShowFilename( true );
5203 $ig->setShowFilename( false );
5205 if ( isset( $params['caption'] ) ) {
5206 // NOTE: We aren't passing a frame here or below. Frame info
5207 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5208 // See T107332#4030581
5209 $caption = $this->recursiveTagParse( $params['caption'] );
5210 $ig->setCaptionHtml( $caption );
5212 if ( isset( $params['perrow'] ) ) {
5213 $ig->setPerRow( $params['perrow'] );
5215 if ( isset( $params['widths'] ) ) {
5216 $ig->setWidths( $params['widths'] );
5218 if ( isset( $params['heights'] ) ) {
5219 $ig->setHeights( $params['heights'] );
5221 $ig->setAdditionalOptions( $params );
5223 // Avoid PHP 7.1 warning from passing $this by reference
5225 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5227 $lines = StringUtils
::explode( "\n", $text );
5228 foreach ( $lines as $line ) {
5229 # match lines like these:
5230 # Image:someimage.jpg|This is some image
5232 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5234 if ( count( $matches ) == 0 ) {
5238 if ( strpos( $matches[0], '%' ) !== false ) {
5239 $matches[1] = rawurldecode( $matches[1] );
5241 $title = Title
::newFromText( $matches[1], NS_FILE
);
5242 if ( is_null( $title ) ) {
5243 # Bogus title. Ignore these so we don't bomb out later.
5247 # We need to get what handler the file uses, to figure out parameters.
5248 # Note, a hook can overide the file name, and chose an entirely different
5249 # file (which potentially could be of a different type and have different handler).
5252 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5253 [ $this, $title, &$options, &$descQuery ] );
5254 # Don't register it now, as TraditionalImageGallery does that later.
5255 $file = $this->fetchFileNoRegister( $title, $options );
5256 $handler = $file ?
$file->getHandler() : false;
5259 'img_alt' => 'gallery-internal-alt',
5260 'img_link' => 'gallery-internal-link',
5263 $paramMap +
= $handler->getParamMap();
5264 // We don't want people to specify per-image widths.
5265 // Additionally the width parameter would need special casing anyhow.
5266 unset( $paramMap['img_width'] );
5269 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5274 $handlerOptions = [];
5275 if ( isset( $matches[3] ) ) {
5276 // look for an |alt= definition while trying not to break existing
5277 // captions with multiple pipes (|) in it, until a more sensible grammar
5278 // is defined for images in galleries
5280 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5281 // splitting on '|' is a bit odd, and different from makeImage.
5282 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5283 // Protect LanguageConverter markup
5284 $parameterMatches = StringUtils
::delimiterExplode(
5285 '-{', '}-', '|', $matches[3], true /* nested */
5288 foreach ( $parameterMatches as $parameterMatch ) {
5289 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5291 $paramName = $paramMap[$magicName];
5293 switch ( $paramName ) {
5294 case 'gallery-internal-alt':
5295 $alt = $this->stripAltText( $match, false );
5297 case 'gallery-internal-link':
5298 $linkValue = $this->stripAltText( $match, false );
5299 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5300 // Result of LanguageConverter::markNoConversion
5301 // invoked on an external link.
5302 $linkValue = substr( $linkValue, 4, -2 );
5304 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5305 if ( $type === 'link-url' ) {
5307 $this->mOutput
->addExternalLink( $target );
5308 } elseif ( $type === 'link-title' ) {
5309 $link = $target->getLinkURL();
5310 $this->mOutput
->addLink( $target );
5314 // Must be a handler specific parameter.
5315 if ( $handler->validateParam( $paramName, $match ) ) {
5316 $handlerOptions[$paramName] = $match;
5318 // Guess not, consider it as caption.
5319 $this->logger
->debug(
5320 "$parameterMatch failed parameter validation" );
5321 $label = $parameterMatch;
5327 $label = $parameterMatch;
5332 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5334 $html = $ig->toHTML();
5335 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5340 * @param MediaHandler $handler
5343 public function getImageParams( $handler ) {
5345 $handlerClass = get_class( $handler );
5349 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5350 # Initialise static lists
5351 static $internalParamNames = [
5352 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5353 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5354 'bottom', 'text-bottom' ],
5355 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5356 'upright', 'border', 'link', 'alt', 'class' ],
5358 static $internalParamMap;
5359 if ( !$internalParamMap ) {
5360 $internalParamMap = [];
5361 foreach ( $internalParamNames as $type => $names ) {
5362 foreach ( $names as $name ) {
5363 // For grep: img_left, img_right, img_center, img_none,
5364 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5365 // img_bottom, img_text_bottom,
5366 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5367 // img_border, img_link, img_alt, img_class
5368 $magicName = str_replace( '-', '_', "img_$name" );
5369 $internalParamMap[$magicName] = [ $type, $name ];
5374 # Add handler params
5375 $paramMap = $internalParamMap;
5377 $handlerParamMap = $handler->getParamMap();
5378 foreach ( $handlerParamMap as $magic => $paramName ) {
5379 $paramMap[$magic] = [ 'handler', $paramName ];
5382 $this->mImageParams
[$handlerClass] = $paramMap;
5383 $this->mImageParamsMagicArray
[$handlerClass] =
5384 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5386 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5390 * Parse image options text and use it to make an image
5392 * @param Title $title
5393 * @param string $options
5394 * @param LinkHolderArray|bool $holders
5395 * @return string HTML
5397 public function makeImage( $title, $options, $holders = false ) {
5398 # Check if the options text is of the form "options|alt text"
5400 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5401 # * left no resizing, just left align. label is used for alt= only
5402 # * right same, but right aligned
5403 # * none same, but not aligned
5404 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5405 # * center center the image
5406 # * frame Keep original image size, no magnify-button.
5407 # * framed Same as "frame"
5408 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5409 # * upright reduce width for upright images, rounded to full __0 px
5410 # * border draw a 1px border around the image
5411 # * alt Text for HTML alt attribute (defaults to empty)
5412 # * class Set a class for img node
5413 # * link Set the target of the image link. Can be external, interwiki, or local
5414 # vertical-align values (no % or length right now):
5424 # Protect LanguageConverter markup when splitting into parts
5425 $parts = StringUtils
::delimiterExplode(
5426 '-{', '}-', '|', $options, true /* allow nesting */
5429 # Give extensions a chance to select the file revision for us
5432 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5433 [ $this, $title, &$options, &$descQuery ] );
5434 # Fetch and register the file (file title may be different via hooks)
5435 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5438 $handler = $file ?
$file->getHandler() : false;
5440 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5443 $this->addTrackingCategory( 'broken-file-category' );
5446 # Process the input parameters
5448 $params = [ 'frame' => [], 'handler' => [],
5449 'horizAlign' => [], 'vertAlign' => [] ];
5450 $seenformat = false;
5451 foreach ( $parts as $part ) {
5452 $part = trim( $part );
5453 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5455 if ( isset( $paramMap[$magicName] ) ) {
5456 list( $type, $paramName ) = $paramMap[$magicName];
5458 # Special case; width and height come in one variable together
5459 if ( $type === 'handler' && $paramName === 'width' ) {
5460 $parsedWidthParam = self
::parseWidthParam( $value );
5461 if ( isset( $parsedWidthParam['width'] ) ) {
5462 $width = $parsedWidthParam['width'];
5463 if ( $handler->validateParam( 'width', $width ) ) {
5464 $params[$type]['width'] = $width;
5468 if ( isset( $parsedWidthParam['height'] ) ) {
5469 $height = $parsedWidthParam['height'];
5470 if ( $handler->validateParam( 'height', $height ) ) {
5471 $params[$type]['height'] = $height;
5475 # else no validation -- T15436
5477 if ( $type === 'handler' ) {
5478 # Validate handler parameter
5479 $validated = $handler->validateParam( $paramName, $value );
5481 # Validate internal parameters
5482 switch ( $paramName ) {
5486 # @todo FIXME: Possibly check validity here for
5487 # manualthumb? downstream behavior seems odd with
5488 # missing manual thumbs.
5490 $value = $this->stripAltText( $value, $holders );
5493 list( $paramName, $value ) =
5494 $this->parseLinkParameter(
5495 $this->stripAltText( $value, $holders )
5499 if ( $paramName === 'no-link' ) {
5502 if ( ( $paramName === 'link-url' ) && $this->mOptions
->getExternalLinkTarget() ) {
5503 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5510 // use first appearing option, discard others.
5511 $validated = !$seenformat;
5515 # Most other things appear to be empty or numeric...
5516 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5521 $params[$type][$paramName] = $value;
5525 if ( !$validated ) {
5530 # Process alignment parameters
5531 if ( $params['horizAlign'] ) {
5532 $params['frame']['align'] = key( $params['horizAlign'] );
5534 if ( $params['vertAlign'] ) {
5535 $params['frame']['valign'] = key( $params['vertAlign'] );
5538 $params['frame']['caption'] = $caption;
5540 # Will the image be presented in a frame, with the caption below?
5541 $imageIsFramed = isset( $params['frame']['frame'] )
5542 ||
isset( $params['frame']['framed'] )
5543 ||
isset( $params['frame']['thumbnail'] )
5544 ||
isset( $params['frame']['manualthumb'] );
5546 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5547 # came to also set the caption, ordinary text after the image -- which
5548 # makes no sense, because that just repeats the text multiple times in
5549 # screen readers. It *also* came to set the title attribute.
5550 # Now that we have an alt attribute, we should not set the alt text to
5551 # equal the caption: that's worse than useless, it just repeats the
5552 # text. This is the framed/thumbnail case. If there's no caption, we
5553 # use the unnamed parameter for alt text as well, just for the time be-
5554 # ing, if the unnamed param is set and the alt param is not.
5555 # For the future, we need to figure out if we want to tweak this more,
5556 # e.g., introducing a title= parameter for the title; ignoring the un-
5557 # named parameter entirely for images without a caption; adding an ex-
5558 # plicit caption= parameter and preserving the old magic unnamed para-
5560 if ( $imageIsFramed ) { # Framed image
5561 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5562 # No caption or alt text, add the filename as the alt text so
5563 # that screen readers at least get some description of the image
5564 $params['frame']['alt'] = $title->getText();
5566 # Do not set $params['frame']['title'] because tooltips don't make sense
5568 } else { # Inline image
5569 if ( !isset( $params['frame']['alt'] ) ) {
5570 # No alt text, use the "caption" for the alt text
5571 if ( $caption !== '' ) {
5572 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5574 # No caption, fall back to using the filename for the
5576 $params['frame']['alt'] = $title->getText();
5579 # Use the "caption" for the tooltip text
5580 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5582 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5584 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5586 # Linker does the rest
5587 $time = $options['time'] ??
false;
5588 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5589 $time, $descQuery, $this->mOptions
->getThumbSize() );
5591 # Give the handler a chance to modify the parser object
5593 $handler->parserTransformHook( $this, $file );
5600 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5602 * Adds an entry to appropriate link tables.
5605 * @param string $value
5606 * @return array of `[ type, target ]`, where:
5607 * - `type` is one of:
5608 * - `null`: Given value is not a valid link target, use default
5609 * - `'no-link'`: Given value is empty, do not generate a link
5610 * - `'link-url'`: Given value is a valid external link
5611 * - `'link-title'`: Given value is a valid internal link
5613 * - When `type` is `null` or `'no-link'`: `false`
5614 * - When `type` is `'link-url'`: URL string corresponding to given value
5615 * - When `type` is `'link-title'`: Title object corresponding to given value
5617 public function parseLinkParameter( $value ) {
5618 $chars = self
::EXT_LINK_URL_CLASS
;
5619 $addr = self
::EXT_LINK_ADDR
;
5620 $prots = $this->mUrlProtocols
;
5623 if ( $value === '' ) {
5625 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5626 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5627 $this->mOutput
->addExternalLink( $value );
5632 $linkTitle = Title
::newFromText( $value );
5634 $this->mOutput
->addLink( $linkTitle );
5635 $type = 'link-title';
5636 $target = $linkTitle;
5639 return [ $type, $target ];
5643 * @param string $caption
5644 * @param LinkHolderArray|bool $holders
5645 * @return mixed|string
5647 protected function stripAltText( $caption, $holders ) {
5648 # Strip bad stuff out of the title (tooltip). We can't just use
5649 # replaceLinkHoldersText() here, because if this function is called
5650 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5652 $tooltip = $holders->replaceText( $caption );
5654 $tooltip = $this->replaceLinkHoldersText( $caption );
5657 # make sure there are no placeholders in thumbnail attributes
5658 # that are later expanded to html- so expand them now and
5660 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5661 # Compatibility hack! In HTML certain entity references not terminated
5662 # by a semicolon are decoded (but not if we're in an attribute; that's
5663 # how link URLs get away without properly escaping & in queries).
5664 # But wikitext has always required semicolon-termination of entities,
5665 # so encode & where needed to avoid decode of semicolon-less entities.
5667 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5668 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5669 $tooltip = preg_replace( "/
5670 & # 1. entity prefix
5671 (?= # 2. followed by:
5672 (?: # a. one of the legacy semicolon-less named entities
5673 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5674 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5675 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5676 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5677 U(?:acute|circ|grave|uml)|Yacute|
5678 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5679 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5680 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5681 frac(?:1(?:2|4)|34)|
5682 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5683 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5684 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5685 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5686 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5687 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5688 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5689 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5690 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5692 (?:[^;]|$)) # b. and not followed by a semicolon
5693 # S = study, for efficiency
5694 /Sx", '&', $tooltip );
5695 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5701 * Set a flag in the output object indicating that the content is dynamic and
5702 * shouldn't be cached.
5703 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5705 public function disableCache() {
5706 $this->logger
->debug( "Parser output marked as uncacheable." );
5707 if ( !$this->mOutput
) {
5708 throw new MWException( __METHOD__
.
5709 " can only be called when actually parsing something" );
5711 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5715 * Callback from the Sanitizer for expanding items found in HTML attribute
5716 * values, so they can be safely tested and escaped.
5718 * @param string &$text
5719 * @param bool|PPFrame $frame
5722 public function attributeStripCallback( &$text, $frame = false ) {
5723 $text = $this->replaceVariables( $text, $frame );
5724 $text = $this->mStripState
->unstripBoth( $text );
5733 public function getTags() {
5734 $this->firstCallInit();
5736 array_keys( $this->mTransparentTagHooks
),
5737 array_keys( $this->mTagHooks
),
5738 array_keys( $this->mFunctionTagHooks
)
5746 public function getFunctionSynonyms() {
5747 $this->firstCallInit();
5748 return $this->mFunctionSynonyms
;
5755 public function getUrlProtocols() {
5756 return $this->mUrlProtocols
;
5760 * Replace transparent tags in $text with the values given by the callbacks.
5762 * Transparent tag hooks are like regular XML-style tag hooks, except they
5763 * operate late in the transformation sequence, on HTML instead of wikitext.
5765 * @param string $text
5769 public function replaceTransparentTags( $text ) {
5771 $elements = array_keys( $this->mTransparentTagHooks
);
5772 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5775 foreach ( $matches as $marker => $data ) {
5776 list( $element, $content, $params, $tag ) = $data;
5777 $tagName = strtolower( $element );
5778 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5779 $output = call_user_func_array(
5780 $this->mTransparentTagHooks
[$tagName],
5781 [ $content, $params, $this ]
5786 $replacements[$marker] = $output;
5788 return strtr( $text, $replacements );
5792 * Break wikitext input into sections, and either pull or replace
5793 * some particular section's text.
5795 * External callers should use the getSection and replaceSection methods.
5797 * @param string $text Page wikitext
5798 * @param string|int $sectionId A section identifier string of the form:
5799 * "<flag1> - <flag2> - ... - <section number>"
5801 * Currently the only recognised flag is "T", which means the target section number
5802 * was derived during a template inclusion parse, in other words this is a template
5803 * section edit link. If no flags are given, it was an ordinary section edit link.
5804 * This flag is required to avoid a section numbering mismatch when a section is
5805 * enclosed by "<includeonly>" (T8563).
5807 * The section number 0 pulls the text before the first heading; other numbers will
5808 * pull the given section along with its lower-level subsections. If the section is
5809 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5811 * Section 0 is always considered to exist, even if it only contains the empty
5812 * string. If $text is the empty string and section 0 is replaced, $newText is
5815 * @param string $mode One of "get" or "replace"
5816 * @param string $newText Replacement text for section data.
5817 * @return string For "get", the extracted section text.
5818 * for "replace", the whole page with the section replaced.
5820 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5821 global $wgTitle; # not generally used but removes an ugly failure mode
5823 $magicScopeVariable = $this->lock();
5824 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5826 $frame = $this->getPreprocessor()->newFrame();
5828 # Process section extraction flags
5830 $sectionParts = explode( '-', $sectionId );
5831 $sectionIndex = array_pop( $sectionParts );
5832 foreach ( $sectionParts as $part ) {
5833 if ( $part === 'T' ) {
5834 $flags |
= self
::PTD_FOR_INCLUSION
;
5838 # Check for empty input
5839 if ( strval( $text ) === '' ) {
5840 # Only sections 0 and T-0 exist in an empty document
5841 if ( $sectionIndex == 0 ) {
5842 if ( $mode === 'get' ) {
5848 if ( $mode === 'get' ) {
5856 # Preprocess the text
5857 $root = $this->preprocessToDom( $text, $flags );
5859 # <h> nodes indicate section breaks
5860 # They can only occur at the top level, so we can find them by iterating the root's children
5861 $node = $root->getFirstChild();
5863 # Find the target section
5864 if ( $sectionIndex == 0 ) {
5865 # Section zero doesn't nest, level=big
5866 $targetLevel = 1000;
5869 if ( $node->getName() === 'h' ) {
5870 $bits = $node->splitHeading();
5871 if ( $bits['i'] == $sectionIndex ) {
5872 $targetLevel = $bits['level'];
5876 if ( $mode === 'replace' ) {
5877 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5879 $node = $node->getNextSibling();
5885 if ( $mode === 'get' ) {
5892 # Find the end of the section, including nested sections
5894 if ( $node->getName() === 'h' ) {
5895 $bits = $node->splitHeading();
5896 $curLevel = $bits['level'];
5897 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5901 if ( $mode === 'get' ) {
5902 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5904 $node = $node->getNextSibling();
5907 # Write out the remainder (in replace mode only)
5908 if ( $mode === 'replace' ) {
5909 # Output the replacement text
5910 # Add two newlines on -- trailing whitespace in $newText is conventionally
5911 # stripped by the editor, so we need both newlines to restore the paragraph gap
5912 # Only add trailing whitespace if there is newText
5913 if ( $newText != "" ) {
5914 $outText .= $newText . "\n\n";
5918 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5919 $node = $node->getNextSibling();
5923 if ( is_string( $outText ) ) {
5924 # Re-insert stripped tags
5925 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5932 * This function returns the text of a section, specified by a number ($section).
5933 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5934 * the first section before any such heading (section 0).
5936 * If a section contains subsections, these are also returned.
5938 * @param string $text Text to look in
5939 * @param string|int $sectionId Section identifier as a number or string
5940 * (e.g. 0, 1 or 'T-1').
5941 * @param string $defaultText Default to return if section is not found
5943 * @return string Text of the requested section
5945 public function getSection( $text, $sectionId, $defaultText = '' ) {
5946 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5950 * This function returns $oldtext after the content of the section
5951 * specified by $section has been replaced with $text. If the target
5952 * section does not exist, $oldtext is returned unchanged.
5954 * @param string $oldText Former text of the article
5955 * @param string|int $sectionId Section identifier as a number or string
5956 * (e.g. 0, 1 or 'T-1').
5957 * @param string $newText Replacing text
5959 * @return string Modified text
5961 public function replaceSection( $oldText, $sectionId, $newText ) {
5962 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5966 * Get the ID of the revision we are parsing
5968 * The return value will be either:
5969 * - a) Positive, indicating a specific revision ID (current or old)
5970 * - b) Zero, meaning the revision ID is specified by getCurrentRevisionCallback()
5971 * - c) Null, meaning the parse is for preview mode and there is no revision
5975 public function getRevisionId() {
5976 return $this->mRevisionId
;
5980 * Get the revision object for $this->mRevisionId
5982 * @return Revision|null Either a Revision object or null
5983 * @since 1.23 (public since 1.23)
5985 public function getRevisionObject() {
5986 if ( $this->mRevisionObject
) {
5987 return $this->mRevisionObject
;
5990 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5991 // This is useful when parsing a revision that has not yet been saved.
5992 // However, if we get back a saved revision even though we are in
5993 // preview mode, we'll have to ignore it, see below.
5994 // NOTE: This callback may be used to inject an OLD revision that was
5995 // already loaded, so "current" is a bit of a misnomer. We can't just
5996 // skip it if mRevisionId is set.
5997 $rev = call_user_func(
5998 $this->mOptions
->getCurrentRevisionCallback(),
6003 if ( $this->mRevisionId
=== null && $rev && $rev->getId() ) {
6004 // We are in preview mode (mRevisionId is null), and the current revision callback
6005 // returned an existing revision. Ignore it and return null, it's probably the page's
6006 // current revision, which is not what we want here. Note that we do want to call the
6007 // callback to allow the unsaved revision to be injected here, e.g. for
6008 // self-transclusion previews.
6012 // If the parse is for a new revision, then the callback should have
6013 // already been set to force the object and should match mRevisionId.
6014 // If not, try to fetch by mRevisionId for sanity.
6015 if ( $this->mRevisionId
&& $rev && $rev->getId() != $this->mRevisionId
) {
6016 $rev = Revision
::newFromId( $this->mRevisionId
);
6019 $this->mRevisionObject
= $rev;
6021 return $this->mRevisionObject
;
6025 * Get the timestamp associated with the current revision, adjusted for
6026 * the default server-local timestamp
6027 * @return string TS_MW timestamp
6029 public function getRevisionTimestamp() {
6030 if ( $this->mRevisionTimestamp
!== null ) {
6031 return $this->mRevisionTimestamp
;
6034 # Use specified revision timestamp, falling back to the current timestamp
6035 $revObject = $this->getRevisionObject();
6036 $timestamp = $revObject ?
$revObject->getTimestamp() : $this->mOptions
->getTimestamp();
6037 $this->mOutput
->setRevisionTimestampUsed( $timestamp ); // unadjusted time zone
6039 # The cryptic '' timezone parameter tells to use the site-default
6040 # timezone offset instead of the user settings.
6041 # Since this value will be saved into the parser cache, served
6042 # to other users, and potentially even used inside links and such,
6043 # it needs to be consistent for all visitors.
6044 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
6046 return $this->mRevisionTimestamp
;
6050 * Get the name of the user that edited the last revision
6052 * @return string User name
6054 public function getRevisionUser() {
6055 if ( is_null( $this->mRevisionUser
) ) {
6056 $revObject = $this->getRevisionObject();
6058 # if this template is subst: the revision id will be blank,
6059 # so just use the current user's name
6061 $this->mRevisionUser
= $revObject->getUserText();
6062 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6063 $this->mRevisionUser
= $this->getUser()->getName();
6066 return $this->mRevisionUser
;
6070 * Get the size of the revision
6072 * @return int|null Revision size
6074 public function getRevisionSize() {
6075 if ( is_null( $this->mRevisionSize
) ) {
6076 $revObject = $this->getRevisionObject();
6078 # if this variable is subst: the revision id will be blank,
6079 # so just use the parser input size, because the own substituation
6080 # will change the size.
6082 $this->mRevisionSize
= $revObject->getSize();
6084 $this->mRevisionSize
= $this->mInputSize
;
6087 return $this->mRevisionSize
;
6091 * Mutator for $mDefaultSort
6093 * @param string $sort New value
6095 public function setDefaultSort( $sort ) {
6096 $this->mDefaultSort
= $sort;
6097 $this->mOutput
->setProperty( 'defaultsort', $sort );
6101 * Accessor for $mDefaultSort
6102 * Will use the empty string if none is set.
6104 * This value is treated as a prefix, so the
6105 * empty string is equivalent to sorting by
6110 public function getDefaultSort() {
6111 if ( $this->mDefaultSort
!== false ) {
6112 return $this->mDefaultSort
;
6119 * Accessor for $mDefaultSort
6120 * Unlike getDefaultSort(), will return false if none is set
6122 * @return string|bool
6124 public function getCustomDefaultSort() {
6125 return $this->mDefaultSort
;
6128 private static function getSectionNameFromStrippedText( $text ) {
6129 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6130 $text = Sanitizer
::decodeCharReferences( $text );
6131 $text = self
::normalizeSectionName( $text );
6135 private static function makeAnchor( $sectionName ) {
6136 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
6139 private function makeLegacyAnchor( $sectionName ) {
6140 $fragmentMode = $this->svcOptions
->get( 'FragmentMode' );
6141 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
6142 // ForAttribute() and ForLink() are the same for legacy encoding
6143 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
6145 $id = Sanitizer
::escapeIdForLink( $sectionName );
6152 * Try to guess the section anchor name based on a wikitext fragment
6153 * presumably extracted from a heading, for example "Header" from
6156 * @param string $text
6157 * @return string Anchor (starting with '#')
6159 public function guessSectionNameFromWikiText( $text ) {
6160 # Strip out wikitext links(they break the anchor)
6161 $text = $this->stripSectionName( $text );
6162 $sectionName = self
::getSectionNameFromStrippedText( $text );
6163 return self
::makeAnchor( $sectionName );
6167 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6168 * instead, if possible. For use in redirects, since various versions
6169 * of Microsoft browsers interpret Location: headers as something other
6170 * than UTF-8, resulting in breakage.
6172 * @param string $text The section name
6173 * @return string Anchor (starting with '#')
6175 public function guessLegacySectionNameFromWikiText( $text ) {
6176 # Strip out wikitext links(they break the anchor)
6177 $text = $this->stripSectionName( $text );
6178 $sectionName = self
::getSectionNameFromStrippedText( $text );
6179 return $this->makeLegacyAnchor( $sectionName );
6183 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6184 * @param string $text Section name (plain text)
6185 * @return string Anchor (starting with '#')
6187 public static function guessSectionNameFromStrippedText( $text ) {
6188 $sectionName = self
::getSectionNameFromStrippedText( $text );
6189 return self
::makeAnchor( $sectionName );
6193 * Apply the same normalization as code making links to this section would
6195 * @param string $text
6198 private static function normalizeSectionName( $text ) {
6199 # T90902: ensure the same normalization is applied for IDs as to links
6200 /** @var MediaWikiTitleCodec $titleParser */
6201 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
6202 '@phan-var MediaWikiTitleCodec $titleParser';
6205 $parts = $titleParser->splitTitleString( "#$text" );
6206 } catch ( MalformedTitleException
$ex ) {
6209 return $parts['fragment'];
6213 * Strips a text string of wikitext for use in a section anchor
6215 * Accepts a text string and then removes all wikitext from the
6216 * string and leaves only the resultant text (i.e. the result of
6217 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6218 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6219 * to create valid section anchors by mimicing the output of the
6220 * parser when headings are parsed.
6222 * @param string $text Text string to be stripped of wikitext
6223 * for use in a Section anchor
6224 * @return string Filtered text string
6226 public function stripSectionName( $text ) {
6227 # Strip internal link markup
6228 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6229 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6231 # Strip external link markup
6232 # @todo FIXME: Not tolerant to blank link text
6233 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6234 # on how many empty links there are on the page - need to figure that out.
6235 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6237 # Parse wikitext quotes (italics & bold)
6238 $text = $this->doQuotes( $text );
6241 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6246 * strip/replaceVariables/unstrip for preprocessor regression testing
6248 * @param string $text
6249 * @param Title $title
6250 * @param ParserOptions $options
6251 * @param int $outputType
6255 public function testSrvus( $text, Title
$title, ParserOptions
$options,
6256 $outputType = self
::OT_HTML
6258 $magicScopeVariable = $this->lock();
6259 $this->startParse( $title, $options, $outputType, true );
6261 $text = $this->replaceVariables( $text );
6262 $text = $this->mStripState
->unstripBoth( $text );
6263 $text = Sanitizer
::removeHTMLtags( $text );
6268 * @param string $text
6269 * @param Title $title
6270 * @param ParserOptions $options
6273 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6274 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6278 * @param string $text
6279 * @param Title $title
6280 * @param ParserOptions $options
6283 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6284 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6288 * Call a callback function on all regions of the given text that are not
6289 * inside strip markers, and replace those regions with the return value
6290 * of the callback. For example, with input:
6294 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6295 * two strings will be replaced with the value returned by the callback in
6299 * @param callable $callback
6303 public function markerSkipCallback( $s, $callback ) {
6306 while ( $i < strlen( $s ) ) {
6307 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6308 if ( $markerStart === false ) {
6309 $out .= call_user_func( $callback, substr( $s, $i ) );
6312 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6313 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6314 if ( $markerEnd === false ) {
6315 $out .= substr( $s, $markerStart );
6318 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6319 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6328 * Remove any strip markers found in the given text.
6330 * @param string $text
6333 public function killMarkers( $text ) {
6334 return $this->mStripState
->killMarkers( $text );
6338 * Save the parser state required to convert the given half-parsed text to
6339 * HTML. "Half-parsed" in this context means the output of
6340 * recursiveTagParse() or internalParse(). This output has strip markers
6341 * from replaceVariables (extensionSubstitution() etc.), and link
6342 * placeholders from replaceLinkHolders().
6344 * Returns an array which can be serialized and stored persistently. This
6345 * array can later be loaded into another parser instance with
6346 * unserializeHalfParsedText(). The text can then be safely incorporated into
6347 * the return value of a parser hook.
6349 * @deprecated since 1.31
6350 * @param string $text
6354 public function serializeHalfParsedText( $text ) {
6355 wfDeprecated( __METHOD__
, '1.31' );
6358 'version' => self
::HALF_PARSED_VERSION
,
6359 'stripState' => $this->mStripState
->getSubState( $text ),
6360 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6366 * Load the parser state given in the $data array, which is assumed to
6367 * have been generated by serializeHalfParsedText(). The text contents is
6368 * extracted from the array, and its markers are transformed into markers
6369 * appropriate for the current Parser instance. This transformed text is
6370 * returned, and can be safely included in the return value of a parser
6373 * If the $data array has been stored persistently, the caller should first
6374 * check whether it is still valid, by calling isValidHalfParsedText().
6376 * @deprecated since 1.31
6377 * @param array $data Serialized data
6378 * @throws MWException
6381 public function unserializeHalfParsedText( $data ) {
6382 wfDeprecated( __METHOD__
, '1.31' );
6383 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6384 throw new MWException( __METHOD__
. ': invalid version' );
6387 # First, extract the strip state.
6388 $texts = [ $data['text'] ];
6389 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6391 # Now renumber links
6392 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6394 # Should be good to go.
6399 * Returns true if the given array, presumed to be generated by
6400 * serializeHalfParsedText(), is compatible with the current version of the
6403 * @deprecated since 1.31
6404 * @param array $data
6408 public function isValidHalfParsedText( $data ) {
6409 wfDeprecated( __METHOD__
, '1.31' );
6410 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6414 * Parsed a width param of imagelink like 300px or 200x300px
6416 * @param string $value
6417 * @param bool $parseHeight
6422 public static function parseWidthParam( $value, $parseHeight = true ) {
6423 $parsedWidthParam = [];
6424 if ( $value === '' ) {
6425 return $parsedWidthParam;
6428 # (T15500) In both cases (width/height and width only),
6429 # permit trailing "px" for backward compatibility.
6430 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6431 $width = intval( $m[1] );
6432 $height = intval( $m[2] );
6433 $parsedWidthParam['width'] = $width;
6434 $parsedWidthParam['height'] = $height;
6435 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6436 $width = intval( $value );
6437 $parsedWidthParam['width'] = $width;
6439 return $parsedWidthParam;
6443 * Lock the current instance of the parser.
6445 * This is meant to stop someone from calling the parser
6446 * recursively and messing up all the strip state.
6448 * @throws MWException If parser is in a parse
6449 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6451 protected function lock() {
6452 if ( $this->mInParse
) {
6453 throw new MWException( "Parser state cleared while parsing. "
6454 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6457 // Save the backtrace when locking, so that if some code tries locking again,
6458 // we can print the lock owner's backtrace for easier debugging
6460 $this->mInParse
= $e->getTraceAsString();
6462 $recursiveCheck = new ScopedCallback( function () {
6463 $this->mInParse
= false;
6466 return $recursiveCheck;
6470 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6472 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6473 * or if there is more than one <p/> tag in the input HTML.
6475 * @param string $html
6479 public static function stripOuterParagraph( $html ) {
6481 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '</p>' ) === false ) {
6489 * Return this parser if it is not doing anything, otherwise
6490 * get a fresh parser. You can use this method by doing
6491 * $newParser = $oldParser->getFreshParser(), or more simply
6492 * $oldParser->getFreshParser()->parse( ... );
6493 * if you're unsure if $oldParser is safe to use.
6496 * @return Parser A parser object that is not parsing anything
6498 public function getFreshParser() {
6499 if ( $this->mInParse
) {
6500 return $this->factory
->create();
6507 * Set's up the PHP implementation of OOUI for use in this request
6508 * and instructs OutputPage to enable OOUI for itself.
6512 public function enableOOUI() {
6513 OutputPage
::setupOOUI();
6514 $this->mOutput
->setEnableOOUI( true );
6518 * @param string $flag
6519 * @param string $reason
6521 protected function setOutputFlag( $flag, $reason ) {
6522 $this->mOutput
->setFlag( $flag );
6523 $name = $this->mTitle
->getPrefixedText();
6524 $this->logger
->debug( __METHOD__
. ": set $flag flag on '$name'; $reason" );