3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @defgroup Parser Parser
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
37 * There are seven main entry points into the Parser class:
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
89 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
90 # uses to replace invalid HTML characters.
91 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
92 # Simplified expression to match an IPv4 or IPv6 address, or
93 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
94 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
95 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
96 // phpcs:ignore Generic.Files.LineLength
97 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
98 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
100 # Regular expression for a non-newline space
101 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
103 # Flags for preprocessToDom
104 const PTD_FOR_INCLUSION
= 1;
106 # Allowed values for $this->mOutputType
107 # Parameter to startExternalParse().
108 const OT_HTML
= 1; # like parse()
109 const OT_WIKI
= 2; # like preSaveTransform()
110 const OT_PREPROCESS
= 3; # like preprocess()
112 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 * @var string Prefix and suffix for temporary replacement strings
116 * for the multipass parser.
118 * \x7f should never appear in input as it's disallowed in XML.
119 * Using it at the front also gives us a little extra robustness
120 * since it shouldn't match when butted up against identifier-like
123 * Must not consist of all title characters, or else it will change
124 * the behavior of <nowiki> in a link.
126 * Must have a character that needs escaping in attributes, otherwise
127 * someone could put a strip marker in an attribute, to get around
128 * escaping quote marks, and break out of the attribute. Thus we add
131 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
132 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
134 # Markers used for wrapping the table of contents
135 const TOC_START
= '<mw:toc>';
136 const TOC_END
= '</mw:toc>';
138 /** @var int Assume that no output will later be saved this many seconds after parsing */
142 public $mTagHooks = [];
143 public $mTransparentTagHooks = [];
144 public $mFunctionHooks = [];
145 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
146 public $mFunctionTagHooks = [];
147 public $mStripList = [];
148 public $mDefaultStripList = [];
149 public $mVarCache = [];
150 public $mImageParams = [];
151 public $mImageParamsMagicArray = [];
152 public $mMarkerIndex = 0;
154 * @var bool Whether firstCallInit still needs to be called
156 public $mFirstCall = true;
158 # Initialised by initialiseVariables()
161 * @var MagicWordArray
166 * @var MagicWordArray
169 # Initialised in constructor
170 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
172 # Initialized in getPreprocessor()
173 /** @var Preprocessor */
174 public $mPreprocessor;
176 # Cleared with clearState():
188 public $mIncludeCount;
190 * @var LinkHolderArray
192 public $mLinkHolders;
195 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
196 public $mDefaultSort;
197 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
198 public $mExpensiveFunctionCount; # number of expensive parser function calls
199 public $mShowToc, $mForceTocPosition;
204 public $mUser; # User object; only used when doing pre-save transform
207 # These are variables reset at least once per parse regardless of $clearState
217 public $mTitle; # Title context, used for self-link rendering and similar things
218 public $mOutputType; # Output type, one of the OT_xxx constants
219 public $ot; # Shortcut alias, see setOutputType()
220 public $mRevisionObject; # The revision object of the specified revision ID
221 public $mRevisionId; # ID to display in {{REVISIONID}} tags
222 public $mRevisionTimestamp; # The timestamp of the specified revision ID
223 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
224 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
225 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
226 public $mInputSize = false; # For {{PAGESIZE}} on current page.
229 * @var string Deprecated accessor for the strip marker prefix.
230 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
232 public $mUniqPrefix = self
::MARKER_PREFIX
;
235 * @var array Array with the language name of each language link (i.e. the
236 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
237 * duplicate language links to the ParserOutput.
239 public $mLangLinkLanguages;
242 * @var MapCacheLRU|null
245 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
247 public $currentRevisionCache;
250 * @var bool|string Recursive call protection.
251 * This variable should be treated as if it were private.
253 public $mInParse = false;
255 /** @var SectionProfiler */
256 protected $mProfiler;
261 protected $mLinkRenderer;
263 /** @var MagicWordFactory */
264 private $magicWordFactory;
269 /** @var ParserFactory */
273 * @param array $conf See $wgParserConf documentation
274 * @param MagicWordFactory|null $magicWordFactory
275 * @param Language|null $contLang Content language
276 * @param ParserFactory|null $factory
277 * @param string|null $urlProtocols As returned from wfUrlProtocols()
279 public function __construct(
280 array $conf = [], MagicWordFactory
$magicWordFactory = null, Language
$contLang = null,
281 ParserFactory
$factory = null, $urlProtocols = null
283 $this->mConf
= $conf;
284 $this->mUrlProtocols
= $urlProtocols ??
wfUrlProtocols();
285 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
286 self
::EXT_LINK_ADDR
.
287 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
288 if ( isset( $conf['preprocessorClass'] ) ) {
289 $this->mPreprocessorClass
= $conf['preprocessorClass'];
290 } elseif ( defined( 'HPHP_VERSION' ) ) {
291 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
292 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
293 } elseif ( extension_loaded( 'domxml' ) ) {
294 # PECL extension that conflicts with the core DOM extension (T15770)
295 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
296 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
297 } elseif ( extension_loaded( 'dom' ) ) {
298 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
300 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
302 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
304 $this->magicWordFactory
= $magicWordFactory ??
305 MediaWikiServices
::getInstance()->getMagicWordFactory();
307 $this->contLang
= $contLang ?? MediaWikiServices
::getInstance()->getContentLanguage();
309 $this->factory
= $factory ?? MediaWikiServices
::getInstance()->getParserFactory();
313 * Reduce memory usage to reduce the impact of circular references
315 public function __destruct() {
316 if ( isset( $this->mLinkHolders
) ) {
317 unset( $this->mLinkHolders
);
319 foreach ( $this as $name => $value ) {
320 unset( $this->$name );
325 * Allow extensions to clean up when the parser is cloned
327 public function __clone() {
328 $this->mInParse
= false;
330 // T58226: When you create a reference "to" an object field, that
331 // makes the object field itself be a reference too (until the other
332 // reference goes out of scope). When cloning, any field that's a
333 // reference is copied as a reference in the new object. Both of these
334 // are defined PHP5 behaviors, as inconvenient as it is for us when old
335 // hooks from PHP4 days are passing fields by reference.
336 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
337 // Make a non-reference copy of the field, then rebind the field to
338 // reference the new copy.
344 Hooks
::run( 'ParserCloned', [ $this ] );
348 * Do various kinds of initialisation on the first call of the parser
350 public function firstCallInit() {
351 if ( !$this->mFirstCall
) {
354 $this->mFirstCall
= false;
356 CoreParserFunctions
::register( $this );
357 CoreTagHooks
::register( $this );
358 $this->initialiseVariables();
360 // Avoid PHP 7.1 warning from passing $this by reference
362 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
370 public function clearState() {
371 $this->firstCallInit();
372 $this->mOutput
= new ParserOutput
;
373 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
374 $this->mAutonumber
= 0;
375 $this->mIncludeCount
= [];
376 $this->mLinkHolders
= new LinkHolderArray( $this );
378 $this->mRevisionObject
= $this->mRevisionTimestamp
=
379 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
380 $this->mVarCache
= [];
382 $this->mLangLinkLanguages
= [];
383 $this->currentRevisionCache
= null;
385 $this->mStripState
= new StripState( $this );
387 # Clear these on every parse, T6549
388 $this->mTplRedirCache
= $this->mTplDomCache
= [];
390 $this->mShowToc
= true;
391 $this->mForceTocPosition
= false;
392 $this->mIncludeSizes
= [
396 $this->mPPNodeCount
= 0;
397 $this->mGeneratedPPNodeCount
= 0;
398 $this->mHighestExpansionDepth
= 0;
399 $this->mDefaultSort
= false;
400 $this->mHeadings
= [];
401 $this->mDoubleUnderscores
= [];
402 $this->mExpensiveFunctionCount
= 0;
405 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
406 $this->mPreprocessor
= null;
409 $this->mProfiler
= new SectionProfiler();
411 // Avoid PHP 7.1 warning from passing $this by reference
413 Hooks
::run( 'ParserClearState', [ &$parser ] );
417 * Convert wikitext to HTML
418 * Do not call this function recursively.
420 * @param string $text Text we want to parse
421 * @param Title $title
422 * @param ParserOptions $options
423 * @param bool $linestart
424 * @param bool $clearState
425 * @param int|null $revid Number to pass in {{REVISIONID}}
426 * @return ParserOutput A ParserOutput
428 public function parse(
429 $text, Title
$title, ParserOptions
$options,
430 $linestart = true, $clearState = true, $revid = null
433 // We use U+007F DELETE to construct strip markers, so we have to make
434 // sure that this character does not occur in the input text.
435 $text = strtr( $text, "\x7f", "?" );
436 $magicScopeVariable = $this->lock();
438 // Strip U+0000 NULL (T159174)
439 $text = str_replace( "\000", '', $text );
441 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
443 $this->currentRevisionCache
= null;
444 $this->mInputSize
= strlen( $text );
445 if ( $this->mOptions
->getEnableLimitReport() ) {
446 $this->mOutput
->resetParseStartTime();
449 $oldRevisionId = $this->mRevisionId
;
450 $oldRevisionObject = $this->mRevisionObject
;
451 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
452 $oldRevisionUser = $this->mRevisionUser
;
453 $oldRevisionSize = $this->mRevisionSize
;
454 if ( $revid !== null ) {
455 $this->mRevisionId
= $revid;
456 $this->mRevisionObject
= null;
457 $this->mRevisionTimestamp
= null;
458 $this->mRevisionUser
= null;
459 $this->mRevisionSize
= null;
462 // Avoid PHP 7.1 warning from passing $this by reference
464 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
466 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
467 $text = $this->internalParse( $text );
468 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
470 $text = $this->internalParseHalfParsed( $text, true, $linestart );
473 * A converted title will be provided in the output object if title and
474 * content conversion are enabled, the article text does not contain
475 * a conversion-suppressing double-underscore tag, and no
476 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
477 * automatic link conversion.
479 if ( !( $options->getDisableTitleConversion()
480 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
481 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
482 ||
$this->mOutput
->getDisplayTitle() !== false )
484 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
485 if ( $convruletitle ) {
486 $this->mOutput
->setTitleText( $convruletitle );
488 $titleText = $this->getTargetLanguage()->convertTitle( $title );
489 $this->mOutput
->setTitleText( $titleText );
493 # Compute runtime adaptive expiry if set
494 $this->mOutput
->finalizeAdaptiveCacheExpiry();
496 # Warn if too many heavyweight parser functions were used
497 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
498 $this->limitationWarn( 'expensive-parserfunction',
499 $this->mExpensiveFunctionCount
,
500 $this->mOptions
->getExpensiveParserFunctionLimit()
504 # Information on limits, for the benefit of users who try to skirt them
505 if ( $this->mOptions
->getEnableLimitReport() ) {
506 $text .= $this->makeLimitReport();
509 # Wrap non-interface parser output in a <div> so it can be targeted
511 $class = $this->mOptions
->getWrapOutputClass();
512 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
513 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
516 $this->mOutput
->setText( $text );
518 $this->mRevisionId
= $oldRevisionId;
519 $this->mRevisionObject
= $oldRevisionObject;
520 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
521 $this->mRevisionUser
= $oldRevisionUser;
522 $this->mRevisionSize
= $oldRevisionSize;
523 $this->mInputSize
= false;
524 $this->currentRevisionCache
= null;
526 return $this->mOutput
;
530 * Set the limit report data in the current ParserOutput, and return the
531 * limit report HTML comment.
535 protected function makeLimitReport() {
536 global $wgShowHostnames;
538 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
540 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
541 if ( $cpuTime !== null ) {
542 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
543 sprintf( "%.3f", $cpuTime )
547 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
548 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
549 sprintf( "%.3f", $wallTime )
552 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
553 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
555 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
556 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
558 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
559 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
561 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
562 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
564 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
565 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
567 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
568 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
571 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
572 $this->mOutput
->setLimitReportData( $key, $value );
575 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
577 $limitReport = "NewPP limit report\n";
578 if ( $wgShowHostnames ) {
579 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
581 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
582 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
583 $limitReport .= 'Dynamic content: ' .
584 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
587 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
588 if ( Hooks
::run( 'ParserLimitReportFormat',
589 [ $key, &$value, &$limitReport, false, false ]
591 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
592 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
593 ->inLanguage( 'en' )->useDatabase( false );
594 if ( !$valueMsg->exists() ) {
595 $valueMsg = new RawMessage( '$1' );
597 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
598 $valueMsg->params( $value );
599 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
603 // Since we're not really outputting HTML, decode the entities and
604 // then re-encode the things that need hiding inside HTML comments.
605 $limitReport = htmlspecialchars_decode( $limitReport );
606 // Run deprecated hook
607 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
609 // Sanitize for comment. Note '‐' in the replacement is U+2010,
610 // which looks much like the problematic '-'.
611 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
612 $text = "\n<!-- \n$limitReport-->\n";
614 // Add on template profiling data in human/machine readable way
615 $dataByFunc = $this->mProfiler
->getFunctionStats();
616 uasort( $dataByFunc, function ( $a, $b ) {
617 return $b['real'] <=> $a['real']; // descending order
620 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
621 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
622 $item['%real'], $item['real'], $item['calls'],
623 htmlspecialchars( $item['name'] ) );
625 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
626 $text .= implode( "\n", $profileReport ) . "\n-->\n";
628 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
630 // Add other cache related metadata
631 if ( $wgShowHostnames ) {
632 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
634 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
635 $this->mOutput
->getCacheTime() );
636 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
637 $this->mOutput
->getCacheExpiry() );
638 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
639 $this->mOutput
->hasDynamicContent() );
641 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
642 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
643 $this->mTitle
->getPrefixedDBkey() );
649 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
650 * can be called from an extension tag hook.
652 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
653 * instead, which means that lists and links have not been fully parsed yet,
654 * and strip markers are still present.
656 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
658 * Use this function if you're a parser tag hook and you want to parse
659 * wikitext before or after applying additional transformations, and you
660 * intend to *return the result as hook output*, which will cause it to go
661 * through the rest of parsing process automatically.
663 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
664 * $text are not expanded
666 * @param string $text Text extension wants to have parsed
667 * @param bool|PPFrame $frame The frame to use for expanding any template variables
668 * @return string UNSAFE half-parsed HTML
670 public function recursiveTagParse( $text, $frame = false ) {
671 // Avoid PHP 7.1 warning from passing $this by reference
673 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
674 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
675 $text = $this->internalParse( $text, false, $frame );
680 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
681 * point can be called from an extension tag hook.
683 * The output of this function is fully-parsed HTML that is safe for output.
684 * If you're a parser tag hook, you might want to use recursiveTagParse()
687 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
688 * $text are not expanded
692 * @param string $text Text extension wants to have parsed
693 * @param bool|PPFrame $frame The frame to use for expanding any template variables
694 * @return string Fully parsed HTML
696 public function recursiveTagParseFully( $text, $frame = false ) {
697 $text = $this->recursiveTagParse( $text, $frame );
698 $text = $this->internalParseHalfParsed( $text, false );
703 * Expand templates and variables in the text, producing valid, static wikitext.
704 * Also removes comments.
705 * Do not call this function recursively.
706 * @param string $text
707 * @param Title|null $title
708 * @param ParserOptions $options
709 * @param int|null $revid
710 * @param bool|PPFrame $frame
711 * @return mixed|string
713 public function preprocess( $text, Title
$title = null,
714 ParserOptions
$options, $revid = null, $frame = false
716 $magicScopeVariable = $this->lock();
717 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
718 if ( $revid !== null ) {
719 $this->mRevisionId
= $revid;
721 // Avoid PHP 7.1 warning from passing $this by reference
723 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
724 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
725 $text = $this->replaceVariables( $text, $frame );
726 $text = $this->mStripState
->unstripBoth( $text );
731 * Recursive parser entry point that can be called from an extension tag
734 * @param string $text Text to be expanded
735 * @param bool|PPFrame $frame The frame to use for expanding any template variables
739 public function recursivePreprocess( $text, $frame = false ) {
740 $text = $this->replaceVariables( $text, $frame );
741 $text = $this->mStripState
->unstripBoth( $text );
746 * Process the wikitext for the "?preload=" feature. (T7210)
748 * "<noinclude>", "<includeonly>" etc. are parsed as for template
749 * transclusion, comments, templates, arguments, tags hooks and parser
750 * functions are untouched.
752 * @param string $text
753 * @param Title $title
754 * @param ParserOptions $options
755 * @param array $params
758 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
759 $msg = new RawMessage( $text );
760 $text = $msg->params( $params )->plain();
762 # Parser (re)initialisation
763 $magicScopeVariable = $this->lock();
764 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
766 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
767 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
768 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
769 $text = $this->mStripState
->unstripBoth( $text );
774 * Set the current user.
775 * Should only be used when doing pre-save transform.
777 * @param User|null $user User object or null (to reset)
779 public function setUser( $user ) {
780 $this->mUser
= $user;
784 * Set the context title
788 public function setTitle( $t ) {
790 $t = Title
::newFromText( 'NO TITLE' );
793 if ( $t->hasFragment() ) {
794 # Strip the fragment to avoid various odd effects
795 $this->mTitle
= $t->createFragmentTarget( '' );
802 * Accessor for the Title object
806 public function getTitle() {
807 return $this->mTitle
;
811 * Accessor/mutator for the Title object
813 * @param Title|null $x Title object or null to just get the current one
816 public function Title( $x = null ) {
817 return wfSetVar( $this->mTitle
, $x );
821 * Set the output type
823 * @param int $ot New value
825 public function setOutputType( $ot ) {
826 $this->mOutputType
= $ot;
829 'html' => $ot == self
::OT_HTML
,
830 'wiki' => $ot == self
::OT_WIKI
,
831 'pre' => $ot == self
::OT_PREPROCESS
,
832 'plain' => $ot == self
::OT_PLAIN
,
837 * Accessor/mutator for the output type
839 * @param int|null $x New value or null to just get the current one
842 public function OutputType( $x = null ) {
843 return wfSetVar( $this->mOutputType
, $x );
847 * Get the ParserOutput object
849 * @return ParserOutput
851 public function getOutput() {
852 return $this->mOutput
;
856 * Get the ParserOptions object
858 * @return ParserOptions
860 public function getOptions() {
861 return $this->mOptions
;
865 * Accessor/mutator for the ParserOptions object
867 * @param ParserOptions|null $x New value or null to just get the current one
868 * @return ParserOptions Current ParserOptions object
870 public function Options( $x = null ) {
871 return wfSetVar( $this->mOptions
, $x );
877 public function nextLinkID() {
878 return $this->mLinkID++
;
884 public function setLinkID( $id ) {
885 $this->mLinkID
= $id;
889 * Get a language object for use in parser functions such as {{FORMATNUM:}}
892 public function getFunctionLang() {
893 return $this->getTargetLanguage();
897 * Get the target language for the content being parsed. This is usually the
898 * language that the content is in.
902 * @throws MWException
905 public function getTargetLanguage() {
906 $target = $this->mOptions
->getTargetLanguage();
908 if ( $target !== null ) {
910 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
911 return $this->mOptions
->getUserLangObj();
912 } elseif ( is_null( $this->mTitle
) ) {
913 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
916 return $this->mTitle
->getPageLanguage();
920 * Get the language object for language conversion
921 * @deprecated since 1.32, just use getTargetLanguage()
922 * @return Language|null
924 public function getConverterLanguage() {
925 return $this->getTargetLanguage();
929 * Get a User object either from $this->mUser, if set, or from the
930 * ParserOptions object otherwise
934 public function getUser() {
935 if ( !is_null( $this->mUser
) ) {
938 return $this->mOptions
->getUser();
942 * Get a preprocessor object
944 * @return Preprocessor
946 public function getPreprocessor() {
947 if ( !isset( $this->mPreprocessor
) ) {
948 $class = $this->mPreprocessorClass
;
949 $this->mPreprocessor
= new $class( $this );
951 return $this->mPreprocessor
;
955 * Get a LinkRenderer instance to make links with
958 * @return LinkRenderer
960 public function getLinkRenderer() {
961 if ( !$this->mLinkRenderer
) {
962 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
963 ->getLinkRendererFactory()->create();
964 $this->mLinkRenderer
->setStubThreshold(
965 $this->getOptions()->getStubThreshold()
969 return $this->mLinkRenderer
;
973 * Get the MagicWordFactory that this Parser is using
976 * @return MagicWordFactory
978 public function getMagicWordFactory() {
979 return $this->magicWordFactory
;
983 * Get the content language that this Parser is using
988 public function getContentLanguage() {
989 return $this->contLang
;
993 * Replaces all occurrences of HTML-style comments and the given tags
994 * in the text with a random marker and returns the next text. The output
995 * parameter $matches will be an associative array filled with data in
1002 * [ 'param' => 'x' ],
1003 * '<element param="x">tag content</element>' ]
1006 * @param array $elements List of element names. Comments are always extracted.
1007 * @param string $text Source text string.
1008 * @param array &$matches Out parameter, Array: extracted tags
1009 * @return string Stripped text
1011 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1016 $taglist = implode( '|', $elements );
1017 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
1019 while ( $text != '' ) {
1020 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1022 if ( count( $p ) < 5 ) {
1025 if ( count( $p ) > 5 ) {
1034 $attributes = $p[2];
1039 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1040 $stripped .= $marker;
1042 if ( $close === '/>' ) {
1043 # Empty element tag, <tag />
1048 if ( $element === '!--' ) {
1051 $end = "/(<\\/$element\\s*>)/i";
1053 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1055 if ( count( $q ) < 3 ) {
1056 # No end tag -- let it run out to the end of the text.
1065 $matches[$marker] = [ $element,
1067 Sanitizer
::decodeTagAttributes( $attributes ),
1068 "<$element$attributes$close$content$tail" ];
1074 * Get a list of strippable XML-like elements
1078 public function getStripList() {
1079 return $this->mStripList
;
1083 * Add an item to the strip state
1084 * Returns the unique tag which must be inserted into the stripped text
1085 * The tag will be replaced with the original text in unstrip()
1087 * @param string $text
1091 public function insertStripItem( $text ) {
1092 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1093 $this->mMarkerIndex++
;
1094 $this->mStripState
->addGeneral( $marker, $text );
1099 * parse the wiki syntax used to render tables
1102 * @param string $text
1105 public function doTableStuff( $text ) {
1106 $lines = StringUtils
::explode( "\n", $text );
1108 $td_history = []; # Is currently a td tag open?
1109 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1110 $tr_history = []; # Is currently a tr tag open?
1111 $tr_attributes = []; # history of tr attributes
1112 $has_opened_tr = []; # Did this table open a <tr> element?
1113 $indent_level = 0; # indent level of the table
1115 foreach ( $lines as $outLine ) {
1116 $line = trim( $outLine );
1118 if ( $line === '' ) { # empty line, go to next line
1119 $out .= $outLine . "\n";
1123 $first_character = $line[0];
1124 $first_two = substr( $line, 0, 2 );
1127 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1128 # First check if we are starting a new table
1129 $indent_level = strlen( $matches[1] );
1131 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1132 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1134 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1135 array_push( $td_history, false );
1136 array_push( $last_tag_history, '' );
1137 array_push( $tr_history, false );
1138 array_push( $tr_attributes, '' );
1139 array_push( $has_opened_tr, false );
1140 } elseif ( count( $td_history ) == 0 ) {
1141 # Don't do any of the following
1142 $out .= $outLine . "\n";
1144 } elseif ( $first_two === '|}' ) {
1145 # We are ending a table
1146 $line = '</table>' . substr( $line, 2 );
1147 $last_tag = array_pop( $last_tag_history );
1149 if ( !array_pop( $has_opened_tr ) ) {
1150 $line = "<tr><td></td></tr>{$line}";
1153 if ( array_pop( $tr_history ) ) {
1154 $line = "</tr>{$line}";
1157 if ( array_pop( $td_history ) ) {
1158 $line = "</{$last_tag}>{$line}";
1160 array_pop( $tr_attributes );
1161 if ( $indent_level > 0 ) {
1162 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1166 } elseif ( $first_two === '|-' ) {
1167 # Now we have a table row
1168 $line = preg_replace( '#^\|-+#', '', $line );
1170 # Whats after the tag is now only attributes
1171 $attributes = $this->mStripState
->unstripBoth( $line );
1172 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1173 array_pop( $tr_attributes );
1174 array_push( $tr_attributes, $attributes );
1177 $last_tag = array_pop( $last_tag_history );
1178 array_pop( $has_opened_tr );
1179 array_push( $has_opened_tr, true );
1181 if ( array_pop( $tr_history ) ) {
1185 if ( array_pop( $td_history ) ) {
1186 $line = "</{$last_tag}>{$line}";
1190 array_push( $tr_history, false );
1191 array_push( $td_history, false );
1192 array_push( $last_tag_history, '' );
1193 } elseif ( $first_character === '|'
1194 ||
$first_character === '!'
1195 ||
$first_two === '|+'
1197 # This might be cell elements, td, th or captions
1198 if ( $first_two === '|+' ) {
1199 $first_character = '+';
1200 $line = substr( $line, 2 );
1202 $line = substr( $line, 1 );
1205 // Implies both are valid for table headings.
1206 if ( $first_character === '!' ) {
1207 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1210 # Split up multiple cells on the same line.
1211 # FIXME : This can result in improper nesting of tags processed
1212 # by earlier parser steps.
1213 $cells = explode( '||', $line );
1217 # Loop through each table cell
1218 foreach ( $cells as $cell ) {
1220 if ( $first_character !== '+' ) {
1221 $tr_after = array_pop( $tr_attributes );
1222 if ( !array_pop( $tr_history ) ) {
1223 $previous = "<tr{$tr_after}>\n";
1225 array_push( $tr_history, true );
1226 array_push( $tr_attributes, '' );
1227 array_pop( $has_opened_tr );
1228 array_push( $has_opened_tr, true );
1231 $last_tag = array_pop( $last_tag_history );
1233 if ( array_pop( $td_history ) ) {
1234 $previous = "</{$last_tag}>\n{$previous}";
1237 if ( $first_character === '|' ) {
1239 } elseif ( $first_character === '!' ) {
1241 } elseif ( $first_character === '+' ) {
1242 $last_tag = 'caption';
1247 array_push( $last_tag_history, $last_tag );
1249 # A cell could contain both parameters and data
1250 $cell_data = explode( '|', $cell, 2 );
1252 # T2553: Note that a '|' inside an invalid link should not
1253 # be mistaken as delimiting cell parameters
1254 # Bug T153140: Neither should language converter markup.
1255 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1256 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1257 } elseif ( count( $cell_data ) == 1 ) {
1258 // Whitespace in cells is trimmed
1259 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1261 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1262 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1263 // Whitespace in cells is trimmed
1264 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1268 array_push( $td_history, true );
1271 $out .= $outLine . "\n";
1274 # Closing open td, tr && table
1275 while ( count( $td_history ) > 0 ) {
1276 if ( array_pop( $td_history ) ) {
1279 if ( array_pop( $tr_history ) ) {
1282 if ( !array_pop( $has_opened_tr ) ) {
1283 $out .= "<tr><td></td></tr>\n";
1286 $out .= "</table>\n";
1289 # Remove trailing line-ending (b/c)
1290 if ( substr( $out, -1 ) === "\n" ) {
1291 $out = substr( $out, 0, -1 );
1294 # special case: don't return empty table
1295 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1303 * Helper function for parse() that transforms wiki markup into half-parsed
1304 * HTML. Only called for $mOutputType == self::OT_HTML.
1308 * @param string $text The text to parse
1309 * @param bool $isMain Whether this is being called from the main parse() function
1310 * @param PPFrame|bool $frame A pre-processor frame
1314 public function internalParse( $text, $isMain = true, $frame = false ) {
1317 // Avoid PHP 7.1 warning from passing $this by reference
1320 # Hook to suspend the parser in this state
1321 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1325 # if $frame is provided, then use $frame for replacing any variables
1327 # use frame depth to infer how include/noinclude tags should be handled
1328 # depth=0 means this is the top-level document; otherwise it's an included document
1329 if ( !$frame->depth
) {
1332 $flag = self
::PTD_FOR_INCLUSION
;
1334 $dom = $this->preprocessToDom( $text, $flag );
1335 $text = $frame->expand( $dom );
1337 # if $frame is not provided, then use old-style replaceVariables
1338 $text = $this->replaceVariables( $text );
1341 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1342 $text = Sanitizer
::removeHTMLtags(
1344 [ $this, 'attributeStripCallback' ],
1346 array_keys( $this->mTransparentTagHooks
),
1348 [ $this, 'addTrackingCategory' ]
1350 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1352 # Tables need to come after variable replacement for things to work
1353 # properly; putting them before other transformations should keep
1354 # exciting things like link expansions from showing up in surprising
1356 $text = $this->doTableStuff( $text );
1358 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1360 $text = $this->doDoubleUnderscore( $text );
1362 $text = $this->doHeadings( $text );
1363 $text = $this->replaceInternalLinks( $text );
1364 $text = $this->doAllQuotes( $text );
1365 $text = $this->replaceExternalLinks( $text );
1367 # replaceInternalLinks may sometimes leave behind
1368 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1369 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1371 $text = $this->doMagicLinks( $text );
1372 $text = $this->formatHeadings( $text, $origText, $isMain );
1378 * Helper function for parse() that transforms half-parsed HTML into fully
1381 * @param string $text
1382 * @param bool $isMain
1383 * @param bool $linestart
1386 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1387 $text = $this->mStripState
->unstripGeneral( $text );
1389 // Avoid PHP 7.1 warning from passing $this by reference
1393 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1396 # Clean up special characters, only run once, next-to-last before doBlockLevels
1397 $text = Sanitizer
::armorFrenchSpaces( $text );
1399 $text = $this->doBlockLevels( $text, $linestart );
1401 $this->replaceLinkHolders( $text );
1404 * The input doesn't get language converted if
1406 * b) Content isn't converted
1407 * c) It's a conversion table
1408 * d) it is an interface message (which is in the user language)
1410 if ( !( $this->mOptions
->getDisableContentConversion()
1411 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1413 if ( !$this->mOptions
->getInterfaceMessage() ) {
1414 # The position of the convert() call should not be changed. it
1415 # assumes that the links are all replaced and the only thing left
1416 # is the <nowiki> mark.
1417 $text = $this->getTargetLanguage()->convert( $text );
1421 $text = $this->mStripState
->unstripNoWiki( $text );
1424 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1427 $text = $this->replaceTransparentTags( $text );
1428 $text = $this->mStripState
->unstripGeneral( $text );
1430 $text = Sanitizer
::normalizeCharReferences( $text );
1432 if ( MWTidy
::isEnabled() ) {
1433 if ( $this->mOptions
->getTidy() ) {
1434 $text = MWTidy
::tidy( $text );
1437 # attempt to sanitize at least some nesting problems
1438 # (T4702 and quite a few others)
1440 # ''Something [http://www.cool.com cool''] -->
1441 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1442 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1443 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1444 # fix up an anchor inside another anchor, only
1445 # at least for a single single nested link (T5695)
1446 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1447 '\\1\\2</a>\\3</a>\\1\\4</a>',
1448 # fix div inside inline elements- doBlockLevels won't wrap a line which
1449 # contains a div, so fix it up here; replace
1450 # div with escaped text
1451 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1452 '\\1\\3<div\\5>\\6</div>\\8\\9',
1453 # remove empty italic or bold tag pairs, some
1454 # introduced by rules above
1455 '/<([bi])><\/\\1>/' => '',
1458 $text = preg_replace(
1459 array_keys( $tidyregs ),
1460 array_values( $tidyregs ),
1465 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1472 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1473 * magic external links.
1478 * @param string $text
1482 public function doMagicLinks( $text ) {
1483 $prots = wfUrlProtocolsWithoutProtRel();
1484 $urlChar = self
::EXT_LINK_URL_CLASS
;
1485 $addr = self
::EXT_LINK_ADDR
;
1486 $space = self
::SPACE_NOT_NL
; # non-newline space
1487 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1488 $spaces = "$space++"; # possessive match of 1 or more spaces
1489 $text = preg_replace_callback(
1491 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1492 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1493 (\b # m[3]: Free external links
1495 ($addr$urlChar*) # m[4]: Post-protocol path
1497 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1499 \bISBN $spaces ( # m[6]: ISBN, capture number
1500 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1501 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1502 [0-9Xx] # check digit
1504 )!xu", [ $this, 'magicLinkCallback' ], $text );
1509 * @throws MWException
1511 * @return string HTML
1513 public function magicLinkCallback( $m ) {
1514 if ( isset( $m[1] ) && $m[1] !== '' ) {
1517 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1520 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1521 # Free external link
1522 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1523 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1525 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1526 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1531 $cssClass = 'mw-magiclink-rfc';
1532 $trackingCat = 'magiclink-tracking-rfc';
1534 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1535 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1539 $urlmsg = 'pubmedurl';
1540 $cssClass = 'mw-magiclink-pmid';
1541 $trackingCat = 'magiclink-tracking-pmid';
1544 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1545 substr( $m[0], 0, 20 ) . '"' );
1547 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1548 $this->addTrackingCategory( $trackingCat );
1549 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1550 } elseif ( isset( $m[6] ) && $m[6] !== ''
1551 && $this->mOptions
->getMagicISBNLinks()
1555 $space = self
::SPACE_NOT_NL
; # non-newline space
1556 $isbn = preg_replace( "/$space/", ' ', $isbn );
1557 $num = strtr( $isbn, [
1562 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1563 return $this->getLinkRenderer()->makeKnownLink(
1564 SpecialPage
::getTitleFor( 'Booksources', $num ),
1567 'class' => 'internal mw-magiclink-isbn',
1568 'title' => false // suppress title attribute
1577 * Make a free external link, given a user-supplied URL
1579 * @param string $url
1580 * @param int $numPostProto
1581 * The number of characters after the protocol.
1582 * @return string HTML
1585 public function makeFreeExternalLink( $url, $numPostProto ) {
1588 # The characters '<' and '>' (which were escaped by
1589 # removeHTMLtags()) should not be included in
1590 # URLs, per RFC 2396.
1591 # Make terminate a URL as well (bug T84937)
1594 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1599 $trail = substr( $url, $m2[0][1] ) . $trail;
1600 $url = substr( $url, 0, $m2[0][1] );
1603 # Move trailing punctuation to $trail
1605 # If there is no left bracket, then consider right brackets fair game too
1606 if ( strpos( $url, '(' ) === false ) {
1610 $urlRev = strrev( $url );
1611 $numSepChars = strspn( $urlRev, $sep );
1612 # Don't break a trailing HTML entity by moving the ; into $trail
1613 # This is in hot code, so use substr_compare to avoid having to
1614 # create a new string object for the comparison
1615 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1616 # more optimization: instead of running preg_match with a $
1617 # anchor, which can be slow, do the match on the reversed
1618 # string starting at the desired offset.
1619 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1620 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1624 if ( $numSepChars ) {
1625 $trail = substr( $url, -$numSepChars ) . $trail;
1626 $url = substr( $url, 0, -$numSepChars );
1629 # Verify that we still have a real URL after trail removal, and
1630 # not just lone protocol
1631 if ( strlen( $trail ) >= $numPostProto ) {
1632 return $url . $trail;
1635 $url = Sanitizer
::cleanUrl( $url );
1637 # Is this an external image?
1638 $text = $this->maybeMakeExternalImage( $url );
1639 if ( $text === false ) {
1640 # Not an image, make a link
1641 $text = Linker
::makeExternalLink( $url,
1642 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1644 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1645 # Register it in the output object...
1646 $this->mOutput
->addExternalLink( $url );
1648 return $text . $trail;
1652 * Parse headers and return html
1656 * @param string $text
1660 public function doHeadings( $text ) {
1661 for ( $i = 6; $i >= 1; --$i ) {
1662 $h = str_repeat( '=', $i );
1663 // Trim non-newline whitespace from headings
1664 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1665 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1671 * Replace single quotes with HTML markup
1674 * @param string $text
1676 * @return string The altered text
1678 public function doAllQuotes( $text ) {
1680 $lines = StringUtils
::explode( "\n", $text );
1681 foreach ( $lines as $line ) {
1682 $outtext .= $this->doQuotes( $line ) . "\n";
1684 $outtext = substr( $outtext, 0, -1 );
1689 * Helper function for doAllQuotes()
1691 * @param string $text
1695 public function doQuotes( $text ) {
1696 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1697 $countarr = count( $arr );
1698 if ( $countarr == 1 ) {
1702 // First, do some preliminary work. This may shift some apostrophes from
1703 // being mark-up to being text. It also counts the number of occurrences
1704 // of bold and italics mark-ups.
1707 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1708 $thislen = strlen( $arr[$i] );
1709 // If there are ever four apostrophes, assume the first is supposed to
1710 // be text, and the remaining three constitute mark-up for bold text.
1711 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1712 if ( $thislen == 4 ) {
1713 $arr[$i - 1] .= "'";
1716 } elseif ( $thislen > 5 ) {
1717 // If there are more than 5 apostrophes in a row, assume they're all
1718 // text except for the last 5.
1719 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1720 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1724 // Count the number of occurrences of bold and italics mark-ups.
1725 if ( $thislen == 2 ) {
1727 } elseif ( $thislen == 3 ) {
1729 } elseif ( $thislen == 5 ) {
1735 // If there is an odd number of both bold and italics, it is likely
1736 // that one of the bold ones was meant to be an apostrophe followed
1737 // by italics. Which one we cannot know for certain, but it is more
1738 // likely to be one that has a single-letter word before it.
1739 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1740 $firstsingleletterword = -1;
1741 $firstmultiletterword = -1;
1743 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1744 if ( strlen( $arr[$i] ) == 3 ) {
1745 $x1 = substr( $arr[$i - 1], -1 );
1746 $x2 = substr( $arr[$i - 1], -2, 1 );
1747 if ( $x1 === ' ' ) {
1748 if ( $firstspace == -1 ) {
1751 } elseif ( $x2 === ' ' ) {
1752 $firstsingleletterword = $i;
1753 // if $firstsingleletterword is set, we don't
1754 // look at the other options, so we can bail early.
1757 if ( $firstmultiletterword == -1 ) {
1758 $firstmultiletterword = $i;
1764 // If there is a single-letter word, use it!
1765 if ( $firstsingleletterword > -1 ) {
1766 $arr[$firstsingleletterword] = "''";
1767 $arr[$firstsingleletterword - 1] .= "'";
1768 } elseif ( $firstmultiletterword > -1 ) {
1769 // If not, but there's a multi-letter word, use that one.
1770 $arr[$firstmultiletterword] = "''";
1771 $arr[$firstmultiletterword - 1] .= "'";
1772 } elseif ( $firstspace > -1 ) {
1773 // ... otherwise use the first one that has neither.
1774 // (notice that it is possible for all three to be -1 if, for example,
1775 // there is only one pentuple-apostrophe in the line)
1776 $arr[$firstspace] = "''";
1777 $arr[$firstspace - 1] .= "'";
1781 // Now let's actually convert our apostrophic mush to HTML!
1786 foreach ( $arr as $r ) {
1787 if ( ( $i %
2 ) == 0 ) {
1788 if ( $state === 'both' ) {
1794 $thislen = strlen( $r );
1795 if ( $thislen == 2 ) {
1796 if ( $state === 'i' ) {
1799 } elseif ( $state === 'bi' ) {
1802 } elseif ( $state === 'ib' ) {
1803 $output .= '</b></i><b>';
1805 } elseif ( $state === 'both' ) {
1806 $output .= '<b><i>' . $buffer . '</i>';
1808 } else { // $state can be 'b' or ''
1812 } elseif ( $thislen == 3 ) {
1813 if ( $state === 'b' ) {
1816 } elseif ( $state === 'bi' ) {
1817 $output .= '</i></b><i>';
1819 } elseif ( $state === 'ib' ) {
1822 } elseif ( $state === 'both' ) {
1823 $output .= '<i><b>' . $buffer . '</b>';
1825 } else { // $state can be 'i' or ''
1829 } elseif ( $thislen == 5 ) {
1830 if ( $state === 'b' ) {
1831 $output .= '</b><i>';
1833 } elseif ( $state === 'i' ) {
1834 $output .= '</i><b>';
1836 } elseif ( $state === 'bi' ) {
1837 $output .= '</i></b>';
1839 } elseif ( $state === 'ib' ) {
1840 $output .= '</b></i>';
1842 } elseif ( $state === 'both' ) {
1843 $output .= '<i><b>' . $buffer . '</b></i>';
1845 } else { // ($state == '')
1853 // Now close all remaining tags. Notice that the order is important.
1854 if ( $state === 'b' ||
$state === 'ib' ) {
1857 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1860 if ( $state === 'bi' ) {
1863 // There might be lonely ''''', so make sure we have a buffer
1864 if ( $state === 'both' && $buffer ) {
1865 $output .= '<b><i>' . $buffer . '</i></b>';
1871 * Replace external links (REL)
1873 * Note: this is all very hackish and the order of execution matters a lot.
1874 * Make sure to run tests/parser/parserTests.php if you change this code.
1878 * @param string $text
1880 * @throws MWException
1883 public function replaceExternalLinks( $text ) {
1884 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1885 if ( $bits === false ) {
1886 throw new MWException( "PCRE needs to be compiled with "
1887 . "--enable-unicode-properties in order for MediaWiki to function" );
1889 $s = array_shift( $bits );
1892 while ( $i < count( $bits ) ) {
1895 $text = $bits[$i++
];
1896 $trail = $bits[$i++
];
1898 # The characters '<' and '>' (which were escaped by
1899 # removeHTMLtags()) should not be included in
1900 # URLs, per RFC 2396.
1902 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1903 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1904 $url = substr( $url, 0, $m2[0][1] );
1907 # If the link text is an image URL, replace it with an <img> tag
1908 # This happened by accident in the original parser, but some people used it extensively
1909 $img = $this->maybeMakeExternalImage( $text );
1910 if ( $img !== false ) {
1916 # Set linktype for CSS
1919 # No link text, e.g. [http://domain.tld/some.link]
1920 if ( $text == '' ) {
1922 $langObj = $this->getTargetLanguage();
1923 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1924 $linktype = 'autonumber';
1926 # Have link text, e.g. [http://domain.tld/some.link text]s
1928 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1931 // Excluding protocol-relative URLs may avoid many false positives.
1932 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1933 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1936 $url = Sanitizer
::cleanUrl( $url );
1938 # Use the encoded URL
1939 # This means that users can paste URLs directly into the text
1940 # Funny characters like ö aren't valid in URLs anyway
1941 # This was changed in August 2004
1942 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1943 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1945 # Register link in the output object.
1946 $this->mOutput
->addExternalLink( $url );
1953 * Get the rel attribute for a particular external link.
1956 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1957 * nofollow if appropriate
1958 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1959 * @return string|null Rel attribute for $url
1961 public static function getExternalLinkRel( $url = false, $title = null ) {
1962 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1963 $ns = $title ?
$title->getNamespace() : false;
1964 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1965 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1973 * Get an associative array of additional HTML attributes appropriate for a
1974 * particular external link. This currently may include rel => nofollow
1975 * (depending on configuration, namespace, and the URL's domain) and/or a
1976 * target attribute (depending on configuration).
1978 * @param string $url URL to extract the domain from for rel =>
1979 * nofollow if appropriate
1980 * @return array Associative array of HTML attributes
1982 public function getExternalLinkAttribs( $url ) {
1984 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1986 $target = $this->mOptions
->getExternalLinkTarget();
1988 $attribs['target'] = $target;
1989 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1990 // T133507. New windows can navigate parent cross-origin.
1991 // Including noreferrer due to lacking browser
1992 // support of noopener. Eventually noreferrer should be removed.
1993 if ( $rel !== '' ) {
1996 $rel .= 'noreferrer noopener';
1999 $attribs['rel'] = $rel;
2004 * Replace unusual escape codes in a URL with their equivalent characters
2006 * This generally follows the syntax defined in RFC 3986, with special
2007 * consideration for HTTP query strings.
2009 * @param string $url
2012 public static function normalizeLinkUrl( $url ) {
2013 # First, make sure unsafe characters are encoded
2014 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2016 return rawurlencode( $m[0] );
2022 $end = strlen( $url );
2024 # Fragment part - 'fragment'
2025 $start = strpos( $url, '#' );
2026 if ( $start !== false && $start < $end ) {
2027 $ret = self
::normalizeUrlComponent(
2028 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2032 # Query part - 'query' minus &=+;
2033 $start = strpos( $url, '?' );
2034 if ( $start !== false && $start < $end ) {
2035 $ret = self
::normalizeUrlComponent(
2036 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2040 # Scheme and path part - 'pchar'
2041 # (we assume no userinfo or encoded colons in the host)
2042 $ret = self
::normalizeUrlComponent(
2043 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2048 private static function normalizeUrlComponent( $component, $unsafe ) {
2049 $callback = function ( $matches ) use ( $unsafe ) {
2050 $char = urldecode( $matches[0] );
2051 $ord = ord( $char );
2052 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2056 # Leave it escaped, but use uppercase for a-f
2057 return strtoupper( $matches[0] );
2060 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2064 * make an image if it's allowed, either through the global
2065 * option, through the exception, or through the on-wiki whitelist
2067 * @param string $url
2071 private function maybeMakeExternalImage( $url ) {
2072 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2073 $imagesexception = !empty( $imagesfrom );
2075 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2076 if ( $imagesexception && is_array( $imagesfrom ) ) {
2077 $imagematch = false;
2078 foreach ( $imagesfrom as $match ) {
2079 if ( strpos( $url, $match ) === 0 ) {
2084 } elseif ( $imagesexception ) {
2085 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2087 $imagematch = false;
2090 if ( $this->mOptions
->getAllowExternalImages()
2091 ||
( $imagesexception && $imagematch )
2093 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2095 $text = Linker
::makeExternalImage( $url );
2098 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2099 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2101 $whitelist = explode(
2103 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2106 foreach ( $whitelist as $entry ) {
2107 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2108 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2111 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2112 # Image matches a whitelist entry
2113 $text = Linker
::makeExternalImage( $url );
2122 * Process [[ ]] wikilinks
2126 * @return string Processed text
2130 public function replaceInternalLinks( $s ) {
2131 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2136 * Process [[ ]] wikilinks (RIL)
2138 * @throws MWException
2139 * @return LinkHolderArray
2143 public function replaceInternalLinks2( &$s ) {
2144 global $wgExtraInterlanguageLinkPrefixes;
2146 static $tc = false, $e1, $e1_img;
2147 # the % is needed to support urlencoded titles as well
2149 $tc = Title
::legalChars() . '#%';
2150 # Match a link having the form [[namespace:link|alternate]]trail
2151 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2152 # Match cases where there is no "]]", which might still be images
2153 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2156 $holders = new LinkHolderArray( $this );
2158 # split the entire text string on occurrences of [[
2159 $a = StringUtils
::explode( '[[', ' ' . $s );
2160 # get the first element (all text up to first [[), and remove the space we added
2163 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2164 $s = substr( $s, 1 );
2166 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2168 if ( $useLinkPrefixExtension ) {
2169 # Match the end of a line for a word that's not followed by whitespace,
2170 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2171 $charset = $this->contLang
->linkPrefixCharset();
2172 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2175 if ( is_null( $this->mTitle
) ) {
2176 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2178 $nottalk = !$this->mTitle
->isTalkPage();
2180 if ( $useLinkPrefixExtension ) {
2182 if ( preg_match( $e2, $s, $m ) ) {
2183 $first_prefix = $m[2];
2185 $first_prefix = false;
2191 $useSubpages = $this->areSubpagesAllowed();
2193 # Loop for each link
2194 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2195 # Check for excessive memory usage
2196 if ( $holders->isBig() ) {
2198 # Do the existence check, replace the link holders and clear the array
2199 $holders->replace( $s );
2203 if ( $useLinkPrefixExtension ) {
2204 if ( preg_match( $e2, $s, $m ) ) {
2211 if ( $first_prefix ) {
2212 $prefix = $first_prefix;
2213 $first_prefix = false;
2217 $might_be_img = false;
2219 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2221 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2222 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2223 # the real problem is with the $e1 regex
2225 # Still some problems for cases where the ] is meant to be outside punctuation,
2226 # and no image is in sight. See T4095.
2228 && substr( $m[3], 0, 1 ) === ']'
2229 && strpos( $text, '[' ) !== false
2231 $text .= ']'; # so that replaceExternalLinks($text) works later
2232 $m[3] = substr( $m[3], 1 );
2234 # fix up urlencoded title texts
2235 if ( strpos( $m[1], '%' ) !== false ) {
2236 # Should anchors '#' also be rejected?
2237 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2240 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2241 # Invalid, but might be an image with a link in its caption
2242 $might_be_img = true;
2244 if ( strpos( $m[1], '%' ) !== false ) {
2245 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2248 } else { # Invalid form; output directly
2249 $s .= $prefix . '[[' . $line;
2253 $origLink = ltrim( $m[1], ' ' );
2255 # Don't allow internal links to pages containing
2256 # PROTO: where PROTO is a valid URL protocol; these
2257 # should be external links.
2258 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2259 $s .= $prefix . '[[' . $line;
2263 # Make subpage if necessary
2264 if ( $useSubpages ) {
2265 $link = $this->maybeDoSubpageLink( $origLink, $text );
2270 // \x7f isn't a default legal title char, so most likely strip
2271 // markers will force us into the "invalid form" path above. But,
2272 // just in case, let's assert that xmlish tags aren't valid in
2273 // the title position.
2274 $unstrip = $this->mStripState
->killMarkers( $link );
2275 $noMarkers = ( $unstrip === $link );
2277 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2278 if ( $nt === null ) {
2279 $s .= $prefix . '[[' . $line;
2283 $ns = $nt->getNamespace();
2284 $iw = $nt->getInterwiki();
2286 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2288 if ( $might_be_img ) { # if this is actually an invalid link
2289 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2292 # look at the next 'line' to see if we can close it there
2294 $next_line = $a->current();
2295 if ( $next_line === false ||
$next_line === null ) {
2298 $m = explode( ']]', $next_line, 3 );
2299 if ( count( $m ) == 3 ) {
2300 # the first ]] closes the inner link, the second the image
2302 $text .= "[[{$m[0]}]]{$m[1]}";
2305 } elseif ( count( $m ) == 2 ) {
2306 # if there's exactly one ]] that's fine, we'll keep looking
2307 $text .= "[[{$m[0]}]]{$m[1]}";
2309 # if $next_line is invalid too, we need look no further
2310 $text .= '[[' . $next_line;
2315 # we couldn't find the end of this imageLink, so output it raw
2316 # but don't ignore what might be perfectly normal links in the text we've examined
2317 $holders->merge( $this->replaceInternalLinks2( $text ) );
2318 $s .= "{$prefix}[[$link|$text";
2319 # note: no $trail, because without an end, there *is* no trail
2322 } else { # it's not an image, so output it raw
2323 $s .= "{$prefix}[[$link|$text";
2324 # note: no $trail, because without an end, there *is* no trail
2329 $wasblank = ( $text == '' );
2333 # Strip off leading ':'
2334 $text = substr( $text, 1 );
2337 # T6598 madness. Handle the quotes only if they come from the alternate part
2338 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2339 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2340 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2341 $text = $this->doQuotes( $text );
2344 # Link not escaped by : , create the various objects
2345 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2348 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2349 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2350 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2353 # T26502: filter duplicates
2354 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2355 $this->mLangLinkLanguages
[$iw] = true;
2356 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2360 * Strip the whitespace interwiki links produce, see T10897
2362 $s = rtrim( $s . $prefix ) . $trail; # T175416
2366 if ( $ns == NS_FILE
) {
2367 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2369 # if no parameters were passed, $text
2370 # becomes something like "File:Foo.png",
2371 # which we don't want to pass on to the
2375 # recursively parse links inside the image caption
2376 # actually, this will parse them in any other parameters, too,
2377 # but it might be hard to fix that, and it doesn't matter ATM
2378 $text = $this->replaceExternalLinks( $text );
2379 $holders->merge( $this->replaceInternalLinks2( $text ) );
2381 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2382 $s .= $prefix . $this->armorLinks(
2383 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2386 } elseif ( $ns == NS_CATEGORY
) {
2388 * Strip the whitespace Category links produce, see T2087
2390 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2393 $sortkey = $this->getDefaultSort();
2397 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2398 $sortkey = str_replace( "\n", '', $sortkey );
2399 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2400 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2406 # Self-link checking. For some languages, variants of the title are checked in
2407 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2408 # for linking to a different variant.
2409 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2410 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2414 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2415 # @todo FIXME: Should do batch file existence checks, see comment below
2416 if ( $ns == NS_MEDIA
) {
2417 # Give extensions a chance to select the file revision for us
2420 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2421 [ $this, $nt, &$options, &$descQuery ] );
2422 # Fetch and register the file (file title may be different via hooks)
2423 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2424 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2425 $s .= $prefix . $this->armorLinks(
2426 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2430 # Some titles, such as valid special pages or files in foreign repos, should
2431 # be shown as bluelinks even though they're not included in the page table
2432 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2433 # batch file existence checks for NS_FILE and NS_MEDIA
2434 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2435 $this->mOutput
->addLink( $nt );
2436 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2438 # Links will be added to the output link list after checking
2439 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2446 * Render a forced-blue link inline; protect against double expansion of
2447 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2448 * Since this little disaster has to split off the trail text to avoid
2449 * breaking URLs in the following text without breaking trails on the
2450 * wiki links, it's been made into a horrible function.
2453 * @param string $text
2454 * @param string $trail
2455 * @param string $prefix
2456 * @return string HTML-wikitext mix oh yuck
2458 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2459 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2461 if ( $text == '' ) {
2462 $text = htmlspecialchars( $nt->getPrefixedText() );
2465 $link = $this->getLinkRenderer()->makeKnownLink(
2466 $nt, new HtmlArmor( "$prefix$text$inside" )
2469 return $this->armorLinks( $link ) . $trail;
2473 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2474 * going to go through further parsing steps before inline URL expansion.
2476 * Not needed quite as much as it used to be since free links are a bit
2477 * more sensible these days. But bracketed links are still an issue.
2479 * @param string $text More-or-less HTML
2480 * @return string Less-or-more HTML with NOPARSE bits
2482 public function armorLinks( $text ) {
2483 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2484 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2488 * Return true if subpage links should be expanded on this page.
2491 public function areSubpagesAllowed() {
2492 # Some namespaces don't allow subpages
2493 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2497 * Handle link to subpage if necessary
2499 * @param string $target The source of the link
2500 * @param string &$text The link text, modified as necessary
2501 * @return string The full name of the link
2504 public function maybeDoSubpageLink( $target, &$text ) {
2505 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2509 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2511 * @param string $text
2512 * @param bool $linestart Whether or not this is at the start of a line.
2514 * @return string The lists rendered as HTML
2516 public function doBlockLevels( $text, $linestart ) {
2517 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2521 * Return value of a magic variable (like PAGENAME)
2525 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2526 * @param bool|PPFrame $frame
2528 * @throws MWException
2531 public function getVariableValue( $index, $frame = false ) {
2532 global $wgSitename, $wgServer, $wgServerName;
2533 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2535 if ( is_null( $this->mTitle
) ) {
2536 // If no title set, bad things are going to happen
2537 // later. Title should always be set since this
2538 // should only be called in the middle of a parse
2539 // operation (but the unit-tests do funky stuff)
2540 throw new MWException( __METHOD__
. ' Should only be '
2541 . ' called while parsing (no title set)' );
2544 // Avoid PHP 7.1 warning from passing $this by reference
2548 * Some of these require message or data lookups and can be
2549 * expensive to check many times.
2551 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2552 if ( isset( $this->mVarCache
[$index] ) ) {
2553 return $this->mVarCache
[$index];
2557 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2558 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2560 $pageLang = $this->getFunctionLang();
2566 case 'currentmonth':
2567 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2569 case 'currentmonth1':
2570 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2572 case 'currentmonthname':
2573 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2575 case 'currentmonthnamegen':
2576 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2578 case 'currentmonthabbrev':
2579 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2582 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2585 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2588 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2591 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2593 case 'localmonthname':
2594 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2596 case 'localmonthnamegen':
2597 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2599 case 'localmonthabbrev':
2600 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2603 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2606 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2609 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2612 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2614 case 'fullpagename':
2615 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2617 case 'fullpagenamee':
2618 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2621 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2623 case 'subpagenamee':
2624 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2626 case 'rootpagename':
2627 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2629 case 'rootpagenamee':
2630 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2633 $this->mTitle
->getRootText()
2636 case 'basepagename':
2637 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2639 case 'basepagenamee':
2640 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2643 $this->mTitle
->getBaseText()
2646 case 'talkpagename':
2647 if ( $this->mTitle
->canHaveTalkPage() ) {
2648 $talkPage = $this->mTitle
->getTalkPage();
2649 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2654 case 'talkpagenamee':
2655 if ( $this->mTitle
->canHaveTalkPage() ) {
2656 $talkPage = $this->mTitle
->getTalkPage();
2657 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2662 case 'subjectpagename':
2663 $subjPage = $this->mTitle
->getSubjectPage();
2664 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2666 case 'subjectpagenamee':
2667 $subjPage = $this->mTitle
->getSubjectPage();
2668 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2670 case 'pageid': // requested in T25427
2671 $pageid = $this->getTitle()->getArticleID();
2672 if ( $pageid == 0 ) {
2673 # 0 means the page doesn't exist in the database,
2674 # which means the user is previewing a new page.
2675 # The vary-revision flag must be set, because the magic word
2676 # will have a different value once the page is saved.
2677 $this->mOutput
->setFlag( 'vary-revision' );
2678 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2680 $value = $pageid ?
: null;
2683 # Let the edit saving system know we should parse the page
2684 # *after* a revision ID has been assigned.
2685 $this->mOutput
->setFlag( 'vary-revision-id' );
2686 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2687 $value = $this->mRevisionId
;
2688 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2689 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2690 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2694 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2696 case 'revisionday2':
2697 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2699 case 'revisionmonth':
2700 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2702 case 'revisionmonth1':
2703 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2705 case 'revisionyear':
2706 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2708 case 'revisiontimestamp':
2709 # Let the edit saving system know we should parse the page
2710 # *after* a revision ID has been assigned. This is for null edits.
2711 $this->mOutput
->setFlag( 'vary-revision' );
2712 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2713 $value = $this->getRevisionTimestamp();
2715 case 'revisionuser':
2716 # Let the edit saving system know we should parse the page
2717 # *after* a revision ID has been assigned for null edits.
2718 $this->mOutput
->setFlag( 'vary-user' );
2719 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2720 $value = $this->getRevisionUser();
2722 case 'revisionsize':
2723 $value = $this->getRevisionSize();
2726 $value = str_replace( '_', ' ',
2727 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2730 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2732 case 'namespacenumber':
2733 $value = $this->mTitle
->getNamespace();
2736 $value = $this->mTitle
->canHaveTalkPage()
2737 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2741 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2743 case 'subjectspace':
2744 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2746 case 'subjectspacee':
2747 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2749 case 'currentdayname':
2750 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2753 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2756 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2759 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2762 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2763 # int to remove the padding
2764 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2767 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2769 case 'localdayname':
2770 $value = $pageLang->getWeekdayName(
2771 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2775 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2778 $value = $pageLang->time(
2779 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2785 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2788 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2789 # int to remove the padding
2790 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2793 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2795 case 'numberofarticles':
2796 $value = $pageLang->formatNum( SiteStats
::articles() );
2798 case 'numberoffiles':
2799 $value = $pageLang->formatNum( SiteStats
::images() );
2801 case 'numberofusers':
2802 $value = $pageLang->formatNum( SiteStats
::users() );
2804 case 'numberofactiveusers':
2805 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2807 case 'numberofpages':
2808 $value = $pageLang->formatNum( SiteStats
::pages() );
2810 case 'numberofadmins':
2811 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2813 case 'numberofedits':
2814 $value = $pageLang->formatNum( SiteStats
::edits() );
2816 case 'currenttimestamp':
2817 $value = wfTimestamp( TS_MW
, $ts );
2819 case 'localtimestamp':
2820 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2822 case 'currentversion':
2823 $value = SpecialVersion
::getVersion();
2826 return $wgArticlePath;
2832 return $wgServerName;
2834 return $wgScriptPath;
2836 return $wgStylePath;
2837 case 'directionmark':
2838 return $pageLang->getDirMark();
2839 case 'contentlanguage':
2840 global $wgLanguageCode;
2841 return $wgLanguageCode;
2842 case 'pagelanguage':
2843 $value = $pageLang->getCode();
2845 case 'cascadingsources':
2846 $value = CoreParserFunctions
::cascadingsources( $this );
2851 'ParserGetVariableValueSwitch',
2852 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2859 $this->mVarCache
[$index] = $value;
2868 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2869 * @param string $variable Parser variable name
2872 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2873 # Get the timezone-adjusted timestamp to be used for this revision
2874 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2875 # Possibly set vary-revision if there is not yet an associated revision
2876 if ( !$this->getRevisionObject() ) {
2877 # Get the timezone-adjusted timestamp $mtts seconds in the future
2879 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2884 if ( $resNow !== $resThen ) {
2885 # Let the edit saving system know we should parse the page
2886 # *after* a revision ID has been assigned. This is for null edits.
2887 $this->mOutput
->setFlag( 'vary-revision' );
2888 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2896 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2900 public function initialiseVariables() {
2901 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2902 $substIDs = $this->magicWordFactory
->getSubstIDs();
2904 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2905 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2909 * Preprocess some wikitext and return the document tree.
2910 * This is the ghost of replace_variables().
2912 * @param string $text The text to parse
2913 * @param int $flags Bitwise combination of:
2914 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2915 * included. Default is to assume a direct page view.
2917 * The generated DOM tree must depend only on the input text and the flags.
2918 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2920 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2921 * change in the DOM tree for a given text, must be passed through the section identifier
2922 * in the section edit link and thus back to extractSections().
2924 * The output of this function is currently only cached in process memory, but a persistent
2925 * cache may be implemented at a later date which takes further advantage of these strict
2926 * dependency requirements.
2930 public function preprocessToDom( $text, $flags = 0 ) {
2931 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2936 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2942 public static function splitWhitespace( $s ) {
2943 $ltrimmed = ltrim( $s );
2944 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2945 $trimmed = rtrim( $ltrimmed );
2946 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2948 $w2 = substr( $ltrimmed, -$diff );
2952 return [ $w1, $trimmed, $w2 ];
2956 * Replace magic variables, templates, and template arguments
2957 * with the appropriate text. Templates are substituted recursively,
2958 * taking care to avoid infinite loops.
2960 * Note that the substitution depends on value of $mOutputType:
2961 * self::OT_WIKI: only {{subst:}} templates
2962 * self::OT_PREPROCESS: templates but not extension tags
2963 * self::OT_HTML: all templates and extension tags
2965 * @param string $text The text to transform
2966 * @param bool|PPFrame $frame Object describing the arguments passed to the
2967 * template. Arguments may also be provided as an associative array, as
2968 * was the usual case before MW1.12. Providing arguments this way may be
2969 * useful for extensions wishing to perform variable replacement
2971 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2972 * double-brace expansion.
2975 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2976 # Is there any text? Also, Prevent too big inclusions!
2977 $textSize = strlen( $text );
2978 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2982 if ( $frame === false ) {
2983 $frame = $this->getPreprocessor()->newFrame();
2984 } elseif ( !( $frame instanceof PPFrame
) ) {
2985 wfDebug( __METHOD__
. " called using plain parameters instead of "
2986 . "a PPFrame instance. Creating custom frame.\n" );
2987 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2990 $dom = $this->preprocessToDom( $text );
2991 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2992 $text = $frame->expand( $dom, $flags );
2998 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3000 * @param array $args
3004 public static function createAssocArgs( $args ) {
3007 foreach ( $args as $arg ) {
3008 $eqpos = strpos( $arg, '=' );
3009 if ( $eqpos === false ) {
3010 $assocArgs[$index++
] = $arg;
3012 $name = trim( substr( $arg, 0, $eqpos ) );
3013 $value = trim( substr( $arg, $eqpos +
1 ) );
3014 if ( $value === false ) {
3017 if ( $name !== false ) {
3018 $assocArgs[$name] = $value;
3027 * Warn the user when a parser limitation is reached
3028 * Will warn at most once the user per limitation type
3030 * The results are shown during preview and run through the Parser (See EditPage.php)
3032 * @param string $limitationType Should be one of:
3033 * 'expensive-parserfunction' (corresponding messages:
3034 * 'expensive-parserfunction-warning',
3035 * 'expensive-parserfunction-category')
3036 * 'post-expand-template-argument' (corresponding messages:
3037 * 'post-expand-template-argument-warning',
3038 * 'post-expand-template-argument-category')
3039 * 'post-expand-template-inclusion' (corresponding messages:
3040 * 'post-expand-template-inclusion-warning',
3041 * 'post-expand-template-inclusion-category')
3042 * 'node-count-exceeded' (corresponding messages:
3043 * 'node-count-exceeded-warning',
3044 * 'node-count-exceeded-category')
3045 * 'expansion-depth-exceeded' (corresponding messages:
3046 * 'expansion-depth-exceeded-warning',
3047 * 'expansion-depth-exceeded-category')
3048 * @param string|int|null $current Current value
3049 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3050 * exceeded, provide the values (optional)
3052 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3053 # does no harm if $current and $max are present but are unnecessary for the message
3054 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3055 # only during preview, and that would split the parser cache unnecessarily.
3056 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3058 $this->mOutput
->addWarning( $warning );
3059 $this->addTrackingCategory( "$limitationType-category" );
3063 * Return the text of a template, after recursively
3064 * replacing any variables or templates within the template.
3066 * @param array $piece The parts of the template
3067 * $piece['title']: the title, i.e. the part before the |
3068 * $piece['parts']: the parameter array
3069 * $piece['lineStart']: whether the brace was at the start of a line
3070 * @param PPFrame $frame The current frame, contains template arguments
3072 * @return string The text of the template
3074 public function braceSubstitution( $piece, $frame ) {
3077 // $text has been filled
3079 // wiki markup in $text should be escaped
3081 // $text is HTML, armour it against wikitext transformation
3083 // Force interwiki transclusion to be done in raw mode not rendered
3084 $forceRawInterwiki = false;
3085 // $text is a DOM node needing expansion in a child frame
3086 $isChildObj = false;
3087 // $text is a DOM node needing expansion in the current frame
3088 $isLocalObj = false;
3090 # Title object, where $text came from
3093 # $part1 is the bit before the first |, and must contain only title characters.
3094 # Various prefixes will be stripped from it later.
3095 $titleWithSpaces = $frame->expand( $piece['title'] );
3096 $part1 = trim( $titleWithSpaces );
3099 # Original title text preserved for various purposes
3100 $originalTitle = $part1;
3102 # $args is a list of argument nodes, starting from index 0, not including $part1
3103 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3104 # below won't work b/c this $args isn't an object
3105 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3107 $profileSection = null; // profile templates
3111 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3113 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3114 # Decide whether to expand template or keep wikitext as-is.
3115 if ( $this->ot
['wiki'] ) {
3116 if ( $substMatch === false ) {
3117 $literal = true; # literal when in PST with no prefix
3119 $literal = false; # expand when in PST with subst: or safesubst:
3122 if ( $substMatch == 'subst' ) {
3123 $literal = true; # literal when not in PST with plain subst:
3125 $literal = false; # expand when not in PST with safesubst: or no prefix
3129 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3136 if ( !$found && $args->getLength() == 0 ) {
3137 $id = $this->mVariables
->matchStartToEnd( $part1 );
3138 if ( $id !== false ) {
3139 $text = $this->getVariableValue( $id, $frame );
3140 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3141 $this->mOutput
->updateCacheExpiry(
3142 $this->magicWordFactory
->getCacheTTL( $id ) );
3148 # MSG, MSGNW and RAW
3151 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3152 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3155 # Remove obsolete MSG:
3156 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3157 $mwMsg->matchStartAndRemove( $part1 );
3161 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3162 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3163 $forceRawInterwiki = true;
3169 $colonPos = strpos( $part1, ':' );
3170 if ( $colonPos !== false ) {
3171 $func = substr( $part1, 0, $colonPos );
3172 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3173 $argsLength = $args->getLength();
3174 for ( $i = 0; $i < $argsLength; $i++
) {
3175 $funcArgs[] = $args->item( $i );
3178 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3180 // Extract any forwarded flags
3181 if ( isset( $result['title'] ) ) {
3182 $title = $result['title'];
3184 if ( isset( $result['found'] ) ) {
3185 $found = $result['found'];
3187 if ( array_key_exists( 'text', $result ) ) {
3189 $text = $result['text'];
3191 if ( isset( $result['nowiki'] ) ) {
3192 $nowiki = $result['nowiki'];
3194 if ( isset( $result['isHTML'] ) ) {
3195 $isHTML = $result['isHTML'];
3197 if ( isset( $result['forceRawInterwiki'] ) ) {
3198 $forceRawInterwiki = $result['forceRawInterwiki'];
3200 if ( isset( $result['isChildObj'] ) ) {
3201 $isChildObj = $result['isChildObj'];
3203 if ( isset( $result['isLocalObj'] ) ) {
3204 $isLocalObj = $result['isLocalObj'];
3209 # Finish mangling title and then check for loops.
3210 # Set $title to a Title object and $titleText to the PDBK
3213 # Split the title into page and subpage
3215 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3216 if ( $part1 !== $relative ) {
3218 $ns = $this->mTitle
->getNamespace();
3220 $title = Title
::newFromText( $part1, $ns );
3222 $titleText = $title->getPrefixedText();
3223 # Check for language variants if the template is not found
3224 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3225 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3227 # Do recursion depth check
3228 $limit = $this->mOptions
->getMaxTemplateDepth();
3229 if ( $frame->depth
>= $limit ) {
3231 $text = '<span class="error">'
3232 . wfMessage( 'parser-template-recursion-depth-warning' )
3233 ->numParams( $limit )->inContentLanguage()->text()
3239 # Load from database
3240 if ( !$found && $title ) {
3241 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3242 if ( !$title->isExternal() ) {
3243 if ( $title->isSpecialPage()
3244 && $this->mOptions
->getAllowSpecialInclusion()
3245 && $this->ot
['html']
3247 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3248 // Pass the template arguments as URL parameters.
3249 // "uselang" will have no effect since the Language object
3250 // is forced to the one defined in ParserOptions.
3252 $argsLength = $args->getLength();
3253 for ( $i = 0; $i < $argsLength; $i++
) {
3254 $bits = $args->item( $i )->splitArg();
3255 if ( strval( $bits['index'] ) === '' ) {
3256 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3257 $value = trim( $frame->expand( $bits['value'] ) );
3258 $pageArgs[$name] = $value;
3262 // Create a new context to execute the special page
3263 $context = new RequestContext
;
3264 $context->setTitle( $title );
3265 $context->setRequest( new FauxRequest( $pageArgs ) );
3266 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3267 $context->setUser( $this->getUser() );
3269 // If this page is cached, then we better not be per user.
3270 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3272 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3273 $ret = SpecialPageFactory
::capturePath(
3274 $title, $context, $this->getLinkRenderer() );
3276 $text = $context->getOutput()->getHTML();
3277 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3280 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3281 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3282 $specialPage->maxIncludeCacheTime()
3286 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3287 $found = false; # access denied
3288 wfDebug( __METHOD__
. ": template inclusion denied for " .
3289 $title->getPrefixedDBkey() . "\n" );
3291 list( $text, $title ) = $this->getTemplateDom( $title );
3292 if ( $text !== false ) {
3298 # If the title is valid but undisplayable, make a link to it
3299 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3300 $text = "[[:$titleText]]";
3303 } elseif ( $title->isTrans() ) {
3304 # Interwiki transclusion
3305 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3306 $text = $this->interwikiTransclude( $title, 'render' );
3309 $text = $this->interwikiTransclude( $title, 'raw' );
3310 # Preprocess it like a template
3311 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3317 # Do infinite loop check
3318 # This has to be done after redirect resolution to avoid infinite loops via redirects
3319 if ( !$frame->loopCheck( $title ) ) {
3321 $text = '<span class="error">'
3322 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3324 $this->addTrackingCategory( 'template-loop-category' );
3325 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3326 wfEscapeWikiText( $titleText ) )->text() );
3327 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3331 # If we haven't found text to substitute by now, we're done
3332 # Recover the source wikitext and return it
3334 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3335 if ( $profileSection ) {
3336 $this->mProfiler
->scopedProfileOut( $profileSection );
3338 return [ 'object' => $text ];
3341 # Expand DOM-style return values in a child frame
3342 if ( $isChildObj ) {
3343 # Clean up argument array
3344 $newFrame = $frame->newChild( $args, $title );
3347 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3348 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3349 # Expansion is eligible for the empty-frame cache
3350 $text = $newFrame->cachedExpand( $titleText, $text );
3352 # Uncached expansion
3353 $text = $newFrame->expand( $text );
3356 if ( $isLocalObj && $nowiki ) {
3357 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3358 $isLocalObj = false;
3361 if ( $profileSection ) {
3362 $this->mProfiler
->scopedProfileOut( $profileSection );
3365 # Replace raw HTML by a placeholder
3367 $text = $this->insertStripItem( $text );
3368 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3369 # Escape nowiki-style return values
3370 $text = wfEscapeWikiText( $text );
3371 } elseif ( is_string( $text )
3372 && !$piece['lineStart']
3373 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3375 # T2529: if the template begins with a table or block-level
3376 # element, it should be treated as beginning a new line.
3377 # This behavior is somewhat controversial.
3378 $text = "\n" . $text;
3381 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3382 # Error, oversize inclusion
3383 if ( $titleText !== false ) {
3384 # Make a working, properly escaped link if possible (T25588)
3385 $text = "[[:$titleText]]";
3387 # This will probably not be a working link, but at least it may
3388 # provide some hint of where the problem is
3389 preg_replace( '/^:/', '', $originalTitle );
3390 $text = "[[:$originalTitle]]";
3392 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3393 . 'post-expand include size too large -->' );
3394 $this->limitationWarn( 'post-expand-template-inclusion' );
3397 if ( $isLocalObj ) {
3398 $ret = [ 'object' => $text ];
3400 $ret = [ 'text' => $text ];
3407 * Call a parser function and return an array with text and flags.
3409 * The returned array will always contain a boolean 'found', indicating
3410 * whether the parser function was found or not. It may also contain the
3412 * text: string|object, resulting wikitext or PP DOM object
3413 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3414 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3415 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3416 * nowiki: bool, wiki markup in $text should be escaped
3419 * @param PPFrame $frame The current frame, contains template arguments
3420 * @param string $function Function name
3421 * @param array $args Arguments to the function
3422 * @throws MWException
3425 public function callParserFunction( $frame, $function, array $args = [] ) {
3426 # Case sensitive functions
3427 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3428 $function = $this->mFunctionSynonyms
[1][$function];
3430 # Case insensitive functions
3431 $function = $this->contLang
->lc( $function );
3432 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3433 $function = $this->mFunctionSynonyms
[0][$function];
3435 return [ 'found' => false ];
3439 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3441 // Avoid PHP 7.1 warning from passing $this by reference
3444 $allArgs = [ &$parser ];
3445 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3446 # Convert arguments to PPNodes and collect for appending to $allArgs
3448 foreach ( $args as $k => $v ) {
3449 if ( $v instanceof PPNode ||
$k === 0 ) {
3452 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3456 # Add a frame parameter, and pass the arguments as an array
3457 $allArgs[] = $frame;
3458 $allArgs[] = $funcArgs;
3460 # Convert arguments to plain text and append to $allArgs
3461 foreach ( $args as $k => $v ) {
3462 if ( $v instanceof PPNode
) {
3463 $allArgs[] = trim( $frame->expand( $v ) );
3464 } elseif ( is_int( $k ) && $k >= 0 ) {
3465 $allArgs[] = trim( $v );
3467 $allArgs[] = trim( "$k=$v" );
3472 $result = $callback( ...$allArgs );
3474 # The interface for function hooks allows them to return a wikitext
3475 # string or an array containing the string and any flags. This mungs
3476 # things around to match what this method should return.
3477 if ( !is_array( $result ) ) {
3483 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3484 $result['text'] = $result[0];
3486 unset( $result[0] );
3493 $preprocessFlags = 0;
3494 if ( isset( $result['noparse'] ) ) {
3495 $noparse = $result['noparse'];
3497 if ( isset( $result['preprocessFlags'] ) ) {
3498 $preprocessFlags = $result['preprocessFlags'];
3502 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3503 $result['isChildObj'] = true;
3510 * Get the semi-parsed DOM representation of a template with a given title,
3511 * and its redirect destination title. Cached.
3513 * @param Title $title
3517 public function getTemplateDom( $title ) {
3518 $cacheTitle = $title;
3519 $titleText = $title->getPrefixedDBkey();
3521 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3522 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3523 $title = Title
::makeTitle( $ns, $dbk );
3524 $titleText = $title->getPrefixedDBkey();
3526 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3527 return [ $this->mTplDomCache
[$titleText], $title ];
3530 # Cache miss, go to the database
3531 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3533 if ( $text === false ) {
3534 $this->mTplDomCache
[$titleText] = false;
3535 return [ false, $title ];
3538 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3539 $this->mTplDomCache
[$titleText] = $dom;
3541 if ( !$title->equals( $cacheTitle ) ) {
3542 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3543 [ $title->getNamespace(), $title->getDBkey() ];
3546 return [ $dom, $title ];
3550 * Fetch the current revision of a given title. Note that the revision
3551 * (and even the title) may not exist in the database, so everything
3552 * contributing to the output of the parser should use this method
3553 * where possible, rather than getting the revisions themselves. This
3554 * method also caches its results, so using it benefits performance.
3557 * @param Title $title
3560 public function fetchCurrentRevisionOfTitle( $title ) {
3561 $cacheKey = $title->getPrefixedDBkey();
3562 if ( !$this->currentRevisionCache
) {
3563 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3565 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3566 $this->currentRevisionCache
->set( $cacheKey,
3567 // Defaults to Parser::statelessFetchRevision()
3568 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3571 return $this->currentRevisionCache
->get( $cacheKey );
3575 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3576 * without passing them on to it.
3579 * @param Title $title
3580 * @param Parser|bool $parser
3581 * @return Revision|bool False if missing
3583 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3584 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3590 * Fetch the unparsed text of a template and register a reference to it.
3591 * @param Title $title
3592 * @return array ( string or false, Title )
3594 public function fetchTemplateAndTitle( $title ) {
3595 // Defaults to Parser::statelessFetchTemplate()
3596 $templateCb = $this->mOptions
->getTemplateCallback();
3597 $stuff = call_user_func( $templateCb, $title, $this );
3598 // We use U+007F DELETE to distinguish strip markers from regular text.
3599 $text = $stuff['text'];
3600 if ( is_string( $stuff['text'] ) ) {
3601 $text = strtr( $text, "\x7f", "?" );
3603 $finalTitle = $stuff['finalTitle'] ??
$title;
3604 if ( isset( $stuff['deps'] ) ) {
3605 foreach ( $stuff['deps'] as $dep ) {
3606 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3607 if ( $dep['title']->equals( $this->getTitle() ) ) {
3608 // If we transclude ourselves, the final result
3609 // will change based on the new version of the page
3610 $this->mOutput
->setFlag( 'vary-revision' );
3614 return [ $text, $finalTitle ];
3618 * Fetch the unparsed text of a template and register a reference to it.
3619 * @param Title $title
3620 * @return string|bool
3622 public function fetchTemplate( $title ) {
3623 return $this->fetchTemplateAndTitle( $title )[0];
3627 * Static function to get a template
3628 * Can be overridden via ParserOptions::setTemplateCallback().
3630 * @param Title $title
3631 * @param bool|Parser $parser
3635 public static function statelessFetchTemplate( $title, $parser = false ) {
3636 $text = $skip = false;
3637 $finalTitle = $title;
3640 # Loop to fetch the article, with up to 1 redirect
3641 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3642 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3643 # Give extensions a chance to select the revision instead
3644 $id = false; # Assume current
3645 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3646 [ $parser, $title, &$skip, &$id ] );
3652 'page_id' => $title->getArticleID(),
3659 $rev = Revision
::newFromId( $id );
3660 } elseif ( $parser ) {
3661 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3663 $rev = Revision
::newFromTitle( $title );
3665 $rev_id = $rev ?
$rev->getId() : 0;
3666 # If there is no current revision, there is no page
3667 if ( $id === false && !$rev ) {
3668 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3669 $linkCache->addBadLinkObj( $title );
3674 'page_id' => $title->getArticleID(),
3675 'rev_id' => $rev_id ];
3676 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3677 # We fetched a rev from a different title; register it too...
3679 'title' => $rev->getTitle(),
3680 'page_id' => $rev->getPage(),
3681 'rev_id' => $rev_id ];
3685 $content = $rev->getContent();
3686 $text = $content ?
$content->getWikitextForTransclusion() : null;
3688 Hooks
::run( 'ParserFetchTemplate',
3689 [ $parser, $title, $rev, &$text, &$deps ] );
3691 if ( $text === false ||
$text === null ) {
3695 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3696 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3697 lcfirst( $title->getText() ) )->inContentLanguage();
3698 if ( !$message->exists() ) {
3702 $content = $message->content();
3703 $text = $message->plain();
3711 $finalTitle = $title;
3712 $title = $content->getRedirectTarget();
3716 'finalTitle' => $finalTitle,
3721 * Fetch a file and its title and register a reference to it.
3722 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3723 * @param Title $title
3724 * @param array $options Array of options to RepoGroup::findFile
3726 * @deprecated since 1.32, use fetchFileAndTitle instead
3728 public function fetchFile( $title, $options = [] ) {
3729 wfDeprecated( __METHOD__
, '1.32' );
3730 return $this->fetchFileAndTitle( $title, $options )[0];
3734 * Fetch a file and its title and register a reference to it.
3735 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3736 * @param Title $title
3737 * @param array $options Array of options to RepoGroup::findFile
3738 * @return array ( File or false, Title of file )
3740 public function fetchFileAndTitle( $title, $options = [] ) {
3741 $file = $this->fetchFileNoRegister( $title, $options );
3743 $time = $file ?
$file->getTimestamp() : false;
3744 $sha1 = $file ?
$file->getSha1() : false;
3745 # Register the file as a dependency...
3746 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3747 if ( $file && !$title->equals( $file->getTitle() ) ) {
3748 # Update fetched file title
3749 $title = $file->getTitle();
3750 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3752 return [ $file, $title ];
3756 * Helper function for fetchFileAndTitle.
3758 * Also useful if you need to fetch a file but not use it yet,
3759 * for example to get the file's handler.
3761 * @param Title $title
3762 * @param array $options Array of options to RepoGroup::findFile
3765 protected function fetchFileNoRegister( $title, $options = [] ) {
3766 if ( isset( $options['broken'] ) ) {
3767 $file = false; // broken thumbnail forced by hook
3768 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3769 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3770 } else { // get by (name,timestamp)
3771 $file = wfFindFile( $title, $options );
3777 * Transclude an interwiki link.
3779 * @param Title $title
3780 * @param string $action
3784 public function interwikiTransclude( $title, $action ) {
3785 global $wgEnableScaryTranscluding;
3787 if ( !$wgEnableScaryTranscluding ) {
3788 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3791 $url = $title->getFullURL( [ 'action' => $action ] );
3793 if ( strlen( $url ) > 255 ) {
3794 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3796 return $this->fetchScaryTemplateMaybeFromCache( $url );
3800 * @param string $url
3801 * @return mixed|string
3803 public function fetchScaryTemplateMaybeFromCache( $url ) {
3804 global $wgTranscludeCacheExpiry;
3805 $dbr = wfGetDB( DB_REPLICA
);
3806 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3807 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3808 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3810 return $obj->tc_contents
;
3813 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3814 $status = $req->execute(); // Status object
3815 if ( $status->isOK() ) {
3816 $text = $req->getContent();
3817 } elseif ( $req->getStatus() != 200 ) {
3818 // Though we failed to fetch the content, this status is useless.
3819 return wfMessage( 'scarytranscludefailed-httpstatus' )
3820 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3822 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3825 $dbw = wfGetDB( DB_MASTER
);
3826 $dbw->replace( 'transcache', [ 'tc_url' ], [
3828 'tc_time' => $dbw->timestamp( time() ),
3829 'tc_contents' => $text
3835 * Triple brace replacement -- used for template arguments
3838 * @param array $piece
3839 * @param PPFrame $frame
3843 public function argSubstitution( $piece, $frame ) {
3845 $parts = $piece['parts'];
3846 $nameWithSpaces = $frame->expand( $piece['title'] );
3847 $argName = trim( $nameWithSpaces );
3849 $text = $frame->getArgument( $argName );
3850 if ( $text === false && $parts->getLength() > 0
3851 && ( $this->ot
['html']
3853 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3856 # No match in frame, use the supplied default
3857 $object = $parts->item( 0 )->getChildren();
3859 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3860 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3861 $this->limitationWarn( 'post-expand-template-argument' );
3864 if ( $text === false && $object === false ) {
3866 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3868 if ( $error !== false ) {
3871 if ( $object !== false ) {
3872 $ret = [ 'object' => $object ];
3874 $ret = [ 'text' => $text ];
3881 * Return the text to be used for a given extension tag.
3882 * This is the ghost of strip().
3884 * @param array $params Associative array of parameters:
3885 * name PPNode for the tag name
3886 * attr PPNode for unparsed text where tag attributes are thought to be
3887 * attributes Optional associative array of parsed attributes
3888 * inner Contents of extension element
3889 * noClose Original text did not have a close tag
3890 * @param PPFrame $frame
3892 * @throws MWException
3895 public function extensionSubstitution( $params, $frame ) {
3896 static $errorStr = '<span class="error">';
3897 static $errorLen = 20;
3899 $name = $frame->expand( $params['name'] );
3900 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3901 // Probably expansion depth or node count exceeded. Just punt the
3906 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3907 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3912 // We can't safely check if the expansion for $content resulted in an
3913 // error, because the content could happen to be the error string
3915 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3917 $marker = self
::MARKER_PREFIX
. "-$name-"
3918 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3920 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3921 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3922 if ( $isFunctionTag ) {
3923 $markerType = 'none';
3925 $markerType = 'general';
3927 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3928 $name = strtolower( $name );
3929 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3930 if ( isset( $params['attributes'] ) ) {
3931 $attributes = $attributes +
$params['attributes'];
3934 if ( isset( $this->mTagHooks
[$name] ) ) {
3935 $output = call_user_func_array( $this->mTagHooks
[$name],
3936 [ $content, $attributes, $this, $frame ] );
3937 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3938 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3940 // Avoid PHP 7.1 warning from passing $this by reference
3942 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3944 $output = '<span class="error">Invalid tag extension name: ' .
3945 htmlspecialchars( $name ) . '</span>';
3948 if ( is_array( $output ) ) {
3951 $output = $flags[0];
3952 if ( isset( $flags['markerType'] ) ) {
3953 $markerType = $flags['markerType'];
3957 if ( is_null( $attrText ) ) {
3960 if ( isset( $params['attributes'] ) ) {
3961 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3962 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3963 htmlspecialchars( $attrValue ) . '"';
3966 if ( $content === null ) {
3967 $output = "<$name$attrText/>";
3969 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3970 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3974 $output = "<$name$attrText>$content$close";
3978 if ( $markerType === 'none' ) {
3980 } elseif ( $markerType === 'nowiki' ) {
3981 $this->mStripState
->addNoWiki( $marker, $output );
3982 } elseif ( $markerType === 'general' ) {
3983 $this->mStripState
->addGeneral( $marker, $output );
3985 throw new MWException( __METHOD__
. ': invalid marker type' );
3991 * Increment an include size counter
3993 * @param string $type The type of expansion
3994 * @param int $size The size of the text
3995 * @return bool False if this inclusion would take it over the maximum, true otherwise
3997 public function incrementIncludeSize( $type, $size ) {
3998 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4001 $this->mIncludeSizes
[$type] +
= $size;
4007 * Increment the expensive function count
4009 * @return bool False if the limit has been exceeded
4011 public function incrementExpensiveFunctionCount() {
4012 $this->mExpensiveFunctionCount++
;
4013 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4017 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4018 * Fills $this->mDoubleUnderscores, returns the modified text
4020 * @param string $text
4024 public function doDoubleUnderscore( $text ) {
4025 # The position of __TOC__ needs to be recorded
4026 $mw = $this->magicWordFactory
->get( 'toc' );
4027 if ( $mw->match( $text ) ) {
4028 $this->mShowToc
= true;
4029 $this->mForceTocPosition
= true;
4031 # Set a placeholder. At the end we'll fill it in with the TOC.
4032 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4034 # Only keep the first one.
4035 $text = $mw->replace( '', $text );
4038 # Now match and remove the rest of them
4039 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4040 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4042 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4043 $this->mOutput
->mNoGallery
= true;
4045 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4046 $this->mShowToc
= false;
4048 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4049 && $this->mTitle
->getNamespace() == NS_CATEGORY
4051 $this->addTrackingCategory( 'hidden-category-category' );
4053 # (T10068) Allow control over whether robots index a page.
4054 # __INDEX__ always overrides __NOINDEX__, see T16899
4055 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4056 $this->mOutput
->setIndexPolicy( 'noindex' );
4057 $this->addTrackingCategory( 'noindex-category' );
4059 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4060 $this->mOutput
->setIndexPolicy( 'index' );
4061 $this->addTrackingCategory( 'index-category' );
4064 # Cache all double underscores in the database
4065 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4066 $this->mOutput
->setProperty( $key, '' );
4073 * @see ParserOutput::addTrackingCategory()
4074 * @param string $msg Message key
4075 * @return bool Whether the addition was successful
4077 public function addTrackingCategory( $msg ) {
4078 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4082 * This function accomplishes several tasks:
4083 * 1) Auto-number headings if that option is enabled
4084 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4085 * 3) Add a Table of contents on the top for users who have enabled the option
4086 * 4) Auto-anchor headings
4088 * It loops through all headlines, collects the necessary data, then splits up the
4089 * string and re-inserts the newly formatted headlines.
4091 * @param string $text
4092 * @param string $origText Original, untouched wikitext
4093 * @param bool $isMain
4094 * @return mixed|string
4097 public function formatHeadings( $text, $origText, $isMain = true ) {
4098 global $wgMaxTocLevel;
4100 # Inhibit editsection links if requested in the page
4101 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4102 $maybeShowEditLink = false;
4104 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4107 # Get all headlines for numbering them and adding funky stuff like [edit]
4108 # links - this is for later, but we need the number of headlines right now
4109 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4110 # be trimmed here since whitespace in HTML headings is significant.
4112 $numMatches = preg_match_all(
4113 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4118 # if there are fewer than 4 headlines in the article, do not show TOC
4119 # unless it's been explicitly enabled.
4120 $enoughToc = $this->mShowToc
&&
4121 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4123 # Allow user to stipulate that a page should have a "new section"
4124 # link added via __NEWSECTIONLINK__
4125 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4126 $this->mOutput
->setNewSection( true );
4129 # Allow user to remove the "new section"
4130 # link via __NONEWSECTIONLINK__
4131 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4132 $this->mOutput
->hideNewSection( true );
4135 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4136 # override above conditions and always show TOC above first header
4137 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4138 $this->mShowToc
= true;
4146 # Ugh .. the TOC should have neat indentation levels which can be
4147 # passed to the skin functions. These are determined here
4151 $sublevelCount = [];
4157 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4158 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4159 $oldType = $this->mOutputType
;
4160 $this->setOutputType( self
::OT_WIKI
);
4161 $frame = $this->getPreprocessor()->newFrame();
4162 $root = $this->preprocessToDom( $origText );
4163 $node = $root->getFirstChild();
4168 $headlines = $numMatches !== false ?
$matches[3] : [];
4170 foreach ( $headlines as $headline ) {
4171 $isTemplate = false;
4173 $sectionIndex = false;
4175 $markerMatches = [];
4176 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4177 $serial = $markerMatches[1];
4178 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4179 $isTemplate = ( $titleText != $baseTitleText );
4180 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4184 $prevlevel = $level;
4186 $level = $matches[1][$headlineCount];
4188 if ( $level > $prevlevel ) {
4189 # Increase TOC level
4191 $sublevelCount[$toclevel] = 0;
4192 if ( $toclevel < $wgMaxTocLevel ) {
4193 $prevtoclevel = $toclevel;
4194 $toc .= Linker
::tocIndent();
4197 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4198 # Decrease TOC level, find level to jump to
4200 for ( $i = $toclevel; $i > 0; $i-- ) {
4201 if ( $levelCount[$i] == $level ) {
4202 # Found last matching level
4205 } elseif ( $levelCount[$i] < $level ) {
4206 # Found first matching level below current level
4214 if ( $toclevel < $wgMaxTocLevel ) {
4215 if ( $prevtoclevel < $wgMaxTocLevel ) {
4216 # Unindent only if the previous toc level was shown :p
4217 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4218 $prevtoclevel = $toclevel;
4220 $toc .= Linker
::tocLineEnd();
4224 # No change in level, end TOC line
4225 if ( $toclevel < $wgMaxTocLevel ) {
4226 $toc .= Linker
::tocLineEnd();
4230 $levelCount[$toclevel] = $level;
4232 # count number of headlines for each level
4233 $sublevelCount[$toclevel]++
;
4235 for ( $i = 1; $i <= $toclevel; $i++
) {
4236 if ( !empty( $sublevelCount[$i] ) ) {
4240 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4245 # The safe header is a version of the header text safe to use for links
4247 # Remove link placeholders by the link text.
4248 # <!--LINK number-->
4250 # link text with suffix
4251 # Do this before unstrip since link text can contain strip markers
4252 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4254 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4255 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4257 # Remove any <style> or <script> tags (T198618)
4258 $safeHeadline = preg_replace(
4259 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4264 # Strip out HTML (first regex removes any tag not allowed)
4266 # * <sup> and <sub> (T10393)
4270 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4271 # * <s> and <strike> (T35715)
4272 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4273 # to allow setting directionality in toc items.
4274 $tocline = preg_replace(
4276 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4277 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4283 # Strip '<span></span>', which is the result from the above if
4284 # <span id="foo"></span> is used to produce an additional anchor
4286 $tocline = str_replace( '<span></span>', '', $tocline );
4288 $tocline = trim( $tocline );
4290 # For the anchor, strip out HTML-y stuff period
4291 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4292 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4294 # Save headline for section edit hint before it's escaped
4295 $headlineHint = $safeHeadline;
4297 # Decode HTML entities
4298 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4300 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4302 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4303 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4304 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4305 if ( $fallbackHeadline === $safeHeadline ) {
4306 # No reason to have both (in fact, we can't)
4307 $fallbackHeadline = false;
4310 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4311 # @todo FIXME: We may be changing them depending on the current locale.
4312 $arrayKey = strtolower( $safeHeadline );
4313 if ( $fallbackHeadline === false ) {
4314 $fallbackArrayKey = false;
4316 $fallbackArrayKey = strtolower( $fallbackHeadline );
4319 # Create the anchor for linking from the TOC to the section
4320 $anchor = $safeHeadline;
4321 $fallbackAnchor = $fallbackHeadline;
4322 if ( isset( $refers[$arrayKey] ) ) {
4323 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4324 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4326 $linkAnchor .= "_$i";
4327 $refers["${arrayKey}_$i"] = true;
4329 $refers[$arrayKey] = true;
4331 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4332 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4333 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4334 $fallbackAnchor .= "_$i";
4335 $refers["${fallbackArrayKey}_$i"] = true;
4337 $refers[$fallbackArrayKey] = true;
4340 # Don't number the heading if it is the only one (looks silly)
4341 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4342 # the two are different if the line contains a link
4343 $headline = Html
::element(
4345 [ 'class' => 'mw-headline-number' ],
4347 ) . ' ' . $headline;
4350 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4351 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4352 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4355 # Add the section to the section tree
4356 # Find the DOM node for this header
4357 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4358 while ( $node && !$noOffset ) {
4359 if ( $node->getName() === 'h' ) {
4360 $bits = $node->splitHeading();
4361 if ( $bits['i'] == $sectionIndex ) {
4365 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4366 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4367 $node = $node->getNextSibling();
4370 'toclevel' => $toclevel,
4373 'number' => $numbering,
4374 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4375 'fromtitle' => $titleText,
4376 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4377 'anchor' => $anchor,
4380 # give headline the correct <h#> tag
4381 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4382 // Output edit section links as markers with styles that can be customized by skins
4383 if ( $isTemplate ) {
4384 # Put a T flag in the section identifier, to indicate to extractSections()
4385 # that sections inside <includeonly> should be counted.
4386 $editsectionPage = $titleText;
4387 $editsectionSection = "T-$sectionIndex";
4388 $editsectionContent = null;
4390 $editsectionPage = $this->mTitle
->getPrefixedText();
4391 $editsectionSection = $sectionIndex;
4392 $editsectionContent = $headlineHint;
4394 // We use a bit of pesudo-xml for editsection markers. The
4395 // language converter is run later on. Using a UNIQ style marker
4396 // leads to the converter screwing up the tokens when it
4397 // converts stuff. And trying to insert strip tags fails too. At
4398 // this point all real inputted tags have already been escaped,
4399 // so we don't have to worry about a user trying to input one of
4400 // these markers directly. We use a page and section attribute
4401 // to stop the language converter from converting these
4402 // important bits of data, but put the headline hint inside a
4403 // content block because the language converter is supposed to
4404 // be able to convert that piece of data.
4405 // Gets replaced with html in ParserOutput::getText
4406 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4407 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4408 if ( $editsectionContent !== null ) {
4409 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4416 $head[$headlineCount] = Linker
::makeHeadline( $level,
4417 $matches['attrib'][$headlineCount], $anchor, $headline,
4418 $editlink, $fallbackAnchor );
4423 $this->setOutputType( $oldType );
4425 # Never ever show TOC if no headers
4426 if ( $numVisible < 1 ) {
4431 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4432 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4434 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4435 $this->mOutput
->setTOCHTML( $toc );
4436 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4440 $this->mOutput
->setSections( $tocraw );
4443 # split up and insert constructed headlines
4444 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4447 // build an array of document sections
4449 foreach ( $blocks as $block ) {
4450 // $head is zero-based, sections aren't.
4451 if ( empty( $head[$i - 1] ) ) {
4452 $sections[$i] = $block;
4454 $sections[$i] = $head[$i - 1] . $block;
4458 * Send a hook, one per section.
4459 * The idea here is to be able to make section-level DIVs, but to do so in a
4460 * lower-impact, more correct way than r50769
4463 * $section : the section number
4464 * &$sectionContent : ref to the content of the section
4465 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4467 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4472 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4473 // append the TOC at the beginning
4474 // Top anchor now in skin
4475 $sections[0] = $sections[0] . $toc . "\n";
4478 $full .= implode( '', $sections );
4480 if ( $this->mForceTocPosition
) {
4481 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4488 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4489 * conversion, substituting signatures, {{subst:}} templates, etc.
4491 * @param string $text The text to transform
4492 * @param Title $title The Title object for the current article
4493 * @param User $user The User object describing the current user
4494 * @param ParserOptions $options Parsing options
4495 * @param bool $clearState Whether to clear the parser state first
4496 * @return string The altered wiki markup
4498 public function preSaveTransform( $text, Title
$title, User
$user,
4499 ParserOptions
$options, $clearState = true
4501 if ( $clearState ) {
4502 $magicScopeVariable = $this->lock();
4504 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4505 $this->setUser( $user );
4507 // Strip U+0000 NULL (T159174)
4508 $text = str_replace( "\000", '', $text );
4510 // We still normalize line endings for backwards-compatibility
4511 // with other code that just calls PST, but this should already
4512 // be handled in TextContent subclasses
4513 $text = TextContent
::normalizeLineEndings( $text );
4515 if ( $options->getPreSaveTransform() ) {
4516 $text = $this->pstPass2( $text, $user );
4518 $text = $this->mStripState
->unstripBoth( $text );
4520 $this->setUser( null ); # Reset
4526 * Pre-save transform helper function
4528 * @param string $text
4533 private function pstPass2( $text, $user ) {
4534 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4535 # $this->contLang here in order to give everyone the same signature and use the default one
4536 # rather than the one selected in each user's preferences. (see also T14815)
4537 $ts = $this->mOptions
->getTimestamp();
4538 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4539 $ts = $timestamp->format( 'YmdHis' );
4540 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4542 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4544 # Variable replacement
4545 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4546 $text = $this->replaceVariables( $text );
4548 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4549 # which may corrupt this parser instance via its wfMessage()->text() call-
4552 if ( strpos( $text, '~~~' ) !== false ) {
4553 $sigText = $this->getUserSig( $user );
4554 $text = strtr( $text, [
4556 '~~~~' => "$sigText $d",
4559 # The main two signature forms used above are time-sensitive
4560 $this->mOutput
->setFlag( 'user-signature' );
4563 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4564 $tc = '[' . Title
::legalChars() . ']';
4565 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4567 // [[ns:page (context)|]]
4568 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4569 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4570 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4571 // [[ns:page (context), context|]] (using either single or double-width comma)
4572 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4573 // [[|page]] (reverse pipe trick: add context from page title)
4574 $p2 = "/\[\[\\|($tc+)]]/";
4576 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4577 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4578 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4579 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4581 $t = $this->mTitle
->getText();
4583 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4584 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4585 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4586 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4588 # if there's no context, don't bother duplicating the title
4589 $text = preg_replace( $p2, '[[\\1]]', $text );
4596 * Fetch the user's signature text, if any, and normalize to
4597 * validated, ready-to-insert wikitext.
4598 * If you have pre-fetched the nickname or the fancySig option, you can
4599 * specify them here to save a database query.
4600 * Do not reuse this parser instance after calling getUserSig(),
4601 * as it may have changed if it's the $wgParser.
4603 * @param User &$user
4604 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4605 * @param bool|null $fancySig whether the nicknname is the complete signature
4606 * or null to use default value
4609 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4610 global $wgMaxSigChars;
4612 $username = $user->getName();
4614 # If not given, retrieve from the user object.
4615 if ( $nickname === false ) {
4616 $nickname = $user->getOption( 'nickname' );
4619 if ( is_null( $fancySig ) ) {
4620 $fancySig = $user->getBoolOption( 'fancysig' );
4623 $nickname = $nickname == null ?
$username : $nickname;
4625 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4626 $nickname = $username;
4627 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4628 } elseif ( $fancySig !== false ) {
4629 # Sig. might contain markup; validate this
4630 if ( $this->validateSig( $nickname ) !== false ) {
4631 # Validated; clean up (if needed) and return it
4632 return $this->cleanSig( $nickname, true );
4634 # Failed to validate; fall back to the default
4635 $nickname = $username;
4636 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4640 # Make sure nickname doesnt get a sig in a sig
4641 $nickname = self
::cleanSigInSig( $nickname );
4643 # If we're still here, make it a link to the user page
4644 $userText = wfEscapeWikiText( $username );
4645 $nickText = wfEscapeWikiText( $nickname );
4646 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4648 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4649 ->title( $this->getTitle() )->text();
4653 * Check that the user's signature contains no bad XML
4655 * @param string $text
4656 * @return string|bool An expanded string, or false if invalid.
4658 public function validateSig( $text ) {
4659 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4663 * Clean up signature text
4665 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4666 * 2) Substitute all transclusions
4668 * @param string $text
4669 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4670 * @return string Signature text
4672 public function cleanSig( $text, $parsing = false ) {
4675 $magicScopeVariable = $this->lock();
4676 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4679 # Option to disable this feature
4680 if ( !$this->mOptions
->getCleanSignatures() ) {
4684 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4685 # => Move this logic to braceSubstitution()
4686 $substWord = $this->magicWordFactory
->get( 'subst' );
4687 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4688 $substText = '{{' . $substWord->getSynonym( 0 );
4690 $text = preg_replace( $substRegex, $substText, $text );
4691 $text = self
::cleanSigInSig( $text );
4692 $dom = $this->preprocessToDom( $text );
4693 $frame = $this->getPreprocessor()->newFrame();
4694 $text = $frame->expand( $dom );
4697 $text = $this->mStripState
->unstripBoth( $text );
4704 * Strip 3, 4 or 5 tildes out of signatures.
4706 * @param string $text
4707 * @return string Signature text with /~{3,5}/ removed
4709 public static function cleanSigInSig( $text ) {
4710 $text = preg_replace( '/~{3,5}/', '', $text );
4715 * Set up some variables which are usually set up in parse()
4716 * so that an external function can call some class members with confidence
4718 * @param Title|null $title
4719 * @param ParserOptions $options
4720 * @param int $outputType
4721 * @param bool $clearState
4723 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4724 $outputType, $clearState = true
4726 $this->startParse( $title, $options, $outputType, $clearState );
4730 * @param Title|null $title
4731 * @param ParserOptions $options
4732 * @param int $outputType
4733 * @param bool $clearState
4735 private function startParse( Title
$title = null, ParserOptions
$options,
4736 $outputType, $clearState = true
4738 $this->setTitle( $title );
4739 $this->mOptions
= $options;
4740 $this->setOutputType( $outputType );
4741 if ( $clearState ) {
4742 $this->clearState();
4747 * Wrapper for preprocess()
4749 * @param string $text The text to preprocess
4750 * @param ParserOptions $options
4751 * @param Title|null $title Title object or null to use $wgTitle
4754 public function transformMsg( $text, $options, $title = null ) {
4755 static $executing = false;
4757 # Guard against infinite recursion
4768 $text = $this->preprocess( $text, $title, $options );
4775 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4776 * The callback should have the following form:
4777 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4779 * Transform and return $text. Use $parser for any required context, e.g. use
4780 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4782 * Hooks may return extended information by returning an array, of which the
4783 * first numbered element (index 0) must be the return string, and all other
4784 * entries are extracted into local variables within an internal function
4785 * in the Parser class.
4787 * This interface (introduced r61913) appears to be undocumented, but
4788 * 'markerType' is used by some core tag hooks to override which strip
4789 * array their results are placed in. **Use great caution if attempting
4790 * this interface, as it is not documented and injudicious use could smash
4791 * private variables.**
4793 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4794 * @param callable $callback The callback function (and object) to use for the tag
4795 * @throws MWException
4796 * @return callable|null The old value of the mTagHooks array associated with the hook
4798 public function setHook( $tag, callable
$callback ) {
4799 $tag = strtolower( $tag );
4800 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4801 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4803 $oldVal = $this->mTagHooks
[$tag] ??
null;
4804 $this->mTagHooks
[$tag] = $callback;
4805 if ( !in_array( $tag, $this->mStripList
) ) {
4806 $this->mStripList
[] = $tag;
4813 * As setHook(), but letting the contents be parsed.
4815 * Transparent tag hooks are like regular XML-style tag hooks, except they
4816 * operate late in the transformation sequence, on HTML instead of wikitext.
4818 * This is probably obsoleted by things dealing with parser frames?
4819 * The only extension currently using it is geoserver.
4822 * @todo better document or deprecate this
4824 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4825 * @param callable $callback The callback function (and object) to use for the tag
4826 * @throws MWException
4827 * @return callable|null The old value of the mTagHooks array associated with the hook
4829 public function setTransparentTagHook( $tag, callable
$callback ) {
4830 $tag = strtolower( $tag );
4831 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4832 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4834 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4835 $this->mTransparentTagHooks
[$tag] = $callback;
4841 * Remove all tag hooks
4843 public function clearTagHooks() {
4844 $this->mTagHooks
= [];
4845 $this->mFunctionTagHooks
= [];
4846 $this->mStripList
= $this->mDefaultStripList
;
4850 * Create a function, e.g. {{sum:1|2|3}}
4851 * The callback function should have the form:
4852 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4854 * Or with Parser::SFH_OBJECT_ARGS:
4855 * function myParserFunction( $parser, $frame, $args ) { ... }
4857 * The callback may either return the text result of the function, or an array with the text
4858 * in element 0, and a number of flags in the other elements. The names of the flags are
4859 * specified in the keys. Valid flags are:
4860 * found The text returned is valid, stop processing the template. This
4862 * nowiki Wiki markup in the return value should be escaped
4863 * isHTML The returned text is HTML, armour it against wikitext transformation
4865 * @param string $id The magic word ID
4866 * @param callable $callback The callback function (and object) to use
4867 * @param int $flags A combination of the following flags:
4868 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4870 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4871 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4872 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4873 * the arguments, and to control the way they are expanded.
4875 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4876 * arguments, for instance:
4877 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4879 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4880 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4881 * working if/when this is changed.
4883 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4886 * Please read the documentation in includes/parser/Preprocessor.php for more information
4887 * about the methods available in PPFrame and PPNode.
4889 * @throws MWException
4890 * @return string|callable The old callback function for this name, if any
4892 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4893 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4894 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4896 # Add to function cache
4897 $mw = $this->magicWordFactory
->get( $id );
4899 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4902 $synonyms = $mw->getSynonyms();
4903 $sensitive = intval( $mw->isCaseSensitive() );
4905 foreach ( $synonyms as $syn ) {
4907 if ( !$sensitive ) {
4908 $syn = $this->contLang
->lc( $syn );
4911 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4914 # Remove trailing colon
4915 if ( substr( $syn, -1, 1 ) === ':' ) {
4916 $syn = substr( $syn, 0, -1 );
4918 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4924 * Get all registered function hook identifiers
4928 public function getFunctionHooks() {
4929 return array_keys( $this->mFunctionHooks
);
4933 * Create a tag function, e.g. "<test>some stuff</test>".
4934 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4935 * Unlike parser functions, their content is not preprocessed.
4936 * @param string $tag
4937 * @param callable $callback
4939 * @throws MWException
4942 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4943 $tag = strtolower( $tag );
4944 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4945 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4947 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4948 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4950 if ( !in_array( $tag, $this->mStripList
) ) {
4951 $this->mStripList
[] = $tag;
4958 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4959 * Placeholders created in Linker::link()
4961 * @param string &$text
4962 * @param int $options
4964 public function replaceLinkHolders( &$text, $options = 0 ) {
4965 $this->mLinkHolders
->replace( $text );
4969 * Replace "<!--LINK-->" link placeholders with plain text of links
4970 * (not HTML-formatted).
4972 * @param string $text
4975 public function replaceLinkHoldersText( $text ) {
4976 return $this->mLinkHolders
->replaceText( $text );
4980 * Renders an image gallery from a text with one line per image.
4981 * text labels may be given by using |-style alternative text. E.g.
4982 * Image:one.jpg|The number "1"
4983 * Image:tree.jpg|A tree
4984 * given as text will return the HTML of a gallery with two images,
4985 * labeled 'The number "1"' and
4988 * @param string $text
4989 * @param array $params
4990 * @return string HTML
4992 public function renderImageGallery( $text, $params ) {
4994 if ( isset( $params['mode'] ) ) {
4995 $mode = $params['mode'];
4999 $ig = ImageGalleryBase
::factory( $mode );
5000 } catch ( Exception
$e ) {
5001 // If invalid type set, fallback to default.
5002 $ig = ImageGalleryBase
::factory( false );
5005 $ig->setContextTitle( $this->mTitle
);
5006 $ig->setShowBytes( false );
5007 $ig->setShowDimensions( false );
5008 $ig->setShowFilename( false );
5009 $ig->setParser( $this );
5010 $ig->setHideBadImages();
5011 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5013 if ( isset( $params['showfilename'] ) ) {
5014 $ig->setShowFilename( true );
5016 $ig->setShowFilename( false );
5018 if ( isset( $params['caption'] ) ) {
5019 $caption = $params['caption'];
5020 $caption = htmlspecialchars( $caption );
5021 $caption = $this->replaceInternalLinks( $caption );
5022 $ig->setCaptionHtml( $caption );
5024 if ( isset( $params['perrow'] ) ) {
5025 $ig->setPerRow( $params['perrow'] );
5027 if ( isset( $params['widths'] ) ) {
5028 $ig->setWidths( $params['widths'] );
5030 if ( isset( $params['heights'] ) ) {
5031 $ig->setHeights( $params['heights'] );
5033 $ig->setAdditionalOptions( $params );
5035 // Avoid PHP 7.1 warning from passing $this by reference
5037 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5039 $lines = StringUtils
::explode( "\n", $text );
5040 foreach ( $lines as $line ) {
5041 # match lines like these:
5042 # Image:someimage.jpg|This is some image
5044 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5046 if ( count( $matches ) == 0 ) {
5050 if ( strpos( $matches[0], '%' ) !== false ) {
5051 $matches[1] = rawurldecode( $matches[1] );
5053 $title = Title
::newFromText( $matches[1], NS_FILE
);
5054 if ( is_null( $title ) ) {
5055 # Bogus title. Ignore these so we don't bomb out later.
5059 # We need to get what handler the file uses, to figure out parameters.
5060 # Note, a hook can overide the file name, and chose an entirely different
5061 # file (which potentially could be of a different type and have different handler).
5064 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5065 [ $this, $title, &$options, &$descQuery ] );
5066 # Don't register it now, as TraditionalImageGallery does that later.
5067 $file = $this->fetchFileNoRegister( $title, $options );
5068 $handler = $file ?
$file->getHandler() : false;
5071 'img_alt' => 'gallery-internal-alt',
5072 'img_link' => 'gallery-internal-link',
5075 $paramMap = $paramMap +
$handler->getParamMap();
5076 // We don't want people to specify per-image widths.
5077 // Additionally the width parameter would need special casing anyhow.
5078 unset( $paramMap['img_width'] );
5081 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5086 $handlerOptions = [];
5087 if ( isset( $matches[3] ) ) {
5088 // look for an |alt= definition while trying not to break existing
5089 // captions with multiple pipes (|) in it, until a more sensible grammar
5090 // is defined for images in galleries
5092 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5093 // splitting on '|' is a bit odd, and different from makeImage.
5094 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5095 // Protect LanguageConverter markup
5096 $parameterMatches = StringUtils
::delimiterExplode(
5097 '-{', '}-', '|', $matches[3], true /* nested */
5100 foreach ( $parameterMatches as $parameterMatch ) {
5101 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5103 $paramName = $paramMap[$magicName];
5105 switch ( $paramName ) {
5106 case 'gallery-internal-alt':
5107 $alt = $this->stripAltText( $match, false );
5109 case 'gallery-internal-link':
5110 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5111 $chars = self
::EXT_LINK_URL_CLASS
;
5112 $addr = self
::EXT_LINK_ADDR
;
5113 $prots = $this->mUrlProtocols
;
5114 // check to see if link matches an absolute url, if not then it must be a wiki link.
5115 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5116 // Result of LanguageConverter::markNoConversion
5117 // invoked on an external link.
5118 $linkValue = substr( $linkValue, 4, -2 );
5120 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5122 $this->mOutput
->addExternalLink( $link );
5124 $localLinkTitle = Title
::newFromText( $linkValue );
5125 if ( $localLinkTitle !== null ) {
5126 $this->mOutput
->addLink( $localLinkTitle );
5127 $link = $localLinkTitle->getLinkURL();
5132 // Must be a handler specific parameter.
5133 if ( $handler->validateParam( $paramName, $match ) ) {
5134 $handlerOptions[$paramName] = $match;
5136 // Guess not, consider it as caption.
5137 wfDebug( "$parameterMatch failed parameter validation\n" );
5138 $label = $parameterMatch;
5144 $label = $parameterMatch;
5149 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5151 $html = $ig->toHTML();
5152 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5157 * @param MediaHandler $handler
5160 public function getImageParams( $handler ) {
5162 $handlerClass = get_class( $handler );
5166 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5167 # Initialise static lists
5168 static $internalParamNames = [
5169 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5170 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5171 'bottom', 'text-bottom' ],
5172 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5173 'upright', 'border', 'link', 'alt', 'class' ],
5175 static $internalParamMap;
5176 if ( !$internalParamMap ) {
5177 $internalParamMap = [];
5178 foreach ( $internalParamNames as $type => $names ) {
5179 foreach ( $names as $name ) {
5180 // For grep: img_left, img_right, img_center, img_none,
5181 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5182 // img_bottom, img_text_bottom,
5183 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5184 // img_border, img_link, img_alt, img_class
5185 $magicName = str_replace( '-', '_', "img_$name" );
5186 $internalParamMap[$magicName] = [ $type, $name ];
5191 # Add handler params
5192 $paramMap = $internalParamMap;
5194 $handlerParamMap = $handler->getParamMap();
5195 foreach ( $handlerParamMap as $magic => $paramName ) {
5196 $paramMap[$magic] = [ 'handler', $paramName ];
5199 $this->mImageParams
[$handlerClass] = $paramMap;
5200 $this->mImageParamsMagicArray
[$handlerClass] =
5201 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5203 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5207 * Parse image options text and use it to make an image
5209 * @param Title $title
5210 * @param string $options
5211 * @param LinkHolderArray|bool $holders
5212 * @return string HTML
5214 public function makeImage( $title, $options, $holders = false ) {
5215 # Check if the options text is of the form "options|alt text"
5217 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5218 # * left no resizing, just left align. label is used for alt= only
5219 # * right same, but right aligned
5220 # * none same, but not aligned
5221 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5222 # * center center the image
5223 # * frame Keep original image size, no magnify-button.
5224 # * framed Same as "frame"
5225 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5226 # * upright reduce width for upright images, rounded to full __0 px
5227 # * border draw a 1px border around the image
5228 # * alt Text for HTML alt attribute (defaults to empty)
5229 # * class Set a class for img node
5230 # * link Set the target of the image link. Can be external, interwiki, or local
5231 # vertical-align values (no % or length right now):
5241 # Protect LanguageConverter markup when splitting into parts
5242 $parts = StringUtils
::delimiterExplode(
5243 '-{', '}-', '|', $options, true /* allow nesting */
5246 # Give extensions a chance to select the file revision for us
5249 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5250 [ $this, $title, &$options, &$descQuery ] );
5251 # Fetch and register the file (file title may be different via hooks)
5252 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5255 $handler = $file ?
$file->getHandler() : false;
5257 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5260 $this->addTrackingCategory( 'broken-file-category' );
5263 # Process the input parameters
5265 $params = [ 'frame' => [], 'handler' => [],
5266 'horizAlign' => [], 'vertAlign' => [] ];
5267 $seenformat = false;
5268 foreach ( $parts as $part ) {
5269 $part = trim( $part );
5270 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5272 if ( isset( $paramMap[$magicName] ) ) {
5273 list( $type, $paramName ) = $paramMap[$magicName];
5275 # Special case; width and height come in one variable together
5276 if ( $type === 'handler' && $paramName === 'width' ) {
5277 $parsedWidthParam = self
::parseWidthParam( $value );
5278 if ( isset( $parsedWidthParam['width'] ) ) {
5279 $width = $parsedWidthParam['width'];
5280 if ( $handler->validateParam( 'width', $width ) ) {
5281 $params[$type]['width'] = $width;
5285 if ( isset( $parsedWidthParam['height'] ) ) {
5286 $height = $parsedWidthParam['height'];
5287 if ( $handler->validateParam( 'height', $height ) ) {
5288 $params[$type]['height'] = $height;
5292 # else no validation -- T15436
5294 if ( $type === 'handler' ) {
5295 # Validate handler parameter
5296 $validated = $handler->validateParam( $paramName, $value );
5298 # Validate internal parameters
5299 switch ( $paramName ) {
5303 # @todo FIXME: Possibly check validity here for
5304 # manualthumb? downstream behavior seems odd with
5305 # missing manual thumbs.
5307 $value = $this->stripAltText( $value, $holders );
5310 $chars = self
::EXT_LINK_URL_CLASS
;
5311 $addr = self
::EXT_LINK_ADDR
;
5312 $prots = $this->mUrlProtocols
;
5313 if ( $value === '' ) {
5314 $paramName = 'no-link';
5317 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5318 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5319 $paramName = 'link-url';
5320 $this->mOutput
->addExternalLink( $value );
5321 if ( $this->mOptions
->getExternalLinkTarget() ) {
5322 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5327 $linkTitle = Title
::newFromText( $value );
5329 $paramName = 'link-title';
5330 $value = $linkTitle;
5331 $this->mOutput
->addLink( $linkTitle );
5339 // use first appearing option, discard others.
5340 $validated = !$seenformat;
5344 # Most other things appear to be empty or numeric...
5345 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5350 $params[$type][$paramName] = $value;
5354 if ( !$validated ) {
5359 # Process alignment parameters
5360 if ( $params['horizAlign'] ) {
5361 $params['frame']['align'] = key( $params['horizAlign'] );
5363 if ( $params['vertAlign'] ) {
5364 $params['frame']['valign'] = key( $params['vertAlign'] );
5367 $params['frame']['caption'] = $caption;
5369 # Will the image be presented in a frame, with the caption below?
5370 $imageIsFramed = isset( $params['frame']['frame'] )
5371 ||
isset( $params['frame']['framed'] )
5372 ||
isset( $params['frame']['thumbnail'] )
5373 ||
isset( $params['frame']['manualthumb'] );
5375 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5376 # came to also set the caption, ordinary text after the image -- which
5377 # makes no sense, because that just repeats the text multiple times in
5378 # screen readers. It *also* came to set the title attribute.
5379 # Now that we have an alt attribute, we should not set the alt text to
5380 # equal the caption: that's worse than useless, it just repeats the
5381 # text. This is the framed/thumbnail case. If there's no caption, we
5382 # use the unnamed parameter for alt text as well, just for the time be-
5383 # ing, if the unnamed param is set and the alt param is not.
5384 # For the future, we need to figure out if we want to tweak this more,
5385 # e.g., introducing a title= parameter for the title; ignoring the un-
5386 # named parameter entirely for images without a caption; adding an ex-
5387 # plicit caption= parameter and preserving the old magic unnamed para-
5389 if ( $imageIsFramed ) { # Framed image
5390 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5391 # No caption or alt text, add the filename as the alt text so
5392 # that screen readers at least get some description of the image
5393 $params['frame']['alt'] = $title->getText();
5395 # Do not set $params['frame']['title'] because tooltips don't make sense
5397 } else { # Inline image
5398 if ( !isset( $params['frame']['alt'] ) ) {
5399 # No alt text, use the "caption" for the alt text
5400 if ( $caption !== '' ) {
5401 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5403 # No caption, fall back to using the filename for the
5405 $params['frame']['alt'] = $title->getText();
5408 # Use the "caption" for the tooltip text
5409 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5412 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5414 # Linker does the rest
5415 $time = $options['time'] ??
false;
5416 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5417 $time, $descQuery, $this->mOptions
->getThumbSize() );
5419 # Give the handler a chance to modify the parser object
5421 $handler->parserTransformHook( $this, $file );
5428 * @param string $caption
5429 * @param LinkHolderArray|bool $holders
5430 * @return mixed|string
5432 protected function stripAltText( $caption, $holders ) {
5433 # Strip bad stuff out of the title (tooltip). We can't just use
5434 # replaceLinkHoldersText() here, because if this function is called
5435 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5437 $tooltip = $holders->replaceText( $caption );
5439 $tooltip = $this->replaceLinkHoldersText( $caption );
5442 # make sure there are no placeholders in thumbnail attributes
5443 # that are later expanded to html- so expand them now and
5445 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5446 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5452 * Set a flag in the output object indicating that the content is dynamic and
5453 * shouldn't be cached.
5454 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5456 public function disableCache() {
5457 wfDebug( "Parser output marked as uncacheable.\n" );
5458 if ( !$this->mOutput
) {
5459 throw new MWException( __METHOD__
.
5460 " can only be called when actually parsing something" );
5462 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5466 * Callback from the Sanitizer for expanding items found in HTML attribute
5467 * values, so they can be safely tested and escaped.
5469 * @param string &$text
5470 * @param bool|PPFrame $frame
5473 public function attributeStripCallback( &$text, $frame = false ) {
5474 $text = $this->replaceVariables( $text, $frame );
5475 $text = $this->mStripState
->unstripBoth( $text );
5484 public function getTags() {
5486 array_keys( $this->mTransparentTagHooks
),
5487 array_keys( $this->mTagHooks
),
5488 array_keys( $this->mFunctionTagHooks
)
5496 public function getFunctionSynonyms() {
5497 $this->firstCallInit();
5498 return $this->mFunctionSynonyms
;
5505 public function getUrlProtocols() {
5506 return $this->mUrlProtocols
;
5510 * Replace transparent tags in $text with the values given by the callbacks.
5512 * Transparent tag hooks are like regular XML-style tag hooks, except they
5513 * operate late in the transformation sequence, on HTML instead of wikitext.
5515 * @param string $text
5519 public function replaceTransparentTags( $text ) {
5521 $elements = array_keys( $this->mTransparentTagHooks
);
5522 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5525 foreach ( $matches as $marker => $data ) {
5526 list( $element, $content, $params, $tag ) = $data;
5527 $tagName = strtolower( $element );
5528 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5529 $output = call_user_func_array(
5530 $this->mTransparentTagHooks
[$tagName],
5531 [ $content, $params, $this ]
5536 $replacements[$marker] = $output;
5538 return strtr( $text, $replacements );
5542 * Break wikitext input into sections, and either pull or replace
5543 * some particular section's text.
5545 * External callers should use the getSection and replaceSection methods.
5547 * @param string $text Page wikitext
5548 * @param string|int $sectionId A section identifier string of the form:
5549 * "<flag1> - <flag2> - ... - <section number>"
5551 * Currently the only recognised flag is "T", which means the target section number
5552 * was derived during a template inclusion parse, in other words this is a template
5553 * section edit link. If no flags are given, it was an ordinary section edit link.
5554 * This flag is required to avoid a section numbering mismatch when a section is
5555 * enclosed by "<includeonly>" (T8563).
5557 * The section number 0 pulls the text before the first heading; other numbers will
5558 * pull the given section along with its lower-level subsections. If the section is
5559 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5561 * Section 0 is always considered to exist, even if it only contains the empty
5562 * string. If $text is the empty string and section 0 is replaced, $newText is
5565 * @param string $mode One of "get" or "replace"
5566 * @param string $newText Replacement text for section data.
5567 * @return string For "get", the extracted section text.
5568 * for "replace", the whole page with the section replaced.
5570 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5571 global $wgTitle; # not generally used but removes an ugly failure mode
5573 $magicScopeVariable = $this->lock();
5574 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5576 $frame = $this->getPreprocessor()->newFrame();
5578 # Process section extraction flags
5580 $sectionParts = explode( '-', $sectionId );
5581 $sectionIndex = array_pop( $sectionParts );
5582 foreach ( $sectionParts as $part ) {
5583 if ( $part === 'T' ) {
5584 $flags |
= self
::PTD_FOR_INCLUSION
;
5588 # Check for empty input
5589 if ( strval( $text ) === '' ) {
5590 # Only sections 0 and T-0 exist in an empty document
5591 if ( $sectionIndex == 0 ) {
5592 if ( $mode === 'get' ) {
5598 if ( $mode === 'get' ) {
5606 # Preprocess the text
5607 $root = $this->preprocessToDom( $text, $flags );
5609 # <h> nodes indicate section breaks
5610 # They can only occur at the top level, so we can find them by iterating the root's children
5611 $node = $root->getFirstChild();
5613 # Find the target section
5614 if ( $sectionIndex == 0 ) {
5615 # Section zero doesn't nest, level=big
5616 $targetLevel = 1000;
5619 if ( $node->getName() === 'h' ) {
5620 $bits = $node->splitHeading();
5621 if ( $bits['i'] == $sectionIndex ) {
5622 $targetLevel = $bits['level'];
5626 if ( $mode === 'replace' ) {
5627 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5629 $node = $node->getNextSibling();
5635 if ( $mode === 'get' ) {
5642 # Find the end of the section, including nested sections
5644 if ( $node->getName() === 'h' ) {
5645 $bits = $node->splitHeading();
5646 $curLevel = $bits['level'];
5647 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5651 if ( $mode === 'get' ) {
5652 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5654 $node = $node->getNextSibling();
5657 # Write out the remainder (in replace mode only)
5658 if ( $mode === 'replace' ) {
5659 # Output the replacement text
5660 # Add two newlines on -- trailing whitespace in $newText is conventionally
5661 # stripped by the editor, so we need both newlines to restore the paragraph gap
5662 # Only add trailing whitespace if there is newText
5663 if ( $newText != "" ) {
5664 $outText .= $newText . "\n\n";
5668 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5669 $node = $node->getNextSibling();
5673 if ( is_string( $outText ) ) {
5674 # Re-insert stripped tags
5675 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5682 * This function returns the text of a section, specified by a number ($section).
5683 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5684 * the first section before any such heading (section 0).
5686 * If a section contains subsections, these are also returned.
5688 * @param string $text Text to look in
5689 * @param string|int $sectionId Section identifier as a number or string
5690 * (e.g. 0, 1 or 'T-1').
5691 * @param string $defaultText Default to return if section is not found
5693 * @return string Text of the requested section
5695 public function getSection( $text, $sectionId, $defaultText = '' ) {
5696 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5700 * This function returns $oldtext after the content of the section
5701 * specified by $section has been replaced with $text. If the target
5702 * section does not exist, $oldtext is returned unchanged.
5704 * @param string $oldText Former text of the article
5705 * @param string|int $sectionId Section identifier as a number or string
5706 * (e.g. 0, 1 or 'T-1').
5707 * @param string $newText Replacing text
5709 * @return string Modified text
5711 public function replaceSection( $oldText, $sectionId, $newText ) {
5712 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5716 * Get the ID of the revision we are parsing
5720 public function getRevisionId() {
5721 return $this->mRevisionId
;
5725 * Get the revision object for $this->mRevisionId
5727 * @return Revision|null Either a Revision object or null
5728 * @since 1.23 (public since 1.23)
5730 public function getRevisionObject() {
5731 if ( !is_null( $this->mRevisionObject
) ) {
5732 return $this->mRevisionObject
;
5734 if ( is_null( $this->mRevisionId
) ) {
5738 $rev = call_user_func(
5739 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5742 # If the parse is for a new revision, then the callback should have
5743 # already been set to force the object and should match mRevisionId.
5744 # If not, try to fetch by mRevisionId for sanity.
5745 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5746 $rev = Revision
::newFromId( $this->mRevisionId
);
5749 $this->mRevisionObject
= $rev;
5751 return $this->mRevisionObject
;
5755 * Get the timestamp associated with the current revision, adjusted for
5756 * the default server-local timestamp
5759 public function getRevisionTimestamp() {
5760 if ( is_null( $this->mRevisionTimestamp
) ) {
5761 $revObject = $this->getRevisionObject();
5762 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5764 # The cryptic '' timezone parameter tells to use the site-default
5765 # timezone offset instead of the user settings.
5766 # Since this value will be saved into the parser cache, served
5767 # to other users, and potentially even used inside links and such,
5768 # it needs to be consistent for all visitors.
5769 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
5771 return $this->mRevisionTimestamp
;
5775 * Get the name of the user that edited the last revision
5777 * @return string User name
5779 public function getRevisionUser() {
5780 if ( is_null( $this->mRevisionUser
) ) {
5781 $revObject = $this->getRevisionObject();
5783 # if this template is subst: the revision id will be blank,
5784 # so just use the current user's name
5786 $this->mRevisionUser
= $revObject->getUserText();
5787 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5788 $this->mRevisionUser
= $this->getUser()->getName();
5791 return $this->mRevisionUser
;
5795 * Get the size of the revision
5797 * @return int|null Revision size
5799 public function getRevisionSize() {
5800 if ( is_null( $this->mRevisionSize
) ) {
5801 $revObject = $this->getRevisionObject();
5803 # if this variable is subst: the revision id will be blank,
5804 # so just use the parser input size, because the own substituation
5805 # will change the size.
5807 $this->mRevisionSize
= $revObject->getSize();
5809 $this->mRevisionSize
= $this->mInputSize
;
5812 return $this->mRevisionSize
;
5816 * Mutator for $mDefaultSort
5818 * @param string $sort New value
5820 public function setDefaultSort( $sort ) {
5821 $this->mDefaultSort
= $sort;
5822 $this->mOutput
->setProperty( 'defaultsort', $sort );
5826 * Accessor for $mDefaultSort
5827 * Will use the empty string if none is set.
5829 * This value is treated as a prefix, so the
5830 * empty string is equivalent to sorting by
5835 public function getDefaultSort() {
5836 if ( $this->mDefaultSort
!== false ) {
5837 return $this->mDefaultSort
;
5844 * Accessor for $mDefaultSort
5845 * Unlike getDefaultSort(), will return false if none is set
5847 * @return string|bool
5849 public function getCustomDefaultSort() {
5850 return $this->mDefaultSort
;
5853 private static function getSectionNameFromStrippedText( $text ) {
5854 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5855 $text = Sanitizer
::decodeCharReferences( $text );
5856 $text = self
::normalizeSectionName( $text );
5860 private static function makeAnchor( $sectionName ) {
5861 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5864 private static function makeLegacyAnchor( $sectionName ) {
5865 global $wgFragmentMode;
5866 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5867 // ForAttribute() and ForLink() are the same for legacy encoding
5868 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5870 $id = Sanitizer
::escapeIdForLink( $sectionName );
5877 * Try to guess the section anchor name based on a wikitext fragment
5878 * presumably extracted from a heading, for example "Header" from
5881 * @param string $text
5882 * @return string Anchor (starting with '#')
5884 public function guessSectionNameFromWikiText( $text ) {
5885 # Strip out wikitext links(they break the anchor)
5886 $text = $this->stripSectionName( $text );
5887 $sectionName = self
::getSectionNameFromStrippedText( $text );
5888 return self
::makeAnchor( $sectionName );
5892 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5893 * instead, if possible. For use in redirects, since various versions
5894 * of Microsoft browsers interpret Location: headers as something other
5895 * than UTF-8, resulting in breakage.
5897 * @param string $text The section name
5898 * @return string Anchor (starting with '#')
5900 public function guessLegacySectionNameFromWikiText( $text ) {
5901 # Strip out wikitext links(they break the anchor)
5902 $text = $this->stripSectionName( $text );
5903 $sectionName = self
::getSectionNameFromStrippedText( $text );
5904 return self
::makeLegacyAnchor( $sectionName );
5908 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5909 * @param string $text Section name (plain text)
5910 * @return string Anchor (starting with '#')
5912 public static function guessSectionNameFromStrippedText( $text ) {
5913 $sectionName = self
::getSectionNameFromStrippedText( $text );
5914 return self
::makeAnchor( $sectionName );
5918 * Apply the same normalization as code making links to this section would
5920 * @param string $text
5923 private static function normalizeSectionName( $text ) {
5924 # T90902: ensure the same normalization is applied for IDs as to links
5925 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5928 $parts = $titleParser->splitTitleString( "#$text" );
5929 } catch ( MalformedTitleException
$ex ) {
5932 return $parts['fragment'];
5936 * Strips a text string of wikitext for use in a section anchor
5938 * Accepts a text string and then removes all wikitext from the
5939 * string and leaves only the resultant text (i.e. the result of
5940 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5941 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5942 * to create valid section anchors by mimicing the output of the
5943 * parser when headings are parsed.
5945 * @param string $text Text string to be stripped of wikitext
5946 * for use in a Section anchor
5947 * @return string Filtered text string
5949 public function stripSectionName( $text ) {
5950 # Strip internal link markup
5951 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5952 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5954 # Strip external link markup
5955 # @todo FIXME: Not tolerant to blank link text
5956 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5957 # on how many empty links there are on the page - need to figure that out.
5958 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5960 # Parse wikitext quotes (italics & bold)
5961 $text = $this->doQuotes( $text );
5964 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5969 * strip/replaceVariables/unstrip for preprocessor regression testing
5971 * @param string $text
5972 * @param Title $title
5973 * @param ParserOptions $options
5974 * @param int $outputType
5978 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5979 $outputType = self
::OT_HTML
5981 $magicScopeVariable = $this->lock();
5982 $this->startParse( $title, $options, $outputType, true );
5984 $text = $this->replaceVariables( $text );
5985 $text = $this->mStripState
->unstripBoth( $text );
5986 $text = Sanitizer
::removeHTMLtags( $text );
5991 * @param string $text
5992 * @param Title $title
5993 * @param ParserOptions $options
5996 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5997 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6001 * @param string $text
6002 * @param Title $title
6003 * @param ParserOptions $options
6006 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6007 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6011 * Call a callback function on all regions of the given text that are not
6012 * inside strip markers, and replace those regions with the return value
6013 * of the callback. For example, with input:
6017 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6018 * two strings will be replaced with the value returned by the callback in
6022 * @param callable $callback
6026 public function markerSkipCallback( $s, $callback ) {
6029 while ( $i < strlen( $s ) ) {
6030 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6031 if ( $markerStart === false ) {
6032 $out .= call_user_func( $callback, substr( $s, $i ) );
6035 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6036 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6037 if ( $markerEnd === false ) {
6038 $out .= substr( $s, $markerStart );
6041 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6042 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6051 * Remove any strip markers found in the given text.
6053 * @param string $text
6056 public function killMarkers( $text ) {
6057 return $this->mStripState
->killMarkers( $text );
6061 * Save the parser state required to convert the given half-parsed text to
6062 * HTML. "Half-parsed" in this context means the output of
6063 * recursiveTagParse() or internalParse(). This output has strip markers
6064 * from replaceVariables (extensionSubstitution() etc.), and link
6065 * placeholders from replaceLinkHolders().
6067 * Returns an array which can be serialized and stored persistently. This
6068 * array can later be loaded into another parser instance with
6069 * unserializeHalfParsedText(). The text can then be safely incorporated into
6070 * the return value of a parser hook.
6072 * @deprecated since 1.31
6073 * @param string $text
6077 public function serializeHalfParsedText( $text ) {
6078 wfDeprecated( __METHOD__
, '1.31' );
6081 'version' => self
::HALF_PARSED_VERSION
,
6082 'stripState' => $this->mStripState
->getSubState( $text ),
6083 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6089 * Load the parser state given in the $data array, which is assumed to
6090 * have been generated by serializeHalfParsedText(). The text contents is
6091 * extracted from the array, and its markers are transformed into markers
6092 * appropriate for the current Parser instance. This transformed text is
6093 * returned, and can be safely included in the return value of a parser
6096 * If the $data array has been stored persistently, the caller should first
6097 * check whether it is still valid, by calling isValidHalfParsedText().
6099 * @deprecated since 1.31
6100 * @param array $data Serialized data
6101 * @throws MWException
6104 public function unserializeHalfParsedText( $data ) {
6105 wfDeprecated( __METHOD__
, '1.31' );
6106 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6107 throw new MWException( __METHOD__
. ': invalid version' );
6110 # First, extract the strip state.
6111 $texts = [ $data['text'] ];
6112 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6114 # Now renumber links
6115 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6117 # Should be good to go.
6122 * Returns true if the given array, presumed to be generated by
6123 * serializeHalfParsedText(), is compatible with the current version of the
6126 * @deprecated since 1.31
6127 * @param array $data
6131 public function isValidHalfParsedText( $data ) {
6132 wfDeprecated( __METHOD__
, '1.31' );
6133 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6137 * Parsed a width param of imagelink like 300px or 200x300px
6139 * @param string $value
6140 * @param bool $parseHeight
6145 public static function parseWidthParam( $value, $parseHeight = true ) {
6146 $parsedWidthParam = [];
6147 if ( $value === '' ) {
6148 return $parsedWidthParam;
6151 # (T15500) In both cases (width/height and width only),
6152 # permit trailing "px" for backward compatibility.
6153 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6154 $width = intval( $m[1] );
6155 $height = intval( $m[2] );
6156 $parsedWidthParam['width'] = $width;
6157 $parsedWidthParam['height'] = $height;
6158 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6159 $width = intval( $value );
6160 $parsedWidthParam['width'] = $width;
6162 return $parsedWidthParam;
6166 * Lock the current instance of the parser.
6168 * This is meant to stop someone from calling the parser
6169 * recursively and messing up all the strip state.
6171 * @throws MWException If parser is in a parse
6172 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6174 protected function lock() {
6175 if ( $this->mInParse
) {
6176 throw new MWException( "Parser state cleared while parsing. "
6177 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6180 // Save the backtrace when locking, so that if some code tries locking again,
6181 // we can print the lock owner's backtrace for easier debugging
6183 $this->mInParse
= $e->getTraceAsString();
6185 $recursiveCheck = new ScopedCallback( function () {
6186 $this->mInParse
= false;
6189 return $recursiveCheck;
6193 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6195 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6196 * or if there is more than one <p/> tag in the input HTML.
6198 * @param string $html
6202 public static function stripOuterParagraph( $html ) {
6204 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6205 if ( strpos( $m[1], '</p>' ) === false ) {
6214 * Return this parser if it is not doing anything, otherwise
6215 * get a fresh parser. You can use this method by doing
6216 * $myParser = $wgParser->getFreshParser(), or more simply
6217 * $wgParser->getFreshParser()->parse( ... );
6218 * if you're unsure if $wgParser is safe to use.
6221 * @return Parser A parser object that is not parsing anything
6223 public function getFreshParser() {
6224 if ( $this->mInParse
) {
6225 return $this->factory
->create();
6232 * Set's up the PHP implementation of OOUI for use in this request
6233 * and instructs OutputPage to enable OOUI for itself.
6237 public function enableOOUI() {
6238 OutputPage
::setupOOUI();
6239 $this->mOutput
->setEnableOOUI( true );