3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @defgroup Parser Parser
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
37 * There are seven main entry points into the Parser class:
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
57 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
60 * $wgNamespacesWithSubpages
62 * @par Settings only within ParserOptions:
63 * $wgAllowExternalImages
64 * $wgAllowSpecialInclusion
72 * Update this version number when the ParserOutput format
73 * changes in an incompatible way, so the parser cache
74 * can automatically discard old data.
76 const VERSION
= '1.6.4';
79 * Update this version number when the output of serialiseHalfParsedText()
80 * changes in an incompatible way
82 const HALF_PARSED_VERSION
= 2;
84 # Flags for Parser::setFunctionHook
85 const SFH_NO_HASH
= 1;
86 const SFH_OBJECT_ARGS
= 2;
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
92 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
93 # uses to replace invalid HTML characters.
94 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
95 # Simplified expression to match an IPv4 or IPv6 address, or
96 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
97 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
98 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
99 // phpcs:ignore Generic.Files.LineLength
100 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
101 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
103 # Regular expression for a non-newline space
104 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
118 * @var string Prefix and suffix for temporary replacement strings
119 * for the multipass parser.
121 * \x7f should never appear in input as it's disallowed in XML.
122 * Using it at the front also gives us a little extra robustness
123 * since it shouldn't match when butted up against identifier-like
126 * Must not consist of all title characters, or else it will change
127 * the behavior of <nowiki> in a link.
129 * Must have a character that needs escaping in attributes, otherwise
130 * someone could put a strip marker in an attribute, to get around
131 * escaping quote marks, and break out of the attribute. Thus we add
134 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
135 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
137 # Markers used for wrapping the table of contents
138 const TOC_START
= '<mw:toc>';
139 const TOC_END
= '</mw:toc>';
141 /** @var int Assume that no output will later be saved this many seconds after parsing */
145 public $mTagHooks = [];
146 public $mTransparentTagHooks = [];
147 public $mFunctionHooks = [];
148 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
149 public $mFunctionTagHooks = [];
150 public $mStripList = [];
151 public $mDefaultStripList = [];
152 public $mVarCache = [];
153 public $mImageParams = [];
154 public $mImageParamsMagicArray = [];
155 public $mMarkerIndex = 0;
156 public $mFirstCall = true;
158 # Initialised by initialiseVariables()
161 * @var MagicWordArray
166 * @var MagicWordArray
169 # Initialised in constructor
170 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
172 # Initialized in getPreprocessor()
173 /** @var Preprocessor */
174 public $mPreprocessor;
176 # Cleared with clearState():
188 public $mIncludeCount;
190 * @var LinkHolderArray
192 public $mLinkHolders;
195 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
196 public $mDefaultSort;
197 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
198 public $mExpensiveFunctionCount; # number of expensive parser function calls
199 public $mShowToc, $mForceTocPosition;
204 public $mUser; # User object; only used when doing pre-save transform
207 # These are variables reset at least once per parse regardless of $clearState
217 public $mTitle; # Title context, used for self-link rendering and similar things
218 public $mOutputType; # Output type, one of the OT_xxx constants
219 public $ot; # Shortcut alias, see setOutputType()
220 public $mRevisionObject; # The revision object of the specified revision ID
221 public $mRevisionId; # ID to display in {{REVISIONID}} tags
222 public $mRevisionTimestamp; # The timestamp of the specified revision ID
223 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
224 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
225 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
226 public $mInputSize = false; # For {{PAGESIZE}} on current page.
229 * @var string Deprecated accessor for the strip marker prefix.
230 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
232 public $mUniqPrefix = self
::MARKER_PREFIX
;
235 * @var array Array with the language name of each language link (i.e. the
236 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
237 * duplicate language links to the ParserOutput.
239 public $mLangLinkLanguages;
242 * @var MapCacheLRU|null
245 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
247 public $currentRevisionCache;
250 * @var bool|string Recursive call protection.
251 * This variable should be treated as if it were private.
253 public $mInParse = false;
255 /** @var SectionProfiler */
256 protected $mProfiler;
261 protected $mLinkRenderer;
263 /** @var MagicWordFactory */
264 private $magicWordFactory;
268 * @param MagicWordFactory|null $magicWordFactory
270 public function __construct( $conf = [], MagicWordFactory
$magicWordFactory = null ) {
271 $this->mConf
= $conf;
272 $this->mUrlProtocols
= wfUrlProtocols();
273 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
274 self
::EXT_LINK_ADDR
.
275 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
276 if ( isset( $conf['preprocessorClass'] ) ) {
277 $this->mPreprocessorClass
= $conf['preprocessorClass'];
278 } elseif ( defined( 'HPHP_VERSION' ) ) {
279 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
280 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
281 } elseif ( extension_loaded( 'domxml' ) ) {
282 # PECL extension that conflicts with the core DOM extension (T15770)
283 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
284 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
285 } elseif ( extension_loaded( 'dom' ) ) {
286 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
288 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
290 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
292 $this->magicWordFactory
= $magicWordFactory;
293 if ( !$magicWordFactory ) {
294 $this->magicWordFactory
= MediaWikiServices
::getInstance()->getMagicWordFactory();
299 * Reduce memory usage to reduce the impact of circular references
301 public function __destruct() {
302 if ( isset( $this->mLinkHolders
) ) {
303 unset( $this->mLinkHolders
);
305 foreach ( $this as $name => $value ) {
306 unset( $this->$name );
311 * Allow extensions to clean up when the parser is cloned
313 public function __clone() {
314 $this->mInParse
= false;
316 // T58226: When you create a reference "to" an object field, that
317 // makes the object field itself be a reference too (until the other
318 // reference goes out of scope). When cloning, any field that's a
319 // reference is copied as a reference in the new object. Both of these
320 // are defined PHP5 behaviors, as inconvenient as it is for us when old
321 // hooks from PHP4 days are passing fields by reference.
322 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
323 // Make a non-reference copy of the field, then rebind the field to
324 // reference the new copy.
330 Hooks
::run( 'ParserCloned', [ $this ] );
334 * Do various kinds of initialisation on the first call of the parser
336 public function firstCallInit() {
337 if ( !$this->mFirstCall
) {
340 $this->mFirstCall
= false;
342 CoreParserFunctions
::register( $this );
343 CoreTagHooks
::register( $this );
344 $this->initialiseVariables();
346 // Avoid PHP 7.1 warning from passing $this by reference
348 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
356 public function clearState() {
357 if ( $this->mFirstCall
) {
358 $this->firstCallInit();
360 $this->mOutput
= new ParserOutput
;
361 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
362 $this->mAutonumber
= 0;
363 $this->mIncludeCount
= [];
364 $this->mLinkHolders
= new LinkHolderArray( $this );
366 $this->mRevisionObject
= $this->mRevisionTimestamp
=
367 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
368 $this->mVarCache
= [];
370 $this->mLangLinkLanguages
= [];
371 $this->currentRevisionCache
= null;
373 $this->mStripState
= new StripState( $this );
375 # Clear these on every parse, T6549
376 $this->mTplRedirCache
= $this->mTplDomCache
= [];
378 $this->mShowToc
= true;
379 $this->mForceTocPosition
= false;
380 $this->mIncludeSizes
= [
384 $this->mPPNodeCount
= 0;
385 $this->mGeneratedPPNodeCount
= 0;
386 $this->mHighestExpansionDepth
= 0;
387 $this->mDefaultSort
= false;
388 $this->mHeadings
= [];
389 $this->mDoubleUnderscores
= [];
390 $this->mExpensiveFunctionCount
= 0;
393 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
394 $this->mPreprocessor
= null;
397 $this->mProfiler
= new SectionProfiler();
399 // Avoid PHP 7.1 warning from passing $this by reference
401 Hooks
::run( 'ParserClearState', [ &$parser ] );
405 * Convert wikitext to HTML
406 * Do not call this function recursively.
408 * @param string $text Text we want to parse
409 * @param Title $title
410 * @param ParserOptions $options
411 * @param bool $linestart
412 * @param bool $clearState
413 * @param int|null $revid Number to pass in {{REVISIONID}}
414 * @return ParserOutput A ParserOutput
416 public function parse(
417 $text, Title
$title, ParserOptions
$options,
418 $linestart = true, $clearState = true, $revid = null
421 // We use U+007F DELETE to construct strip markers, so we have to make
422 // sure that this character does not occur in the input text.
423 $text = strtr( $text, "\x7f", "?" );
424 $magicScopeVariable = $this->lock();
426 // Strip U+0000 NULL (T159174)
427 $text = str_replace( "\000", '', $text );
429 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
431 $this->currentRevisionCache
= null;
432 $this->mInputSize
= strlen( $text );
433 if ( $this->mOptions
->getEnableLimitReport() ) {
434 $this->mOutput
->resetParseStartTime();
437 $oldRevisionId = $this->mRevisionId
;
438 $oldRevisionObject = $this->mRevisionObject
;
439 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
440 $oldRevisionUser = $this->mRevisionUser
;
441 $oldRevisionSize = $this->mRevisionSize
;
442 if ( $revid !== null ) {
443 $this->mRevisionId
= $revid;
444 $this->mRevisionObject
= null;
445 $this->mRevisionTimestamp
= null;
446 $this->mRevisionUser
= null;
447 $this->mRevisionSize
= null;
450 // Avoid PHP 7.1 warning from passing $this by reference
452 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
454 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
455 $text = $this->internalParse( $text );
456 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
458 $text = $this->internalParseHalfParsed( $text, true, $linestart );
461 * A converted title will be provided in the output object if title and
462 * content conversion are enabled, the article text does not contain
463 * a conversion-suppressing double-underscore tag, and no
464 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
465 * automatic link conversion.
467 if ( !( $options->getDisableTitleConversion()
468 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
469 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
470 ||
$this->mOutput
->getDisplayTitle() !== false )
472 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
473 if ( $convruletitle ) {
474 $this->mOutput
->setTitleText( $convruletitle );
476 $titleText = $this->getTargetLanguage()->convertTitle( $title );
477 $this->mOutput
->setTitleText( $titleText );
481 # Compute runtime adaptive expiry if set
482 $this->mOutput
->finalizeAdaptiveCacheExpiry();
484 # Warn if too many heavyweight parser functions were used
485 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
486 $this->limitationWarn( 'expensive-parserfunction',
487 $this->mExpensiveFunctionCount
,
488 $this->mOptions
->getExpensiveParserFunctionLimit()
492 # Information on limits, for the benefit of users who try to skirt them
493 if ( $this->mOptions
->getEnableLimitReport() ) {
494 $text .= $this->makeLimitReport();
497 # Wrap non-interface parser output in a <div> so it can be targeted
499 $class = $this->mOptions
->getWrapOutputClass();
500 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
501 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
504 $this->mOutput
->setText( $text );
506 $this->mRevisionId
= $oldRevisionId;
507 $this->mRevisionObject
= $oldRevisionObject;
508 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
509 $this->mRevisionUser
= $oldRevisionUser;
510 $this->mRevisionSize
= $oldRevisionSize;
511 $this->mInputSize
= false;
512 $this->currentRevisionCache
= null;
514 return $this->mOutput
;
518 * Set the limit report data in the current ParserOutput, and return the
519 * limit report HTML comment.
523 protected function makeLimitReport() {
524 global $wgShowHostnames;
526 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
528 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
529 if ( $cpuTime !== null ) {
530 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
531 sprintf( "%.3f", $cpuTime )
535 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
536 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
537 sprintf( "%.3f", $wallTime )
540 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
541 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
543 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
544 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
546 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
547 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
549 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
550 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
552 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
553 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
555 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
556 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
559 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
560 $this->mOutput
->setLimitReportData( $key, $value );
563 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
565 $limitReport = "NewPP limit report\n";
566 if ( $wgShowHostnames ) {
567 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
569 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
570 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
571 $limitReport .= 'Dynamic content: ' .
572 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
575 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
576 if ( Hooks
::run( 'ParserLimitReportFormat',
577 [ $key, &$value, &$limitReport, false, false ]
579 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
580 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
581 ->inLanguage( 'en' )->useDatabase( false );
582 if ( !$valueMsg->exists() ) {
583 $valueMsg = new RawMessage( '$1' );
585 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
586 $valueMsg->params( $value );
587 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
591 // Since we're not really outputting HTML, decode the entities and
592 // then re-encode the things that need hiding inside HTML comments.
593 $limitReport = htmlspecialchars_decode( $limitReport );
594 // Run deprecated hook
595 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
597 // Sanitize for comment. Note '‐' in the replacement is U+2010,
598 // which looks much like the problematic '-'.
599 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
600 $text = "\n<!-- \n$limitReport-->\n";
602 // Add on template profiling data in human/machine readable way
603 $dataByFunc = $this->mProfiler
->getFunctionStats();
604 uasort( $dataByFunc, function ( $a, $b ) {
605 return $b['real'] <=> $a['real']; // descending order
608 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
609 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
610 $item['%real'], $item['real'], $item['calls'],
611 htmlspecialchars( $item['name'] ) );
613 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
614 $text .= implode( "\n", $profileReport ) . "\n-->\n";
616 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
618 // Add other cache related metadata
619 if ( $wgShowHostnames ) {
620 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
622 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
623 $this->mOutput
->getCacheTime() );
624 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
625 $this->mOutput
->getCacheExpiry() );
626 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
627 $this->mOutput
->hasDynamicContent() );
629 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
630 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
631 $this->mTitle
->getPrefixedDBkey() );
637 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
638 * can be called from an extension tag hook.
640 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
641 * instead, which means that lists and links have not been fully parsed yet,
642 * and strip markers are still present.
644 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
646 * Use this function if you're a parser tag hook and you want to parse
647 * wikitext before or after applying additional transformations, and you
648 * intend to *return the result as hook output*, which will cause it to go
649 * through the rest of parsing process automatically.
651 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
652 * $text are not expanded
654 * @param string $text Text extension wants to have parsed
655 * @param bool|PPFrame $frame The frame to use for expanding any template variables
656 * @return string UNSAFE half-parsed HTML
658 public function recursiveTagParse( $text, $frame = false ) {
659 // Avoid PHP 7.1 warning from passing $this by reference
661 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
662 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
663 $text = $this->internalParse( $text, false, $frame );
668 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
669 * point can be called from an extension tag hook.
671 * The output of this function is fully-parsed HTML that is safe for output.
672 * If you're a parser tag hook, you might want to use recursiveTagParse()
675 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
676 * $text are not expanded
680 * @param string $text Text extension wants to have parsed
681 * @param bool|PPFrame $frame The frame to use for expanding any template variables
682 * @return string Fully parsed HTML
684 public function recursiveTagParseFully( $text, $frame = false ) {
685 $text = $this->recursiveTagParse( $text, $frame );
686 $text = $this->internalParseHalfParsed( $text, false );
691 * Expand templates and variables in the text, producing valid, static wikitext.
692 * Also removes comments.
693 * Do not call this function recursively.
694 * @param string $text
695 * @param Title|null $title
696 * @param ParserOptions $options
697 * @param int|null $revid
698 * @param bool|PPFrame $frame
699 * @return mixed|string
701 public function preprocess( $text, Title
$title = null,
702 ParserOptions
$options, $revid = null, $frame = false
704 $magicScopeVariable = $this->lock();
705 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
706 if ( $revid !== null ) {
707 $this->mRevisionId
= $revid;
709 // Avoid PHP 7.1 warning from passing $this by reference
711 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
712 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
713 $text = $this->replaceVariables( $text, $frame );
714 $text = $this->mStripState
->unstripBoth( $text );
719 * Recursive parser entry point that can be called from an extension tag
722 * @param string $text Text to be expanded
723 * @param bool|PPFrame $frame The frame to use for expanding any template variables
727 public function recursivePreprocess( $text, $frame = false ) {
728 $text = $this->replaceVariables( $text, $frame );
729 $text = $this->mStripState
->unstripBoth( $text );
734 * Process the wikitext for the "?preload=" feature. (T7210)
736 * "<noinclude>", "<includeonly>" etc. are parsed as for template
737 * transclusion, comments, templates, arguments, tags hooks and parser
738 * functions are untouched.
740 * @param string $text
741 * @param Title $title
742 * @param ParserOptions $options
743 * @param array $params
746 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
747 $msg = new RawMessage( $text );
748 $text = $msg->params( $params )->plain();
750 # Parser (re)initialisation
751 $magicScopeVariable = $this->lock();
752 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
754 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
755 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
756 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
757 $text = $this->mStripState
->unstripBoth( $text );
762 * Set the current user.
763 * Should only be used when doing pre-save transform.
765 * @param User|null $user User object or null (to reset)
767 public function setUser( $user ) {
768 $this->mUser
= $user;
772 * Set the context title
776 public function setTitle( $t ) {
778 $t = Title
::newFromText( 'NO TITLE' );
781 if ( $t->hasFragment() ) {
782 # Strip the fragment to avoid various odd effects
783 $this->mTitle
= $t->createFragmentTarget( '' );
790 * Accessor for the Title object
794 public function getTitle() {
795 return $this->mTitle
;
799 * Accessor/mutator for the Title object
801 * @param Title|null $x Title object or null to just get the current one
804 public function Title( $x = null ) {
805 return wfSetVar( $this->mTitle
, $x );
809 * Set the output type
811 * @param int $ot New value
813 public function setOutputType( $ot ) {
814 $this->mOutputType
= $ot;
817 'html' => $ot == self
::OT_HTML
,
818 'wiki' => $ot == self
::OT_WIKI
,
819 'pre' => $ot == self
::OT_PREPROCESS
,
820 'plain' => $ot == self
::OT_PLAIN
,
825 * Accessor/mutator for the output type
827 * @param int|null $x New value or null to just get the current one
830 public function OutputType( $x = null ) {
831 return wfSetVar( $this->mOutputType
, $x );
835 * Get the ParserOutput object
837 * @return ParserOutput
839 public function getOutput() {
840 return $this->mOutput
;
844 * Get the ParserOptions object
846 * @return ParserOptions
848 public function getOptions() {
849 return $this->mOptions
;
853 * Accessor/mutator for the ParserOptions object
855 * @param ParserOptions|null $x New value or null to just get the current one
856 * @return ParserOptions Current ParserOptions object
858 public function Options( $x = null ) {
859 return wfSetVar( $this->mOptions
, $x );
865 public function nextLinkID() {
866 return $this->mLinkID++
;
872 public function setLinkID( $id ) {
873 $this->mLinkID
= $id;
877 * Get a language object for use in parser functions such as {{FORMATNUM:}}
880 public function getFunctionLang() {
881 return $this->getTargetLanguage();
885 * Get the target language for the content being parsed. This is usually the
886 * language that the content is in.
890 * @throws MWException
893 public function getTargetLanguage() {
894 $target = $this->mOptions
->getTargetLanguage();
896 if ( $target !== null ) {
898 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
899 return $this->mOptions
->getUserLangObj();
900 } elseif ( is_null( $this->mTitle
) ) {
901 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
904 return $this->mTitle
->getPageLanguage();
908 * Get the language object for language conversion
909 * @deprecated since 1.32, just use getTargetLanguage()
910 * @return Language|null
912 public function getConverterLanguage() {
913 return $this->getTargetLanguage();
917 * Get a User object either from $this->mUser, if set, or from the
918 * ParserOptions object otherwise
922 public function getUser() {
923 if ( !is_null( $this->mUser
) ) {
926 return $this->mOptions
->getUser();
930 * Get a preprocessor object
932 * @return Preprocessor
934 public function getPreprocessor() {
935 if ( !isset( $this->mPreprocessor
) ) {
936 $class = $this->mPreprocessorClass
;
937 $this->mPreprocessor
= new $class( $this );
939 return $this->mPreprocessor
;
943 * Get a LinkRenderer instance to make links with
946 * @return LinkRenderer
948 public function getLinkRenderer() {
949 if ( !$this->mLinkRenderer
) {
950 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
951 ->getLinkRendererFactory()->create();
952 $this->mLinkRenderer
->setStubThreshold(
953 $this->getOptions()->getStubThreshold()
957 return $this->mLinkRenderer
;
961 * Get the MagicWordFactory that this Parser is using
964 * @return MagicWordFactory
966 public function getMagicWordFactory() {
967 return $this->magicWordFactory
;
971 * Replaces all occurrences of HTML-style comments and the given tags
972 * in the text with a random marker and returns the next text. The output
973 * parameter $matches will be an associative array filled with data in
980 * [ 'param' => 'x' ],
981 * '<element param="x">tag content</element>' ]
984 * @param array $elements List of element names. Comments are always extracted.
985 * @param string $text Source text string.
986 * @param array &$matches Out parameter, Array: extracted tags
987 * @return string Stripped text
989 public static function extractTagsAndParams( $elements, $text, &$matches ) {
994 $taglist = implode( '|', $elements );
995 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
997 while ( $text != '' ) {
998 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1000 if ( count( $p ) < 5 ) {
1003 if ( count( $p ) > 5 ) {
1012 $attributes = $p[2];
1017 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1018 $stripped .= $marker;
1020 if ( $close === '/>' ) {
1021 # Empty element tag, <tag />
1026 if ( $element === '!--' ) {
1029 $end = "/(<\\/$element\\s*>)/i";
1031 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1033 if ( count( $q ) < 3 ) {
1034 # No end tag -- let it run out to the end of the text.
1043 $matches[$marker] = [ $element,
1045 Sanitizer
::decodeTagAttributes( $attributes ),
1046 "<$element$attributes$close$content$tail" ];
1052 * Get a list of strippable XML-like elements
1056 public function getStripList() {
1057 return $this->mStripList
;
1061 * Add an item to the strip state
1062 * Returns the unique tag which must be inserted into the stripped text
1063 * The tag will be replaced with the original text in unstrip()
1065 * @param string $text
1069 public function insertStripItem( $text ) {
1070 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1071 $this->mMarkerIndex++
;
1072 $this->mStripState
->addGeneral( $marker, $text );
1077 * parse the wiki syntax used to render tables
1080 * @param string $text
1083 public function doTableStuff( $text ) {
1084 $lines = StringUtils
::explode( "\n", $text );
1086 $td_history = []; # Is currently a td tag open?
1087 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1088 $tr_history = []; # Is currently a tr tag open?
1089 $tr_attributes = []; # history of tr attributes
1090 $has_opened_tr = []; # Did this table open a <tr> element?
1091 $indent_level = 0; # indent level of the table
1093 foreach ( $lines as $outLine ) {
1094 $line = trim( $outLine );
1096 if ( $line === '' ) { # empty line, go to next line
1097 $out .= $outLine . "\n";
1101 $first_character = $line[0];
1102 $first_two = substr( $line, 0, 2 );
1105 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1106 # First check if we are starting a new table
1107 $indent_level = strlen( $matches[1] );
1109 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1110 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1112 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1113 array_push( $td_history, false );
1114 array_push( $last_tag_history, '' );
1115 array_push( $tr_history, false );
1116 array_push( $tr_attributes, '' );
1117 array_push( $has_opened_tr, false );
1118 } elseif ( count( $td_history ) == 0 ) {
1119 # Don't do any of the following
1120 $out .= $outLine . "\n";
1122 } elseif ( $first_two === '|}' ) {
1123 # We are ending a table
1124 $line = '</table>' . substr( $line, 2 );
1125 $last_tag = array_pop( $last_tag_history );
1127 if ( !array_pop( $has_opened_tr ) ) {
1128 $line = "<tr><td></td></tr>{$line}";
1131 if ( array_pop( $tr_history ) ) {
1132 $line = "</tr>{$line}";
1135 if ( array_pop( $td_history ) ) {
1136 $line = "</{$last_tag}>{$line}";
1138 array_pop( $tr_attributes );
1139 if ( $indent_level > 0 ) {
1140 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1144 } elseif ( $first_two === '|-' ) {
1145 # Now we have a table row
1146 $line = preg_replace( '#^\|-+#', '', $line );
1148 # Whats after the tag is now only attributes
1149 $attributes = $this->mStripState
->unstripBoth( $line );
1150 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1151 array_pop( $tr_attributes );
1152 array_push( $tr_attributes, $attributes );
1155 $last_tag = array_pop( $last_tag_history );
1156 array_pop( $has_opened_tr );
1157 array_push( $has_opened_tr, true );
1159 if ( array_pop( $tr_history ) ) {
1163 if ( array_pop( $td_history ) ) {
1164 $line = "</{$last_tag}>{$line}";
1168 array_push( $tr_history, false );
1169 array_push( $td_history, false );
1170 array_push( $last_tag_history, '' );
1171 } elseif ( $first_character === '|'
1172 ||
$first_character === '!'
1173 ||
$first_two === '|+'
1175 # This might be cell elements, td, th or captions
1176 if ( $first_two === '|+' ) {
1177 $first_character = '+';
1178 $line = substr( $line, 2 );
1180 $line = substr( $line, 1 );
1183 // Implies both are valid for table headings.
1184 if ( $first_character === '!' ) {
1185 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1188 # Split up multiple cells on the same line.
1189 # FIXME : This can result in improper nesting of tags processed
1190 # by earlier parser steps.
1191 $cells = explode( '||', $line );
1195 # Loop through each table cell
1196 foreach ( $cells as $cell ) {
1198 if ( $first_character !== '+' ) {
1199 $tr_after = array_pop( $tr_attributes );
1200 if ( !array_pop( $tr_history ) ) {
1201 $previous = "<tr{$tr_after}>\n";
1203 array_push( $tr_history, true );
1204 array_push( $tr_attributes, '' );
1205 array_pop( $has_opened_tr );
1206 array_push( $has_opened_tr, true );
1209 $last_tag = array_pop( $last_tag_history );
1211 if ( array_pop( $td_history ) ) {
1212 $previous = "</{$last_tag}>\n{$previous}";
1215 if ( $first_character === '|' ) {
1217 } elseif ( $first_character === '!' ) {
1219 } elseif ( $first_character === '+' ) {
1220 $last_tag = 'caption';
1225 array_push( $last_tag_history, $last_tag );
1227 # A cell could contain both parameters and data
1228 $cell_data = explode( '|', $cell, 2 );
1230 # T2553: Note that a '|' inside an invalid link should not
1231 # be mistaken as delimiting cell parameters
1232 # Bug T153140: Neither should language converter markup.
1233 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1234 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1235 } elseif ( count( $cell_data ) == 1 ) {
1236 // Whitespace in cells is trimmed
1237 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1239 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1240 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1241 // Whitespace in cells is trimmed
1242 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1246 array_push( $td_history, true );
1249 $out .= $outLine . "\n";
1252 # Closing open td, tr && table
1253 while ( count( $td_history ) > 0 ) {
1254 if ( array_pop( $td_history ) ) {
1257 if ( array_pop( $tr_history ) ) {
1260 if ( !array_pop( $has_opened_tr ) ) {
1261 $out .= "<tr><td></td></tr>\n";
1264 $out .= "</table>\n";
1267 # Remove trailing line-ending (b/c)
1268 if ( substr( $out, -1 ) === "\n" ) {
1269 $out = substr( $out, 0, -1 );
1272 # special case: don't return empty table
1273 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1281 * Helper function for parse() that transforms wiki markup into half-parsed
1282 * HTML. Only called for $mOutputType == self::OT_HTML.
1286 * @param string $text The text to parse
1287 * @param bool $isMain Whether this is being called from the main parse() function
1288 * @param PPFrame|bool $frame A pre-processor frame
1292 public function internalParse( $text, $isMain = true, $frame = false ) {
1295 // Avoid PHP 7.1 warning from passing $this by reference
1298 # Hook to suspend the parser in this state
1299 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1303 # if $frame is provided, then use $frame for replacing any variables
1305 # use frame depth to infer how include/noinclude tags should be handled
1306 # depth=0 means this is the top-level document; otherwise it's an included document
1307 if ( !$frame->depth
) {
1310 $flag = self
::PTD_FOR_INCLUSION
;
1312 $dom = $this->preprocessToDom( $text, $flag );
1313 $text = $frame->expand( $dom );
1315 # if $frame is not provided, then use old-style replaceVariables
1316 $text = $this->replaceVariables( $text );
1319 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1320 $text = Sanitizer
::removeHTMLtags(
1322 [ $this, 'attributeStripCallback' ],
1324 array_keys( $this->mTransparentTagHooks
),
1326 [ $this, 'addTrackingCategory' ]
1328 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1330 # Tables need to come after variable replacement for things to work
1331 # properly; putting them before other transformations should keep
1332 # exciting things like link expansions from showing up in surprising
1334 $text = $this->doTableStuff( $text );
1336 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1338 $text = $this->doDoubleUnderscore( $text );
1340 $text = $this->doHeadings( $text );
1341 $text = $this->replaceInternalLinks( $text );
1342 $text = $this->doAllQuotes( $text );
1343 $text = $this->replaceExternalLinks( $text );
1345 # replaceInternalLinks may sometimes leave behind
1346 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1347 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1349 $text = $this->doMagicLinks( $text );
1350 $text = $this->formatHeadings( $text, $origText, $isMain );
1356 * Helper function for parse() that transforms half-parsed HTML into fully
1359 * @param string $text
1360 * @param bool $isMain
1361 * @param bool $linestart
1364 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1365 $text = $this->mStripState
->unstripGeneral( $text );
1367 // Avoid PHP 7.1 warning from passing $this by reference
1371 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1374 # Clean up special characters, only run once, next-to-last before doBlockLevels
1375 $text = Sanitizer
::armorFrenchSpaces( $text );
1377 $text = $this->doBlockLevels( $text, $linestart );
1379 $this->replaceLinkHolders( $text );
1382 * The input doesn't get language converted if
1384 * b) Content isn't converted
1385 * c) It's a conversion table
1386 * d) it is an interface message (which is in the user language)
1388 if ( !( $this->mOptions
->getDisableContentConversion()
1389 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1391 if ( !$this->mOptions
->getInterfaceMessage() ) {
1392 # The position of the convert() call should not be changed. it
1393 # assumes that the links are all replaced and the only thing left
1394 # is the <nowiki> mark.
1395 $text = $this->getTargetLanguage()->convert( $text );
1399 $text = $this->mStripState
->unstripNoWiki( $text );
1402 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1405 $text = $this->replaceTransparentTags( $text );
1406 $text = $this->mStripState
->unstripGeneral( $text );
1408 $text = Sanitizer
::normalizeCharReferences( $text );
1410 if ( MWTidy
::isEnabled() ) {
1411 if ( $this->mOptions
->getTidy() ) {
1412 $text = MWTidy
::tidy( $text );
1415 # attempt to sanitize at least some nesting problems
1416 # (T4702 and quite a few others)
1418 # ''Something [http://www.cool.com cool''] -->
1419 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1420 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1421 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1422 # fix up an anchor inside another anchor, only
1423 # at least for a single single nested link (T5695)
1424 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1425 '\\1\\2</a>\\3</a>\\1\\4</a>',
1426 # fix div inside inline elements- doBlockLevels won't wrap a line which
1427 # contains a div, so fix it up here; replace
1428 # div with escaped text
1429 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1430 '\\1\\3<div\\5>\\6</div>\\8\\9',
1431 # remove empty italic or bold tag pairs, some
1432 # introduced by rules above
1433 '/<([bi])><\/\\1>/' => '',
1436 $text = preg_replace(
1437 array_keys( $tidyregs ),
1438 array_values( $tidyregs ),
1443 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1450 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1451 * magic external links.
1456 * @param string $text
1460 public function doMagicLinks( $text ) {
1461 $prots = wfUrlProtocolsWithoutProtRel();
1462 $urlChar = self
::EXT_LINK_URL_CLASS
;
1463 $addr = self
::EXT_LINK_ADDR
;
1464 $space = self
::SPACE_NOT_NL
; # non-newline space
1465 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1466 $spaces = "$space++"; # possessive match of 1 or more spaces
1467 $text = preg_replace_callback(
1469 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1470 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1471 (\b # m[3]: Free external links
1473 ($addr$urlChar*) # m[4]: Post-protocol path
1475 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1477 \bISBN $spaces ( # m[6]: ISBN, capture number
1478 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1479 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1480 [0-9Xx] # check digit
1482 )!xu", [ $this, 'magicLinkCallback' ], $text );
1487 * @throws MWException
1489 * @return string HTML
1491 public function magicLinkCallback( $m ) {
1492 if ( isset( $m[1] ) && $m[1] !== '' ) {
1495 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1498 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1499 # Free external link
1500 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1501 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1503 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1504 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1509 $cssClass = 'mw-magiclink-rfc';
1510 $trackingCat = 'magiclink-tracking-rfc';
1512 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1513 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1517 $urlmsg = 'pubmedurl';
1518 $cssClass = 'mw-magiclink-pmid';
1519 $trackingCat = 'magiclink-tracking-pmid';
1522 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1523 substr( $m[0], 0, 20 ) . '"' );
1525 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1526 $this->addTrackingCategory( $trackingCat );
1527 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1528 } elseif ( isset( $m[6] ) && $m[6] !== ''
1529 && $this->mOptions
->getMagicISBNLinks()
1533 $space = self
::SPACE_NOT_NL
; # non-newline space
1534 $isbn = preg_replace( "/$space/", ' ', $isbn );
1535 $num = strtr( $isbn, [
1540 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1541 return $this->getLinkRenderer()->makeKnownLink(
1542 SpecialPage
::getTitleFor( 'Booksources', $num ),
1545 'class' => 'internal mw-magiclink-isbn',
1546 'title' => false // suppress title attribute
1555 * Make a free external link, given a user-supplied URL
1557 * @param string $url
1558 * @param int $numPostProto
1559 * The number of characters after the protocol.
1560 * @return string HTML
1563 public function makeFreeExternalLink( $url, $numPostProto ) {
1566 # The characters '<' and '>' (which were escaped by
1567 # removeHTMLtags()) should not be included in
1568 # URLs, per RFC 2396.
1569 # Make terminate a URL as well (bug T84937)
1572 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1577 $trail = substr( $url, $m2[0][1] ) . $trail;
1578 $url = substr( $url, 0, $m2[0][1] );
1581 # Move trailing punctuation to $trail
1583 # If there is no left bracket, then consider right brackets fair game too
1584 if ( strpos( $url, '(' ) === false ) {
1588 $urlRev = strrev( $url );
1589 $numSepChars = strspn( $urlRev, $sep );
1590 # Don't break a trailing HTML entity by moving the ; into $trail
1591 # This is in hot code, so use substr_compare to avoid having to
1592 # create a new string object for the comparison
1593 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1594 # more optimization: instead of running preg_match with a $
1595 # anchor, which can be slow, do the match on the reversed
1596 # string starting at the desired offset.
1597 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1598 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1602 if ( $numSepChars ) {
1603 $trail = substr( $url, -$numSepChars ) . $trail;
1604 $url = substr( $url, 0, -$numSepChars );
1607 # Verify that we still have a real URL after trail removal, and
1608 # not just lone protocol
1609 if ( strlen( $trail ) >= $numPostProto ) {
1610 return $url . $trail;
1613 $url = Sanitizer
::cleanUrl( $url );
1615 # Is this an external image?
1616 $text = $this->maybeMakeExternalImage( $url );
1617 if ( $text === false ) {
1618 # Not an image, make a link
1619 $text = Linker
::makeExternalLink( $url,
1620 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1622 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1623 # Register it in the output object...
1624 $this->mOutput
->addExternalLink( $url );
1626 return $text . $trail;
1630 * Parse headers and return html
1634 * @param string $text
1638 public function doHeadings( $text ) {
1639 for ( $i = 6; $i >= 1; --$i ) {
1640 $h = str_repeat( '=', $i );
1641 // Trim non-newline whitespace from headings
1642 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1643 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1649 * Replace single quotes with HTML markup
1652 * @param string $text
1654 * @return string The altered text
1656 public function doAllQuotes( $text ) {
1658 $lines = StringUtils
::explode( "\n", $text );
1659 foreach ( $lines as $line ) {
1660 $outtext .= $this->doQuotes( $line ) . "\n";
1662 $outtext = substr( $outtext, 0, -1 );
1667 * Helper function for doAllQuotes()
1669 * @param string $text
1673 public function doQuotes( $text ) {
1674 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1675 $countarr = count( $arr );
1676 if ( $countarr == 1 ) {
1680 // First, do some preliminary work. This may shift some apostrophes from
1681 // being mark-up to being text. It also counts the number of occurrences
1682 // of bold and italics mark-ups.
1685 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1686 $thislen = strlen( $arr[$i] );
1687 // If there are ever four apostrophes, assume the first is supposed to
1688 // be text, and the remaining three constitute mark-up for bold text.
1689 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1690 if ( $thislen == 4 ) {
1691 $arr[$i - 1] .= "'";
1694 } elseif ( $thislen > 5 ) {
1695 // If there are more than 5 apostrophes in a row, assume they're all
1696 // text except for the last 5.
1697 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1698 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1702 // Count the number of occurrences of bold and italics mark-ups.
1703 if ( $thislen == 2 ) {
1705 } elseif ( $thislen == 3 ) {
1707 } elseif ( $thislen == 5 ) {
1713 // If there is an odd number of both bold and italics, it is likely
1714 // that one of the bold ones was meant to be an apostrophe followed
1715 // by italics. Which one we cannot know for certain, but it is more
1716 // likely to be one that has a single-letter word before it.
1717 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1718 $firstsingleletterword = -1;
1719 $firstmultiletterword = -1;
1721 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1722 if ( strlen( $arr[$i] ) == 3 ) {
1723 $x1 = substr( $arr[$i - 1], -1 );
1724 $x2 = substr( $arr[$i - 1], -2, 1 );
1725 if ( $x1 === ' ' ) {
1726 if ( $firstspace == -1 ) {
1729 } elseif ( $x2 === ' ' ) {
1730 $firstsingleletterword = $i;
1731 // if $firstsingleletterword is set, we don't
1732 // look at the other options, so we can bail early.
1735 if ( $firstmultiletterword == -1 ) {
1736 $firstmultiletterword = $i;
1742 // If there is a single-letter word, use it!
1743 if ( $firstsingleletterword > -1 ) {
1744 $arr[$firstsingleletterword] = "''";
1745 $arr[$firstsingleletterword - 1] .= "'";
1746 } elseif ( $firstmultiletterword > -1 ) {
1747 // If not, but there's a multi-letter word, use that one.
1748 $arr[$firstmultiletterword] = "''";
1749 $arr[$firstmultiletterword - 1] .= "'";
1750 } elseif ( $firstspace > -1 ) {
1751 // ... otherwise use the first one that has neither.
1752 // (notice that it is possible for all three to be -1 if, for example,
1753 // there is only one pentuple-apostrophe in the line)
1754 $arr[$firstspace] = "''";
1755 $arr[$firstspace - 1] .= "'";
1759 // Now let's actually convert our apostrophic mush to HTML!
1764 foreach ( $arr as $r ) {
1765 if ( ( $i %
2 ) == 0 ) {
1766 if ( $state === 'both' ) {
1772 $thislen = strlen( $r );
1773 if ( $thislen == 2 ) {
1774 if ( $state === 'i' ) {
1777 } elseif ( $state === 'bi' ) {
1780 } elseif ( $state === 'ib' ) {
1781 $output .= '</b></i><b>';
1783 } elseif ( $state === 'both' ) {
1784 $output .= '<b><i>' . $buffer . '</i>';
1786 } else { // $state can be 'b' or ''
1790 } elseif ( $thislen == 3 ) {
1791 if ( $state === 'b' ) {
1794 } elseif ( $state === 'bi' ) {
1795 $output .= '</i></b><i>';
1797 } elseif ( $state === 'ib' ) {
1800 } elseif ( $state === 'both' ) {
1801 $output .= '<i><b>' . $buffer . '</b>';
1803 } else { // $state can be 'i' or ''
1807 } elseif ( $thislen == 5 ) {
1808 if ( $state === 'b' ) {
1809 $output .= '</b><i>';
1811 } elseif ( $state === 'i' ) {
1812 $output .= '</i><b>';
1814 } elseif ( $state === 'bi' ) {
1815 $output .= '</i></b>';
1817 } elseif ( $state === 'ib' ) {
1818 $output .= '</b></i>';
1820 } elseif ( $state === 'both' ) {
1821 $output .= '<i><b>' . $buffer . '</b></i>';
1823 } else { // ($state == '')
1831 // Now close all remaining tags. Notice that the order is important.
1832 if ( $state === 'b' ||
$state === 'ib' ) {
1835 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1838 if ( $state === 'bi' ) {
1841 // There might be lonely ''''', so make sure we have a buffer
1842 if ( $state === 'both' && $buffer ) {
1843 $output .= '<b><i>' . $buffer . '</i></b>';
1849 * Replace external links (REL)
1851 * Note: this is all very hackish and the order of execution matters a lot.
1852 * Make sure to run tests/parser/parserTests.php if you change this code.
1856 * @param string $text
1858 * @throws MWException
1861 public function replaceExternalLinks( $text ) {
1862 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1863 if ( $bits === false ) {
1864 throw new MWException( "PCRE needs to be compiled with "
1865 . "--enable-unicode-properties in order for MediaWiki to function" );
1867 $s = array_shift( $bits );
1870 while ( $i < count( $bits ) ) {
1873 $text = $bits[$i++
];
1874 $trail = $bits[$i++
];
1876 # The characters '<' and '>' (which were escaped by
1877 # removeHTMLtags()) should not be included in
1878 # URLs, per RFC 2396.
1880 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1881 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1882 $url = substr( $url, 0, $m2[0][1] );
1885 # If the link text is an image URL, replace it with an <img> tag
1886 # This happened by accident in the original parser, but some people used it extensively
1887 $img = $this->maybeMakeExternalImage( $text );
1888 if ( $img !== false ) {
1894 # Set linktype for CSS
1897 # No link text, e.g. [http://domain.tld/some.link]
1898 if ( $text == '' ) {
1900 $langObj = $this->getTargetLanguage();
1901 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1902 $linktype = 'autonumber';
1904 # Have link text, e.g. [http://domain.tld/some.link text]s
1906 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1909 // Excluding protocol-relative URLs may avoid many false positives.
1910 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1911 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1914 $url = Sanitizer
::cleanUrl( $url );
1916 # Use the encoded URL
1917 # This means that users can paste URLs directly into the text
1918 # Funny characters like ö aren't valid in URLs anyway
1919 # This was changed in August 2004
1920 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1921 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1923 # Register link in the output object.
1924 $this->mOutput
->addExternalLink( $url );
1931 * Get the rel attribute for a particular external link.
1934 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1935 * nofollow if appropriate
1936 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1937 * @return string|null Rel attribute for $url
1939 public static function getExternalLinkRel( $url = false, $title = null ) {
1940 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1941 $ns = $title ?
$title->getNamespace() : false;
1942 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1943 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1951 * Get an associative array of additional HTML attributes appropriate for a
1952 * particular external link. This currently may include rel => nofollow
1953 * (depending on configuration, namespace, and the URL's domain) and/or a
1954 * target attribute (depending on configuration).
1956 * @param string $url URL to extract the domain from for rel =>
1957 * nofollow if appropriate
1958 * @return array Associative array of HTML attributes
1960 public function getExternalLinkAttribs( $url ) {
1962 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1964 $target = $this->mOptions
->getExternalLinkTarget();
1966 $attribs['target'] = $target;
1967 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1968 // T133507. New windows can navigate parent cross-origin.
1969 // Including noreferrer due to lacking browser
1970 // support of noopener. Eventually noreferrer should be removed.
1971 if ( $rel !== '' ) {
1974 $rel .= 'noreferrer noopener';
1977 $attribs['rel'] = $rel;
1982 * Replace unusual escape codes in a URL with their equivalent characters
1984 * This generally follows the syntax defined in RFC 3986, with special
1985 * consideration for HTTP query strings.
1987 * @param string $url
1990 public static function normalizeLinkUrl( $url ) {
1991 # First, make sure unsafe characters are encoded
1992 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1994 return rawurlencode( $m[0] );
2000 $end = strlen( $url );
2002 # Fragment part - 'fragment'
2003 $start = strpos( $url, '#' );
2004 if ( $start !== false && $start < $end ) {
2005 $ret = self
::normalizeUrlComponent(
2006 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2010 # Query part - 'query' minus &=+;
2011 $start = strpos( $url, '?' );
2012 if ( $start !== false && $start < $end ) {
2013 $ret = self
::normalizeUrlComponent(
2014 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2018 # Scheme and path part - 'pchar'
2019 # (we assume no userinfo or encoded colons in the host)
2020 $ret = self
::normalizeUrlComponent(
2021 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2026 private static function normalizeUrlComponent( $component, $unsafe ) {
2027 $callback = function ( $matches ) use ( $unsafe ) {
2028 $char = urldecode( $matches[0] );
2029 $ord = ord( $char );
2030 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2034 # Leave it escaped, but use uppercase for a-f
2035 return strtoupper( $matches[0] );
2038 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2042 * make an image if it's allowed, either through the global
2043 * option, through the exception, or through the on-wiki whitelist
2045 * @param string $url
2049 private function maybeMakeExternalImage( $url ) {
2050 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2051 $imagesexception = !empty( $imagesfrom );
2053 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2054 if ( $imagesexception && is_array( $imagesfrom ) ) {
2055 $imagematch = false;
2056 foreach ( $imagesfrom as $match ) {
2057 if ( strpos( $url, $match ) === 0 ) {
2062 } elseif ( $imagesexception ) {
2063 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2065 $imagematch = false;
2068 if ( $this->mOptions
->getAllowExternalImages()
2069 ||
( $imagesexception && $imagematch )
2071 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2073 $text = Linker
::makeExternalImage( $url );
2076 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2077 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2079 $whitelist = explode(
2081 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2084 foreach ( $whitelist as $entry ) {
2085 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2086 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2089 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2090 # Image matches a whitelist entry
2091 $text = Linker
::makeExternalImage( $url );
2100 * Process [[ ]] wikilinks
2104 * @return string Processed text
2108 public function replaceInternalLinks( $s ) {
2109 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2114 * Process [[ ]] wikilinks (RIL)
2116 * @throws MWException
2117 * @return LinkHolderArray
2121 public function replaceInternalLinks2( &$s ) {
2122 global $wgExtraInterlanguageLinkPrefixes;
2124 static $tc = false, $e1, $e1_img;
2125 # the % is needed to support urlencoded titles as well
2127 $tc = Title
::legalChars() . '#%';
2128 # Match a link having the form [[namespace:link|alternate]]trail
2129 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2130 # Match cases where there is no "]]", which might still be images
2131 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2134 $holders = new LinkHolderArray( $this );
2136 # split the entire text string on occurrences of [[
2137 $a = StringUtils
::explode( '[[', ' ' . $s );
2138 # get the first element (all text up to first [[), and remove the space we added
2141 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2142 $s = substr( $s, 1 );
2144 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2146 if ( $useLinkPrefixExtension ) {
2147 # Match the end of a line for a word that's not followed by whitespace,
2148 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2150 $charset = $wgContLang->linkPrefixCharset();
2151 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2154 if ( is_null( $this->mTitle
) ) {
2155 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2157 $nottalk = !$this->mTitle
->isTalkPage();
2159 if ( $useLinkPrefixExtension ) {
2161 if ( preg_match( $e2, $s, $m ) ) {
2162 $first_prefix = $m[2];
2164 $first_prefix = false;
2170 $useSubpages = $this->areSubpagesAllowed();
2172 # Loop for each link
2173 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2174 # Check for excessive memory usage
2175 if ( $holders->isBig() ) {
2177 # Do the existence check, replace the link holders and clear the array
2178 $holders->replace( $s );
2182 if ( $useLinkPrefixExtension ) {
2183 if ( preg_match( $e2, $s, $m ) ) {
2190 if ( $first_prefix ) {
2191 $prefix = $first_prefix;
2192 $first_prefix = false;
2196 $might_be_img = false;
2198 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2200 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2201 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2202 # the real problem is with the $e1 regex
2204 # Still some problems for cases where the ] is meant to be outside punctuation,
2205 # and no image is in sight. See T4095.
2207 && substr( $m[3], 0, 1 ) === ']'
2208 && strpos( $text, '[' ) !== false
2210 $text .= ']'; # so that replaceExternalLinks($text) works later
2211 $m[3] = substr( $m[3], 1 );
2213 # fix up urlencoded title texts
2214 if ( strpos( $m[1], '%' ) !== false ) {
2215 # Should anchors '#' also be rejected?
2216 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2219 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2220 # Invalid, but might be an image with a link in its caption
2221 $might_be_img = true;
2223 if ( strpos( $m[1], '%' ) !== false ) {
2224 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2227 } else { # Invalid form; output directly
2228 $s .= $prefix . '[[' . $line;
2232 $origLink = ltrim( $m[1], ' ' );
2234 # Don't allow internal links to pages containing
2235 # PROTO: where PROTO is a valid URL protocol; these
2236 # should be external links.
2237 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2238 $s .= $prefix . '[[' . $line;
2242 # Make subpage if necessary
2243 if ( $useSubpages ) {
2244 $link = $this->maybeDoSubpageLink( $origLink, $text );
2249 // \x7f isn't a default legal title char, so most likely strip
2250 // markers will force us into the "invalid form" path above. But,
2251 // just in case, let's assert that xmlish tags aren't valid in
2252 // the title position.
2253 $unstrip = $this->mStripState
->killMarkers( $link );
2254 $noMarkers = ( $unstrip === $link );
2256 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2257 if ( $nt === null ) {
2258 $s .= $prefix . '[[' . $line;
2262 $ns = $nt->getNamespace();
2263 $iw = $nt->getInterwiki();
2265 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2267 if ( $might_be_img ) { # if this is actually an invalid link
2268 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2271 # look at the next 'line' to see if we can close it there
2273 $next_line = $a->current();
2274 if ( $next_line === false ||
$next_line === null ) {
2277 $m = explode( ']]', $next_line, 3 );
2278 if ( count( $m ) == 3 ) {
2279 # the first ]] closes the inner link, the second the image
2281 $text .= "[[{$m[0]}]]{$m[1]}";
2284 } elseif ( count( $m ) == 2 ) {
2285 # if there's exactly one ]] that's fine, we'll keep looking
2286 $text .= "[[{$m[0]}]]{$m[1]}";
2288 # if $next_line is invalid too, we need look no further
2289 $text .= '[[' . $next_line;
2294 # we couldn't find the end of this imageLink, so output it raw
2295 # but don't ignore what might be perfectly normal links in the text we've examined
2296 $holders->merge( $this->replaceInternalLinks2( $text ) );
2297 $s .= "{$prefix}[[$link|$text";
2298 # note: no $trail, because without an end, there *is* no trail
2301 } else { # it's not an image, so output it raw
2302 $s .= "{$prefix}[[$link|$text";
2303 # note: no $trail, because without an end, there *is* no trail
2308 $wasblank = ( $text == '' );
2312 # Strip off leading ':'
2313 $text = substr( $text, 1 );
2316 # T6598 madness. Handle the quotes only if they come from the alternate part
2317 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2318 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2319 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2320 $text = $this->doQuotes( $text );
2323 # Link not escaped by : , create the various objects
2324 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2327 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2328 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2329 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2332 # T26502: filter duplicates
2333 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2334 $this->mLangLinkLanguages
[$iw] = true;
2335 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2339 * Strip the whitespace interwiki links produce, see T10897
2341 $s = rtrim( $s . $prefix ) . $trail; # T175416
2345 if ( $ns == NS_FILE
) {
2346 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2348 # if no parameters were passed, $text
2349 # becomes something like "File:Foo.png",
2350 # which we don't want to pass on to the
2354 # recursively parse links inside the image caption
2355 # actually, this will parse them in any other parameters, too,
2356 # but it might be hard to fix that, and it doesn't matter ATM
2357 $text = $this->replaceExternalLinks( $text );
2358 $holders->merge( $this->replaceInternalLinks2( $text ) );
2360 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2361 $s .= $prefix . $this->armorLinks(
2362 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2365 } elseif ( $ns == NS_CATEGORY
) {
2367 * Strip the whitespace Category links produce, see T2087
2369 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2372 $sortkey = $this->getDefaultSort();
2376 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2377 $sortkey = str_replace( "\n", '', $sortkey );
2378 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2379 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2385 # Self-link checking. For some languages, variants of the title are checked in
2386 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2387 # for linking to a different variant.
2388 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2389 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2393 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2394 # @todo FIXME: Should do batch file existence checks, see comment below
2395 if ( $ns == NS_MEDIA
) {
2396 # Give extensions a chance to select the file revision for us
2399 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2400 [ $this, $nt, &$options, &$descQuery ] );
2401 # Fetch and register the file (file title may be different via hooks)
2402 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2403 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2404 $s .= $prefix . $this->armorLinks(
2405 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2409 # Some titles, such as valid special pages or files in foreign repos, should
2410 # be shown as bluelinks even though they're not included in the page table
2411 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2412 # batch file existence checks for NS_FILE and NS_MEDIA
2413 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2414 $this->mOutput
->addLink( $nt );
2415 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2417 # Links will be added to the output link list after checking
2418 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2425 * Render a forced-blue link inline; protect against double expansion of
2426 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2427 * Since this little disaster has to split off the trail text to avoid
2428 * breaking URLs in the following text without breaking trails on the
2429 * wiki links, it's been made into a horrible function.
2432 * @param string $text
2433 * @param string $trail
2434 * @param string $prefix
2435 * @return string HTML-wikitext mix oh yuck
2437 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2438 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2440 if ( $text == '' ) {
2441 $text = htmlspecialchars( $nt->getPrefixedText() );
2444 $link = $this->getLinkRenderer()->makeKnownLink(
2445 $nt, new HtmlArmor( "$prefix$text$inside" )
2448 return $this->armorLinks( $link ) . $trail;
2452 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2453 * going to go through further parsing steps before inline URL expansion.
2455 * Not needed quite as much as it used to be since free links are a bit
2456 * more sensible these days. But bracketed links are still an issue.
2458 * @param string $text More-or-less HTML
2459 * @return string Less-or-more HTML with NOPARSE bits
2461 public function armorLinks( $text ) {
2462 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2463 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2467 * Return true if subpage links should be expanded on this page.
2470 public function areSubpagesAllowed() {
2471 # Some namespaces don't allow subpages
2472 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2476 * Handle link to subpage if necessary
2478 * @param string $target The source of the link
2479 * @param string &$text The link text, modified as necessary
2480 * @return string The full name of the link
2483 public function maybeDoSubpageLink( $target, &$text ) {
2484 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2488 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2490 * @param string $text
2491 * @param bool $linestart Whether or not this is at the start of a line.
2493 * @return string The lists rendered as HTML
2495 public function doBlockLevels( $text, $linestart ) {
2496 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2500 * Return value of a magic variable (like PAGENAME)
2504 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2505 * @param bool|PPFrame $frame
2507 * @throws MWException
2510 public function getVariableValue( $index, $frame = false ) {
2511 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2512 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2514 if ( is_null( $this->mTitle
) ) {
2515 // If no title set, bad things are going to happen
2516 // later. Title should always be set since this
2517 // should only be called in the middle of a parse
2518 // operation (but the unit-tests do funky stuff)
2519 throw new MWException( __METHOD__
. ' Should only be '
2520 . ' called while parsing (no title set)' );
2523 // Avoid PHP 7.1 warning from passing $this by reference
2527 * Some of these require message or data lookups and can be
2528 * expensive to check many times.
2530 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2531 if ( isset( $this->mVarCache
[$index] ) ) {
2532 return $this->mVarCache
[$index];
2536 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2537 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2539 $pageLang = $this->getFunctionLang();
2545 case 'currentmonth':
2546 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2548 case 'currentmonth1':
2549 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2551 case 'currentmonthname':
2552 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2554 case 'currentmonthnamegen':
2555 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2557 case 'currentmonthabbrev':
2558 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2561 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2564 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2567 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2570 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2572 case 'localmonthname':
2573 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2575 case 'localmonthnamegen':
2576 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2578 case 'localmonthabbrev':
2579 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2582 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2585 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2588 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2591 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2593 case 'fullpagename':
2594 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2596 case 'fullpagenamee':
2597 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2600 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2602 case 'subpagenamee':
2603 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2605 case 'rootpagename':
2606 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2608 case 'rootpagenamee':
2609 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2612 $this->mTitle
->getRootText()
2615 case 'basepagename':
2616 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2618 case 'basepagenamee':
2619 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2622 $this->mTitle
->getBaseText()
2625 case 'talkpagename':
2626 if ( $this->mTitle
->canHaveTalkPage() ) {
2627 $talkPage = $this->mTitle
->getTalkPage();
2628 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2633 case 'talkpagenamee':
2634 if ( $this->mTitle
->canHaveTalkPage() ) {
2635 $talkPage = $this->mTitle
->getTalkPage();
2636 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2641 case 'subjectpagename':
2642 $subjPage = $this->mTitle
->getSubjectPage();
2643 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2645 case 'subjectpagenamee':
2646 $subjPage = $this->mTitle
->getSubjectPage();
2647 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2649 case 'pageid': // requested in T25427
2650 $pageid = $this->getTitle()->getArticleID();
2651 if ( $pageid == 0 ) {
2652 # 0 means the page doesn't exist in the database,
2653 # which means the user is previewing a new page.
2654 # The vary-revision flag must be set, because the magic word
2655 # will have a different value once the page is saved.
2656 $this->mOutput
->setFlag( 'vary-revision' );
2657 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2659 $value = $pageid ?
: null;
2662 # Let the edit saving system know we should parse the page
2663 # *after* a revision ID has been assigned.
2664 $this->mOutput
->setFlag( 'vary-revision-id' );
2665 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2666 $value = $this->mRevisionId
;
2667 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2668 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2669 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2673 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2675 case 'revisionday2':
2676 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2678 case 'revisionmonth':
2679 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2681 case 'revisionmonth1':
2682 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2684 case 'revisionyear':
2685 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2687 case 'revisiontimestamp':
2688 # Let the edit saving system know we should parse the page
2689 # *after* a revision ID has been assigned. This is for null edits.
2690 $this->mOutput
->setFlag( 'vary-revision' );
2691 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2692 $value = $this->getRevisionTimestamp();
2694 case 'revisionuser':
2695 # Let the edit saving system know we should parse the page
2696 # *after* a revision ID has been assigned for null edits.
2697 $this->mOutput
->setFlag( 'vary-user' );
2698 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2699 $value = $this->getRevisionUser();
2701 case 'revisionsize':
2702 $value = $this->getRevisionSize();
2705 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2708 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2710 case 'namespacenumber':
2711 $value = $this->mTitle
->getNamespace();
2714 $value = $this->mTitle
->canHaveTalkPage()
2715 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2719 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2721 case 'subjectspace':
2722 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2724 case 'subjectspacee':
2725 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2727 case 'currentdayname':
2728 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2731 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2734 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2737 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2740 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2741 # int to remove the padding
2742 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2745 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2747 case 'localdayname':
2748 $value = $pageLang->getWeekdayName(
2749 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2753 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2756 $value = $pageLang->time(
2757 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2763 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2766 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2767 # int to remove the padding
2768 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2771 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2773 case 'numberofarticles':
2774 $value = $pageLang->formatNum( SiteStats
::articles() );
2776 case 'numberoffiles':
2777 $value = $pageLang->formatNum( SiteStats
::images() );
2779 case 'numberofusers':
2780 $value = $pageLang->formatNum( SiteStats
::users() );
2782 case 'numberofactiveusers':
2783 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2785 case 'numberofpages':
2786 $value = $pageLang->formatNum( SiteStats
::pages() );
2788 case 'numberofadmins':
2789 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2791 case 'numberofedits':
2792 $value = $pageLang->formatNum( SiteStats
::edits() );
2794 case 'currenttimestamp':
2795 $value = wfTimestamp( TS_MW
, $ts );
2797 case 'localtimestamp':
2798 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2800 case 'currentversion':
2801 $value = SpecialVersion
::getVersion();
2804 return $wgArticlePath;
2810 return $wgServerName;
2812 return $wgScriptPath;
2814 return $wgStylePath;
2815 case 'directionmark':
2816 return $pageLang->getDirMark();
2817 case 'contentlanguage':
2818 global $wgLanguageCode;
2819 return $wgLanguageCode;
2820 case 'pagelanguage':
2821 $value = $pageLang->getCode();
2823 case 'cascadingsources':
2824 $value = CoreParserFunctions
::cascadingsources( $this );
2829 'ParserGetVariableValueSwitch',
2830 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2837 $this->mVarCache
[$index] = $value;
2846 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2847 * @param string $variable Parser variable name
2850 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2853 # Get the timezone-adjusted timestamp to be used for this revision
2854 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2855 # Possibly set vary-revision if there is not yet an associated revision
2856 if ( !$this->getRevisionObject() ) {
2857 # Get the timezone-adjusted timestamp $mtts seconds in the future
2859 $wgContLang->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2864 if ( $resNow !== $resThen ) {
2865 # Let the edit saving system know we should parse the page
2866 # *after* a revision ID has been assigned. This is for null edits.
2867 $this->mOutput
->setFlag( 'vary-revision' );
2868 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2876 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2880 public function initialiseVariables() {
2881 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2882 $substIDs = $this->magicWordFactory
->getSubstIDs();
2884 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2885 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2889 * Preprocess some wikitext and return the document tree.
2890 * This is the ghost of replace_variables().
2892 * @param string $text The text to parse
2893 * @param int $flags Bitwise combination of:
2894 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2895 * included. Default is to assume a direct page view.
2897 * The generated DOM tree must depend only on the input text and the flags.
2898 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2900 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2901 * change in the DOM tree for a given text, must be passed through the section identifier
2902 * in the section edit link and thus back to extractSections().
2904 * The output of this function is currently only cached in process memory, but a persistent
2905 * cache may be implemented at a later date which takes further advantage of these strict
2906 * dependency requirements.
2910 public function preprocessToDom( $text, $flags = 0 ) {
2911 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2916 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2922 public static function splitWhitespace( $s ) {
2923 $ltrimmed = ltrim( $s );
2924 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2925 $trimmed = rtrim( $ltrimmed );
2926 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2928 $w2 = substr( $ltrimmed, -$diff );
2932 return [ $w1, $trimmed, $w2 ];
2936 * Replace magic variables, templates, and template arguments
2937 * with the appropriate text. Templates are substituted recursively,
2938 * taking care to avoid infinite loops.
2940 * Note that the substitution depends on value of $mOutputType:
2941 * self::OT_WIKI: only {{subst:}} templates
2942 * self::OT_PREPROCESS: templates but not extension tags
2943 * self::OT_HTML: all templates and extension tags
2945 * @param string $text The text to transform
2946 * @param bool|PPFrame $frame Object describing the arguments passed to the
2947 * template. Arguments may also be provided as an associative array, as
2948 * was the usual case before MW1.12. Providing arguments this way may be
2949 * useful for extensions wishing to perform variable replacement
2951 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2952 * double-brace expansion.
2955 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2956 # Is there any text? Also, Prevent too big inclusions!
2957 $textSize = strlen( $text );
2958 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2962 if ( $frame === false ) {
2963 $frame = $this->getPreprocessor()->newFrame();
2964 } elseif ( !( $frame instanceof PPFrame
) ) {
2965 wfDebug( __METHOD__
. " called using plain parameters instead of "
2966 . "a PPFrame instance. Creating custom frame.\n" );
2967 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2970 $dom = $this->preprocessToDom( $text );
2971 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2972 $text = $frame->expand( $dom, $flags );
2978 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2980 * @param array $args
2984 public static function createAssocArgs( $args ) {
2987 foreach ( $args as $arg ) {
2988 $eqpos = strpos( $arg, '=' );
2989 if ( $eqpos === false ) {
2990 $assocArgs[$index++
] = $arg;
2992 $name = trim( substr( $arg, 0, $eqpos ) );
2993 $value = trim( substr( $arg, $eqpos +
1 ) );
2994 if ( $value === false ) {
2997 if ( $name !== false ) {
2998 $assocArgs[$name] = $value;
3007 * Warn the user when a parser limitation is reached
3008 * Will warn at most once the user per limitation type
3010 * The results are shown during preview and run through the Parser (See EditPage.php)
3012 * @param string $limitationType Should be one of:
3013 * 'expensive-parserfunction' (corresponding messages:
3014 * 'expensive-parserfunction-warning',
3015 * 'expensive-parserfunction-category')
3016 * 'post-expand-template-argument' (corresponding messages:
3017 * 'post-expand-template-argument-warning',
3018 * 'post-expand-template-argument-category')
3019 * 'post-expand-template-inclusion' (corresponding messages:
3020 * 'post-expand-template-inclusion-warning',
3021 * 'post-expand-template-inclusion-category')
3022 * 'node-count-exceeded' (corresponding messages:
3023 * 'node-count-exceeded-warning',
3024 * 'node-count-exceeded-category')
3025 * 'expansion-depth-exceeded' (corresponding messages:
3026 * 'expansion-depth-exceeded-warning',
3027 * 'expansion-depth-exceeded-category')
3028 * @param string|int|null $current Current value
3029 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3030 * exceeded, provide the values (optional)
3032 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3033 # does no harm if $current and $max are present but are unnecessary for the message
3034 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3035 # only during preview, and that would split the parser cache unnecessarily.
3036 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3038 $this->mOutput
->addWarning( $warning );
3039 $this->addTrackingCategory( "$limitationType-category" );
3043 * Return the text of a template, after recursively
3044 * replacing any variables or templates within the template.
3046 * @param array $piece The parts of the template
3047 * $piece['title']: the title, i.e. the part before the |
3048 * $piece['parts']: the parameter array
3049 * $piece['lineStart']: whether the brace was at the start of a line
3050 * @param PPFrame $frame The current frame, contains template arguments
3052 * @return string The text of the template
3054 public function braceSubstitution( $piece, $frame ) {
3057 // $text has been filled
3059 // wiki markup in $text should be escaped
3061 // $text is HTML, armour it against wikitext transformation
3063 // Force interwiki transclusion to be done in raw mode not rendered
3064 $forceRawInterwiki = false;
3065 // $text is a DOM node needing expansion in a child frame
3066 $isChildObj = false;
3067 // $text is a DOM node needing expansion in the current frame
3068 $isLocalObj = false;
3070 # Title object, where $text came from
3073 # $part1 is the bit before the first |, and must contain only title characters.
3074 # Various prefixes will be stripped from it later.
3075 $titleWithSpaces = $frame->expand( $piece['title'] );
3076 $part1 = trim( $titleWithSpaces );
3079 # Original title text preserved for various purposes
3080 $originalTitle = $part1;
3082 # $args is a list of argument nodes, starting from index 0, not including $part1
3083 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3084 # below won't work b/c this $args isn't an object
3085 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3087 $profileSection = null; // profile templates
3091 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3093 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3094 # Decide whether to expand template or keep wikitext as-is.
3095 if ( $this->ot
['wiki'] ) {
3096 if ( $substMatch === false ) {
3097 $literal = true; # literal when in PST with no prefix
3099 $literal = false; # expand when in PST with subst: or safesubst:
3102 if ( $substMatch == 'subst' ) {
3103 $literal = true; # literal when not in PST with plain subst:
3105 $literal = false; # expand when not in PST with safesubst: or no prefix
3109 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3116 if ( !$found && $args->getLength() == 0 ) {
3117 $id = $this->mVariables
->matchStartToEnd( $part1 );
3118 if ( $id !== false ) {
3119 $text = $this->getVariableValue( $id, $frame );
3120 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3121 $this->mOutput
->updateCacheExpiry(
3122 $this->magicWordFactory
->getCacheTTL( $id ) );
3128 # MSG, MSGNW and RAW
3131 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3132 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3135 # Remove obsolete MSG:
3136 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3137 $mwMsg->matchStartAndRemove( $part1 );
3141 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3142 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3143 $forceRawInterwiki = true;
3149 $colonPos = strpos( $part1, ':' );
3150 if ( $colonPos !== false ) {
3151 $func = substr( $part1, 0, $colonPos );
3152 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3153 $argsLength = $args->getLength();
3154 for ( $i = 0; $i < $argsLength; $i++
) {
3155 $funcArgs[] = $args->item( $i );
3158 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3160 // Extract any forwarded flags
3161 if ( isset( $result['title'] ) ) {
3162 $title = $result['title'];
3164 if ( isset( $result['found'] ) ) {
3165 $found = $result['found'];
3167 if ( array_key_exists( 'text', $result ) ) {
3169 $text = $result['text'];
3171 if ( isset( $result['nowiki'] ) ) {
3172 $nowiki = $result['nowiki'];
3174 if ( isset( $result['isHTML'] ) ) {
3175 $isHTML = $result['isHTML'];
3177 if ( isset( $result['forceRawInterwiki'] ) ) {
3178 $forceRawInterwiki = $result['forceRawInterwiki'];
3180 if ( isset( $result['isChildObj'] ) ) {
3181 $isChildObj = $result['isChildObj'];
3183 if ( isset( $result['isLocalObj'] ) ) {
3184 $isLocalObj = $result['isLocalObj'];
3189 # Finish mangling title and then check for loops.
3190 # Set $title to a Title object and $titleText to the PDBK
3193 # Split the title into page and subpage
3195 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3196 if ( $part1 !== $relative ) {
3198 $ns = $this->mTitle
->getNamespace();
3200 $title = Title
::newFromText( $part1, $ns );
3202 $titleText = $title->getPrefixedText();
3203 # Check for language variants if the template is not found
3204 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3205 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3207 # Do recursion depth check
3208 $limit = $this->mOptions
->getMaxTemplateDepth();
3209 if ( $frame->depth
>= $limit ) {
3211 $text = '<span class="error">'
3212 . wfMessage( 'parser-template-recursion-depth-warning' )
3213 ->numParams( $limit )->inContentLanguage()->text()
3219 # Load from database
3220 if ( !$found && $title ) {
3221 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3222 if ( !$title->isExternal() ) {
3223 if ( $title->isSpecialPage()
3224 && $this->mOptions
->getAllowSpecialInclusion()
3225 && $this->ot
['html']
3227 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3228 // Pass the template arguments as URL parameters.
3229 // "uselang" will have no effect since the Language object
3230 // is forced to the one defined in ParserOptions.
3232 $argsLength = $args->getLength();
3233 for ( $i = 0; $i < $argsLength; $i++
) {
3234 $bits = $args->item( $i )->splitArg();
3235 if ( strval( $bits['index'] ) === '' ) {
3236 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3237 $value = trim( $frame->expand( $bits['value'] ) );
3238 $pageArgs[$name] = $value;
3242 // Create a new context to execute the special page
3243 $context = new RequestContext
;
3244 $context->setTitle( $title );
3245 $context->setRequest( new FauxRequest( $pageArgs ) );
3246 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3247 $context->setUser( $this->getUser() );
3249 // If this page is cached, then we better not be per user.
3250 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3252 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3253 $ret = SpecialPageFactory
::capturePath(
3254 $title, $context, $this->getLinkRenderer() );
3256 $text = $context->getOutput()->getHTML();
3257 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3260 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3261 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3262 $specialPage->maxIncludeCacheTime()
3266 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3267 $found = false; # access denied
3268 wfDebug( __METHOD__
. ": template inclusion denied for " .
3269 $title->getPrefixedDBkey() . "\n" );
3271 list( $text, $title ) = $this->getTemplateDom( $title );
3272 if ( $text !== false ) {
3278 # If the title is valid but undisplayable, make a link to it
3279 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3280 $text = "[[:$titleText]]";
3283 } elseif ( $title->isTrans() ) {
3284 # Interwiki transclusion
3285 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3286 $text = $this->interwikiTransclude( $title, 'render' );
3289 $text = $this->interwikiTransclude( $title, 'raw' );
3290 # Preprocess it like a template
3291 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3297 # Do infinite loop check
3298 # This has to be done after redirect resolution to avoid infinite loops via redirects
3299 if ( !$frame->loopCheck( $title ) ) {
3301 $text = '<span class="error">'
3302 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3304 $this->addTrackingCategory( 'template-loop-category' );
3305 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3306 wfEscapeWikiText( $titleText ) )->text() );
3307 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3311 # If we haven't found text to substitute by now, we're done
3312 # Recover the source wikitext and return it
3314 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3315 if ( $profileSection ) {
3316 $this->mProfiler
->scopedProfileOut( $profileSection );
3318 return [ 'object' => $text ];
3321 # Expand DOM-style return values in a child frame
3322 if ( $isChildObj ) {
3323 # Clean up argument array
3324 $newFrame = $frame->newChild( $args, $title );
3327 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3328 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3329 # Expansion is eligible for the empty-frame cache
3330 $text = $newFrame->cachedExpand( $titleText, $text );
3332 # Uncached expansion
3333 $text = $newFrame->expand( $text );
3336 if ( $isLocalObj && $nowiki ) {
3337 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3338 $isLocalObj = false;
3341 if ( $profileSection ) {
3342 $this->mProfiler
->scopedProfileOut( $profileSection );
3345 # Replace raw HTML by a placeholder
3347 $text = $this->insertStripItem( $text );
3348 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3349 # Escape nowiki-style return values
3350 $text = wfEscapeWikiText( $text );
3351 } elseif ( is_string( $text )
3352 && !$piece['lineStart']
3353 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3355 # T2529: if the template begins with a table or block-level
3356 # element, it should be treated as beginning a new line.
3357 # This behavior is somewhat controversial.
3358 $text = "\n" . $text;
3361 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3362 # Error, oversize inclusion
3363 if ( $titleText !== false ) {
3364 # Make a working, properly escaped link if possible (T25588)
3365 $text = "[[:$titleText]]";
3367 # This will probably not be a working link, but at least it may
3368 # provide some hint of where the problem is
3369 preg_replace( '/^:/', '', $originalTitle );
3370 $text = "[[:$originalTitle]]";
3372 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3373 . 'post-expand include size too large -->' );
3374 $this->limitationWarn( 'post-expand-template-inclusion' );
3377 if ( $isLocalObj ) {
3378 $ret = [ 'object' => $text ];
3380 $ret = [ 'text' => $text ];
3387 * Call a parser function and return an array with text and flags.
3389 * The returned array will always contain a boolean 'found', indicating
3390 * whether the parser function was found or not. It may also contain the
3392 * text: string|object, resulting wikitext or PP DOM object
3393 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3394 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3395 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3396 * nowiki: bool, wiki markup in $text should be escaped
3399 * @param PPFrame $frame The current frame, contains template arguments
3400 * @param string $function Function name
3401 * @param array $args Arguments to the function
3402 * @throws MWException
3405 public function callParserFunction( $frame, $function, array $args = [] ) {
3408 # Case sensitive functions
3409 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3410 $function = $this->mFunctionSynonyms
[1][$function];
3412 # Case insensitive functions
3413 $function = $wgContLang->lc( $function );
3414 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3415 $function = $this->mFunctionSynonyms
[0][$function];
3417 return [ 'found' => false ];
3421 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3423 // Avoid PHP 7.1 warning from passing $this by reference
3426 $allArgs = [ &$parser ];
3427 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3428 # Convert arguments to PPNodes and collect for appending to $allArgs
3430 foreach ( $args as $k => $v ) {
3431 if ( $v instanceof PPNode ||
$k === 0 ) {
3434 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3438 # Add a frame parameter, and pass the arguments as an array
3439 $allArgs[] = $frame;
3440 $allArgs[] = $funcArgs;
3442 # Convert arguments to plain text and append to $allArgs
3443 foreach ( $args as $k => $v ) {
3444 if ( $v instanceof PPNode
) {
3445 $allArgs[] = trim( $frame->expand( $v ) );
3446 } elseif ( is_int( $k ) && $k >= 0 ) {
3447 $allArgs[] = trim( $v );
3449 $allArgs[] = trim( "$k=$v" );
3454 $result = $callback( ...$allArgs );
3456 # The interface for function hooks allows them to return a wikitext
3457 # string or an array containing the string and any flags. This mungs
3458 # things around to match what this method should return.
3459 if ( !is_array( $result ) ) {
3465 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3466 $result['text'] = $result[0];
3468 unset( $result[0] );
3475 $preprocessFlags = 0;
3476 if ( isset( $result['noparse'] ) ) {
3477 $noparse = $result['noparse'];
3479 if ( isset( $result['preprocessFlags'] ) ) {
3480 $preprocessFlags = $result['preprocessFlags'];
3484 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3485 $result['isChildObj'] = true;
3492 * Get the semi-parsed DOM representation of a template with a given title,
3493 * and its redirect destination title. Cached.
3495 * @param Title $title
3499 public function getTemplateDom( $title ) {
3500 $cacheTitle = $title;
3501 $titleText = $title->getPrefixedDBkey();
3503 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3504 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3505 $title = Title
::makeTitle( $ns, $dbk );
3506 $titleText = $title->getPrefixedDBkey();
3508 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3509 return [ $this->mTplDomCache
[$titleText], $title ];
3512 # Cache miss, go to the database
3513 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3515 if ( $text === false ) {
3516 $this->mTplDomCache
[$titleText] = false;
3517 return [ false, $title ];
3520 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3521 $this->mTplDomCache
[$titleText] = $dom;
3523 if ( !$title->equals( $cacheTitle ) ) {
3524 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3525 [ $title->getNamespace(), $title->getDBkey() ];
3528 return [ $dom, $title ];
3532 * Fetch the current revision of a given title. Note that the revision
3533 * (and even the title) may not exist in the database, so everything
3534 * contributing to the output of the parser should use this method
3535 * where possible, rather than getting the revisions themselves. This
3536 * method also caches its results, so using it benefits performance.
3539 * @param Title $title
3542 public function fetchCurrentRevisionOfTitle( $title ) {
3543 $cacheKey = $title->getPrefixedDBkey();
3544 if ( !$this->currentRevisionCache
) {
3545 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3547 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3548 $this->currentRevisionCache
->set( $cacheKey,
3549 // Defaults to Parser::statelessFetchRevision()
3550 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3553 return $this->currentRevisionCache
->get( $cacheKey );
3557 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3558 * without passing them on to it.
3561 * @param Title $title
3562 * @param Parser|bool $parser
3563 * @return Revision|bool False if missing
3565 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3566 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3572 * Fetch the unparsed text of a template and register a reference to it.
3573 * @param Title $title
3574 * @return array ( string or false, Title )
3576 public function fetchTemplateAndTitle( $title ) {
3577 // Defaults to Parser::statelessFetchTemplate()
3578 $templateCb = $this->mOptions
->getTemplateCallback();
3579 $stuff = call_user_func( $templateCb, $title, $this );
3580 // We use U+007F DELETE to distinguish strip markers from regular text.
3581 $text = $stuff['text'];
3582 if ( is_string( $stuff['text'] ) ) {
3583 $text = strtr( $text, "\x7f", "?" );
3585 $finalTitle = $stuff['finalTitle'] ??
$title;
3586 if ( isset( $stuff['deps'] ) ) {
3587 foreach ( $stuff['deps'] as $dep ) {
3588 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3589 if ( $dep['title']->equals( $this->getTitle() ) ) {
3590 // If we transclude ourselves, the final result
3591 // will change based on the new version of the page
3592 $this->mOutput
->setFlag( 'vary-revision' );
3596 return [ $text, $finalTitle ];
3600 * Fetch the unparsed text of a template and register a reference to it.
3601 * @param Title $title
3602 * @return string|bool
3604 public function fetchTemplate( $title ) {
3605 return $this->fetchTemplateAndTitle( $title )[0];
3609 * Static function to get a template
3610 * Can be overridden via ParserOptions::setTemplateCallback().
3612 * @param Title $title
3613 * @param bool|Parser $parser
3617 public static function statelessFetchTemplate( $title, $parser = false ) {
3618 $text = $skip = false;
3619 $finalTitle = $title;
3622 # Loop to fetch the article, with up to 1 redirect
3623 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3624 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3625 # Give extensions a chance to select the revision instead
3626 $id = false; # Assume current
3627 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3628 [ $parser, $title, &$skip, &$id ] );
3634 'page_id' => $title->getArticleID(),
3641 $rev = Revision
::newFromId( $id );
3642 } elseif ( $parser ) {
3643 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3645 $rev = Revision
::newFromTitle( $title );
3647 $rev_id = $rev ?
$rev->getId() : 0;
3648 # If there is no current revision, there is no page
3649 if ( $id === false && !$rev ) {
3650 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3651 $linkCache->addBadLinkObj( $title );
3656 'page_id' => $title->getArticleID(),
3657 'rev_id' => $rev_id ];
3658 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3659 # We fetched a rev from a different title; register it too...
3661 'title' => $rev->getTitle(),
3662 'page_id' => $rev->getPage(),
3663 'rev_id' => $rev_id ];
3667 $content = $rev->getContent();
3668 $text = $content ?
$content->getWikitextForTransclusion() : null;
3670 Hooks
::run( 'ParserFetchTemplate',
3671 [ $parser, $title, $rev, &$text, &$deps ] );
3673 if ( $text === false ||
$text === null ) {
3677 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3679 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3680 if ( !$message->exists() ) {
3684 $content = $message->content();
3685 $text = $message->plain();
3693 $finalTitle = $title;
3694 $title = $content->getRedirectTarget();
3698 'finalTitle' => $finalTitle,
3703 * Fetch a file and its title and register a reference to it.
3704 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3705 * @param Title $title
3706 * @param array $options Array of options to RepoGroup::findFile
3708 * @deprecated since 1.32, use fetchFileAndTitle instead
3710 public function fetchFile( $title, $options = [] ) {
3711 wfDeprecated( __METHOD__
, '1.32' );
3712 return $this->fetchFileAndTitle( $title, $options )[0];
3716 * Fetch a file and its title and register a reference to it.
3717 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3718 * @param Title $title
3719 * @param array $options Array of options to RepoGroup::findFile
3720 * @return array ( File or false, Title of file )
3722 public function fetchFileAndTitle( $title, $options = [] ) {
3723 $file = $this->fetchFileNoRegister( $title, $options );
3725 $time = $file ?
$file->getTimestamp() : false;
3726 $sha1 = $file ?
$file->getSha1() : false;
3727 # Register the file as a dependency...
3728 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3729 if ( $file && !$title->equals( $file->getTitle() ) ) {
3730 # Update fetched file title
3731 $title = $file->getTitle();
3732 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3734 return [ $file, $title ];
3738 * Helper function for fetchFileAndTitle.
3740 * Also useful if you need to fetch a file but not use it yet,
3741 * for example to get the file's handler.
3743 * @param Title $title
3744 * @param array $options Array of options to RepoGroup::findFile
3747 protected function fetchFileNoRegister( $title, $options = [] ) {
3748 if ( isset( $options['broken'] ) ) {
3749 $file = false; // broken thumbnail forced by hook
3750 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3751 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3752 } else { // get by (name,timestamp)
3753 $file = wfFindFile( $title, $options );
3759 * Transclude an interwiki link.
3761 * @param Title $title
3762 * @param string $action
3766 public function interwikiTransclude( $title, $action ) {
3767 global $wgEnableScaryTranscluding;
3769 if ( !$wgEnableScaryTranscluding ) {
3770 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3773 $url = $title->getFullURL( [ 'action' => $action ] );
3775 if ( strlen( $url ) > 255 ) {
3776 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3778 return $this->fetchScaryTemplateMaybeFromCache( $url );
3782 * @param string $url
3783 * @return mixed|string
3785 public function fetchScaryTemplateMaybeFromCache( $url ) {
3786 global $wgTranscludeCacheExpiry;
3787 $dbr = wfGetDB( DB_REPLICA
);
3788 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3789 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3790 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3792 return $obj->tc_contents
;
3795 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3796 $status = $req->execute(); // Status object
3797 if ( $status->isOK() ) {
3798 $text = $req->getContent();
3799 } elseif ( $req->getStatus() != 200 ) {
3800 // Though we failed to fetch the content, this status is useless.
3801 return wfMessage( 'scarytranscludefailed-httpstatus' )
3802 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3804 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3807 $dbw = wfGetDB( DB_MASTER
);
3808 $dbw->replace( 'transcache', [ 'tc_url' ], [
3810 'tc_time' => $dbw->timestamp( time() ),
3811 'tc_contents' => $text
3817 * Triple brace replacement -- used for template arguments
3820 * @param array $piece
3821 * @param PPFrame $frame
3825 public function argSubstitution( $piece, $frame ) {
3827 $parts = $piece['parts'];
3828 $nameWithSpaces = $frame->expand( $piece['title'] );
3829 $argName = trim( $nameWithSpaces );
3831 $text = $frame->getArgument( $argName );
3832 if ( $text === false && $parts->getLength() > 0
3833 && ( $this->ot
['html']
3835 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3838 # No match in frame, use the supplied default
3839 $object = $parts->item( 0 )->getChildren();
3841 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3842 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3843 $this->limitationWarn( 'post-expand-template-argument' );
3846 if ( $text === false && $object === false ) {
3848 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3850 if ( $error !== false ) {
3853 if ( $object !== false ) {
3854 $ret = [ 'object' => $object ];
3856 $ret = [ 'text' => $text ];
3863 * Return the text to be used for a given extension tag.
3864 * This is the ghost of strip().
3866 * @param array $params Associative array of parameters:
3867 * name PPNode for the tag name
3868 * attr PPNode for unparsed text where tag attributes are thought to be
3869 * attributes Optional associative array of parsed attributes
3870 * inner Contents of extension element
3871 * noClose Original text did not have a close tag
3872 * @param PPFrame $frame
3874 * @throws MWException
3877 public function extensionSubstitution( $params, $frame ) {
3878 static $errorStr = '<span class="error">';
3879 static $errorLen = 20;
3881 $name = $frame->expand( $params['name'] );
3882 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3883 // Probably expansion depth or node count exceeded. Just punt the
3888 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3889 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3894 // We can't safely check if the expansion for $content resulted in an
3895 // error, because the content could happen to be the error string
3897 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3899 $marker = self
::MARKER_PREFIX
. "-$name-"
3900 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3902 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3903 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3904 if ( $isFunctionTag ) {
3905 $markerType = 'none';
3907 $markerType = 'general';
3909 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3910 $name = strtolower( $name );
3911 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3912 if ( isset( $params['attributes'] ) ) {
3913 $attributes = $attributes +
$params['attributes'];
3916 if ( isset( $this->mTagHooks
[$name] ) ) {
3917 $output = call_user_func_array( $this->mTagHooks
[$name],
3918 [ $content, $attributes, $this, $frame ] );
3919 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3920 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3922 // Avoid PHP 7.1 warning from passing $this by reference
3924 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3926 $output = '<span class="error">Invalid tag extension name: ' .
3927 htmlspecialchars( $name ) . '</span>';
3930 if ( is_array( $output ) ) {
3933 $output = $flags[0];
3934 if ( isset( $flags['markerType'] ) ) {
3935 $markerType = $flags['markerType'];
3939 if ( is_null( $attrText ) ) {
3942 if ( isset( $params['attributes'] ) ) {
3943 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3944 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3945 htmlspecialchars( $attrValue ) . '"';
3948 if ( $content === null ) {
3949 $output = "<$name$attrText/>";
3951 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3952 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3956 $output = "<$name$attrText>$content$close";
3960 if ( $markerType === 'none' ) {
3962 } elseif ( $markerType === 'nowiki' ) {
3963 $this->mStripState
->addNoWiki( $marker, $output );
3964 } elseif ( $markerType === 'general' ) {
3965 $this->mStripState
->addGeneral( $marker, $output );
3967 throw new MWException( __METHOD__
. ': invalid marker type' );
3973 * Increment an include size counter
3975 * @param string $type The type of expansion
3976 * @param int $size The size of the text
3977 * @return bool False if this inclusion would take it over the maximum, true otherwise
3979 public function incrementIncludeSize( $type, $size ) {
3980 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3983 $this->mIncludeSizes
[$type] +
= $size;
3989 * Increment the expensive function count
3991 * @return bool False if the limit has been exceeded
3993 public function incrementExpensiveFunctionCount() {
3994 $this->mExpensiveFunctionCount++
;
3995 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3999 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4000 * Fills $this->mDoubleUnderscores, returns the modified text
4002 * @param string $text
4006 public function doDoubleUnderscore( $text ) {
4007 # The position of __TOC__ needs to be recorded
4008 $mw = $this->magicWordFactory
->get( 'toc' );
4009 if ( $mw->match( $text ) ) {
4010 $this->mShowToc
= true;
4011 $this->mForceTocPosition
= true;
4013 # Set a placeholder. At the end we'll fill it in with the TOC.
4014 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4016 # Only keep the first one.
4017 $text = $mw->replace( '', $text );
4020 # Now match and remove the rest of them
4021 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4022 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4024 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4025 $this->mOutput
->mNoGallery
= true;
4027 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4028 $this->mShowToc
= false;
4030 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4031 && $this->mTitle
->getNamespace() == NS_CATEGORY
4033 $this->addTrackingCategory( 'hidden-category-category' );
4035 # (T10068) Allow control over whether robots index a page.
4036 # __INDEX__ always overrides __NOINDEX__, see T16899
4037 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4038 $this->mOutput
->setIndexPolicy( 'noindex' );
4039 $this->addTrackingCategory( 'noindex-category' );
4041 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4042 $this->mOutput
->setIndexPolicy( 'index' );
4043 $this->addTrackingCategory( 'index-category' );
4046 # Cache all double underscores in the database
4047 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4048 $this->mOutput
->setProperty( $key, '' );
4055 * @see ParserOutput::addTrackingCategory()
4056 * @param string $msg Message key
4057 * @return bool Whether the addition was successful
4059 public function addTrackingCategory( $msg ) {
4060 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4064 * This function accomplishes several tasks:
4065 * 1) Auto-number headings if that option is enabled
4066 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4067 * 3) Add a Table of contents on the top for users who have enabled the option
4068 * 4) Auto-anchor headings
4070 * It loops through all headlines, collects the necessary data, then splits up the
4071 * string and re-inserts the newly formatted headlines.
4073 * @param string $text
4074 * @param string $origText Original, untouched wikitext
4075 * @param bool $isMain
4076 * @return mixed|string
4079 public function formatHeadings( $text, $origText, $isMain = true ) {
4080 global $wgMaxTocLevel;
4082 # Inhibit editsection links if requested in the page
4083 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4084 $maybeShowEditLink = false;
4086 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4089 # Get all headlines for numbering them and adding funky stuff like [edit]
4090 # links - this is for later, but we need the number of headlines right now
4091 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4092 # be trimmed here since whitespace in HTML headings is significant.
4094 $numMatches = preg_match_all(
4095 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4100 # if there are fewer than 4 headlines in the article, do not show TOC
4101 # unless it's been explicitly enabled.
4102 $enoughToc = $this->mShowToc
&&
4103 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4105 # Allow user to stipulate that a page should have a "new section"
4106 # link added via __NEWSECTIONLINK__
4107 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4108 $this->mOutput
->setNewSection( true );
4111 # Allow user to remove the "new section"
4112 # link via __NONEWSECTIONLINK__
4113 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4114 $this->mOutput
->hideNewSection( true );
4117 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4118 # override above conditions and always show TOC above first header
4119 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4120 $this->mShowToc
= true;
4128 # Ugh .. the TOC should have neat indentation levels which can be
4129 # passed to the skin functions. These are determined here
4133 $sublevelCount = [];
4139 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4140 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4141 $oldType = $this->mOutputType
;
4142 $this->setOutputType( self
::OT_WIKI
);
4143 $frame = $this->getPreprocessor()->newFrame();
4144 $root = $this->preprocessToDom( $origText );
4145 $node = $root->getFirstChild();
4150 $headlines = $numMatches !== false ?
$matches[3] : [];
4152 foreach ( $headlines as $headline ) {
4153 $isTemplate = false;
4155 $sectionIndex = false;
4157 $markerMatches = [];
4158 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4159 $serial = $markerMatches[1];
4160 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4161 $isTemplate = ( $titleText != $baseTitleText );
4162 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4166 $prevlevel = $level;
4168 $level = $matches[1][$headlineCount];
4170 if ( $level > $prevlevel ) {
4171 # Increase TOC level
4173 $sublevelCount[$toclevel] = 0;
4174 if ( $toclevel < $wgMaxTocLevel ) {
4175 $prevtoclevel = $toclevel;
4176 $toc .= Linker
::tocIndent();
4179 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4180 # Decrease TOC level, find level to jump to
4182 for ( $i = $toclevel; $i > 0; $i-- ) {
4183 if ( $levelCount[$i] == $level ) {
4184 # Found last matching level
4187 } elseif ( $levelCount[$i] < $level ) {
4188 # Found first matching level below current level
4196 if ( $toclevel < $wgMaxTocLevel ) {
4197 if ( $prevtoclevel < $wgMaxTocLevel ) {
4198 # Unindent only if the previous toc level was shown :p
4199 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4200 $prevtoclevel = $toclevel;
4202 $toc .= Linker
::tocLineEnd();
4206 # No change in level, end TOC line
4207 if ( $toclevel < $wgMaxTocLevel ) {
4208 $toc .= Linker
::tocLineEnd();
4212 $levelCount[$toclevel] = $level;
4214 # count number of headlines for each level
4215 $sublevelCount[$toclevel]++
;
4217 for ( $i = 1; $i <= $toclevel; $i++
) {
4218 if ( !empty( $sublevelCount[$i] ) ) {
4222 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4227 # The safe header is a version of the header text safe to use for links
4229 # Remove link placeholders by the link text.
4230 # <!--LINK number-->
4232 # link text with suffix
4233 # Do this before unstrip since link text can contain strip markers
4234 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4236 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4237 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4239 # Remove any <style> or <script> tags (T198618)
4240 $safeHeadline = preg_replace(
4241 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4246 # Strip out HTML (first regex removes any tag not allowed)
4248 # * <sup> and <sub> (T10393)
4252 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4253 # * <s> and <strike> (T35715)
4254 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4255 # to allow setting directionality in toc items.
4256 $tocline = preg_replace(
4258 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4259 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4265 # Strip '<span></span>', which is the result from the above if
4266 # <span id="foo"></span> is used to produce an additional anchor
4268 $tocline = str_replace( '<span></span>', '', $tocline );
4270 $tocline = trim( $tocline );
4272 # For the anchor, strip out HTML-y stuff period
4273 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4274 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4276 # Save headline for section edit hint before it's escaped
4277 $headlineHint = $safeHeadline;
4279 # Decode HTML entities
4280 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4282 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4284 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4285 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4286 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4287 if ( $fallbackHeadline === $safeHeadline ) {
4288 # No reason to have both (in fact, we can't)
4289 $fallbackHeadline = false;
4292 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4293 # @todo FIXME: We may be changing them depending on the current locale.
4294 $arrayKey = strtolower( $safeHeadline );
4295 if ( $fallbackHeadline === false ) {
4296 $fallbackArrayKey = false;
4298 $fallbackArrayKey = strtolower( $fallbackHeadline );
4301 # Create the anchor for linking from the TOC to the section
4302 $anchor = $safeHeadline;
4303 $fallbackAnchor = $fallbackHeadline;
4304 if ( isset( $refers[$arrayKey] ) ) {
4305 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4306 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4308 $linkAnchor .= "_$i";
4309 $refers["${arrayKey}_$i"] = true;
4311 $refers[$arrayKey] = true;
4313 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4314 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4315 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4316 $fallbackAnchor .= "_$i";
4317 $refers["${fallbackArrayKey}_$i"] = true;
4319 $refers[$fallbackArrayKey] = true;
4322 # Don't number the heading if it is the only one (looks silly)
4323 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4324 # the two are different if the line contains a link
4325 $headline = Html
::element(
4327 [ 'class' => 'mw-headline-number' ],
4329 ) . ' ' . $headline;
4332 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4333 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4334 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4337 # Add the section to the section tree
4338 # Find the DOM node for this header
4339 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4340 while ( $node && !$noOffset ) {
4341 if ( $node->getName() === 'h' ) {
4342 $bits = $node->splitHeading();
4343 if ( $bits['i'] == $sectionIndex ) {
4347 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4348 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4349 $node = $node->getNextSibling();
4352 'toclevel' => $toclevel,
4355 'number' => $numbering,
4356 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4357 'fromtitle' => $titleText,
4358 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4359 'anchor' => $anchor,
4362 # give headline the correct <h#> tag
4363 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4364 // Output edit section links as markers with styles that can be customized by skins
4365 if ( $isTemplate ) {
4366 # Put a T flag in the section identifier, to indicate to extractSections()
4367 # that sections inside <includeonly> should be counted.
4368 $editsectionPage = $titleText;
4369 $editsectionSection = "T-$sectionIndex";
4370 $editsectionContent = null;
4372 $editsectionPage = $this->mTitle
->getPrefixedText();
4373 $editsectionSection = $sectionIndex;
4374 $editsectionContent = $headlineHint;
4376 // We use a bit of pesudo-xml for editsection markers. The
4377 // language converter is run later on. Using a UNIQ style marker
4378 // leads to the converter screwing up the tokens when it
4379 // converts stuff. And trying to insert strip tags fails too. At
4380 // this point all real inputted tags have already been escaped,
4381 // so we don't have to worry about a user trying to input one of
4382 // these markers directly. We use a page and section attribute
4383 // to stop the language converter from converting these
4384 // important bits of data, but put the headline hint inside a
4385 // content block because the language converter is supposed to
4386 // be able to convert that piece of data.
4387 // Gets replaced with html in ParserOutput::getText
4388 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4389 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4390 if ( $editsectionContent !== null ) {
4391 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4398 $head[$headlineCount] = Linker
::makeHeadline( $level,
4399 $matches['attrib'][$headlineCount], $anchor, $headline,
4400 $editlink, $fallbackAnchor );
4405 $this->setOutputType( $oldType );
4407 # Never ever show TOC if no headers
4408 if ( $numVisible < 1 ) {
4413 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4414 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4416 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4417 $this->mOutput
->setTOCHTML( $toc );
4418 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4422 $this->mOutput
->setSections( $tocraw );
4425 # split up and insert constructed headlines
4426 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4429 // build an array of document sections
4431 foreach ( $blocks as $block ) {
4432 // $head is zero-based, sections aren't.
4433 if ( empty( $head[$i - 1] ) ) {
4434 $sections[$i] = $block;
4436 $sections[$i] = $head[$i - 1] . $block;
4440 * Send a hook, one per section.
4441 * The idea here is to be able to make section-level DIVs, but to do so in a
4442 * lower-impact, more correct way than r50769
4445 * $section : the section number
4446 * &$sectionContent : ref to the content of the section
4447 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4449 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4454 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4455 // append the TOC at the beginning
4456 // Top anchor now in skin
4457 $sections[0] = $sections[0] . $toc . "\n";
4460 $full .= implode( '', $sections );
4462 if ( $this->mForceTocPosition
) {
4463 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4470 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4471 * conversion, substituting signatures, {{subst:}} templates, etc.
4473 * @param string $text The text to transform
4474 * @param Title $title The Title object for the current article
4475 * @param User $user The User object describing the current user
4476 * @param ParserOptions $options Parsing options
4477 * @param bool $clearState Whether to clear the parser state first
4478 * @return string The altered wiki markup
4480 public function preSaveTransform( $text, Title
$title, User
$user,
4481 ParserOptions
$options, $clearState = true
4483 if ( $clearState ) {
4484 $magicScopeVariable = $this->lock();
4486 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4487 $this->setUser( $user );
4489 // Strip U+0000 NULL (T159174)
4490 $text = str_replace( "\000", '', $text );
4492 // We still normalize line endings for backwards-compatibility
4493 // with other code that just calls PST, but this should already
4494 // be handled in TextContent subclasses
4495 $text = TextContent
::normalizeLineEndings( $text );
4497 if ( $options->getPreSaveTransform() ) {
4498 $text = $this->pstPass2( $text, $user );
4500 $text = $this->mStripState
->unstripBoth( $text );
4502 $this->setUser( null ); # Reset
4508 * Pre-save transform helper function
4510 * @param string $text
4515 private function pstPass2( $text, $user ) {
4518 # Note: This is the timestamp saved as hardcoded wikitext to
4519 # the database, we use $wgContLang here in order to give
4520 # everyone the same signature and use the default one rather
4521 # than the one selected in each user's preferences.
4523 $ts = $this->mOptions
->getTimestamp();
4524 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4525 $ts = $timestamp->format( 'YmdHis' );
4526 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4528 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4530 # Variable replacement
4531 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4532 $text = $this->replaceVariables( $text );
4534 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4535 # which may corrupt this parser instance via its wfMessage()->text() call-
4538 if ( strpos( $text, '~~~' ) !== false ) {
4539 $sigText = $this->getUserSig( $user );
4540 $text = strtr( $text, [
4542 '~~~~' => "$sigText $d",
4545 # The main two signature forms used above are time-sensitive
4546 $this->mOutput
->setFlag( 'user-signature' );
4549 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4550 $tc = '[' . Title
::legalChars() . ']';
4551 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4553 // [[ns:page (context)|]]
4554 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4555 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4556 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4557 // [[ns:page (context), context|]] (using either single or double-width comma)
4558 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4559 // [[|page]] (reverse pipe trick: add context from page title)
4560 $p2 = "/\[\[\\|($tc+)]]/";
4562 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4563 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4564 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4565 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4567 $t = $this->mTitle
->getText();
4569 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4570 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4571 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4572 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4574 # if there's no context, don't bother duplicating the title
4575 $text = preg_replace( $p2, '[[\\1]]', $text );
4582 * Fetch the user's signature text, if any, and normalize to
4583 * validated, ready-to-insert wikitext.
4584 * If you have pre-fetched the nickname or the fancySig option, you can
4585 * specify them here to save a database query.
4586 * Do not reuse this parser instance after calling getUserSig(),
4587 * as it may have changed if it's the $wgParser.
4589 * @param User &$user
4590 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4591 * @param bool|null $fancySig whether the nicknname is the complete signature
4592 * or null to use default value
4595 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4596 global $wgMaxSigChars;
4598 $username = $user->getName();
4600 # If not given, retrieve from the user object.
4601 if ( $nickname === false ) {
4602 $nickname = $user->getOption( 'nickname' );
4605 if ( is_null( $fancySig ) ) {
4606 $fancySig = $user->getBoolOption( 'fancysig' );
4609 $nickname = $nickname == null ?
$username : $nickname;
4611 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4612 $nickname = $username;
4613 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4614 } elseif ( $fancySig !== false ) {
4615 # Sig. might contain markup; validate this
4616 if ( $this->validateSig( $nickname ) !== false ) {
4617 # Validated; clean up (if needed) and return it
4618 return $this->cleanSig( $nickname, true );
4620 # Failed to validate; fall back to the default
4621 $nickname = $username;
4622 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4626 # Make sure nickname doesnt get a sig in a sig
4627 $nickname = self
::cleanSigInSig( $nickname );
4629 # If we're still here, make it a link to the user page
4630 $userText = wfEscapeWikiText( $username );
4631 $nickText = wfEscapeWikiText( $nickname );
4632 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4634 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4635 ->title( $this->getTitle() )->text();
4639 * Check that the user's signature contains no bad XML
4641 * @param string $text
4642 * @return string|bool An expanded string, or false if invalid.
4644 public function validateSig( $text ) {
4645 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4649 * Clean up signature text
4651 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4652 * 2) Substitute all transclusions
4654 * @param string $text
4655 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4656 * @return string Signature text
4658 public function cleanSig( $text, $parsing = false ) {
4661 $magicScopeVariable = $this->lock();
4662 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4665 # Option to disable this feature
4666 if ( !$this->mOptions
->getCleanSignatures() ) {
4670 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4671 # => Move this logic to braceSubstitution()
4672 $substWord = $this->magicWordFactory
->get( 'subst' );
4673 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4674 $substText = '{{' . $substWord->getSynonym( 0 );
4676 $text = preg_replace( $substRegex, $substText, $text );
4677 $text = self
::cleanSigInSig( $text );
4678 $dom = $this->preprocessToDom( $text );
4679 $frame = $this->getPreprocessor()->newFrame();
4680 $text = $frame->expand( $dom );
4683 $text = $this->mStripState
->unstripBoth( $text );
4690 * Strip 3, 4 or 5 tildes out of signatures.
4692 * @param string $text
4693 * @return string Signature text with /~{3,5}/ removed
4695 public static function cleanSigInSig( $text ) {
4696 $text = preg_replace( '/~{3,5}/', '', $text );
4701 * Set up some variables which are usually set up in parse()
4702 * so that an external function can call some class members with confidence
4704 * @param Title|null $title
4705 * @param ParserOptions $options
4706 * @param int $outputType
4707 * @param bool $clearState
4709 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4710 $outputType, $clearState = true
4712 $this->startParse( $title, $options, $outputType, $clearState );
4716 * @param Title|null $title
4717 * @param ParserOptions $options
4718 * @param int $outputType
4719 * @param bool $clearState
4721 private function startParse( Title
$title = null, ParserOptions
$options,
4722 $outputType, $clearState = true
4724 $this->setTitle( $title );
4725 $this->mOptions
= $options;
4726 $this->setOutputType( $outputType );
4727 if ( $clearState ) {
4728 $this->clearState();
4733 * Wrapper for preprocess()
4735 * @param string $text The text to preprocess
4736 * @param ParserOptions $options
4737 * @param Title|null $title Title object or null to use $wgTitle
4740 public function transformMsg( $text, $options, $title = null ) {
4741 static $executing = false;
4743 # Guard against infinite recursion
4754 $text = $this->preprocess( $text, $title, $options );
4761 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4762 * The callback should have the following form:
4763 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4765 * Transform and return $text. Use $parser for any required context, e.g. use
4766 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4768 * Hooks may return extended information by returning an array, of which the
4769 * first numbered element (index 0) must be the return string, and all other
4770 * entries are extracted into local variables within an internal function
4771 * in the Parser class.
4773 * This interface (introduced r61913) appears to be undocumented, but
4774 * 'markerType' is used by some core tag hooks to override which strip
4775 * array their results are placed in. **Use great caution if attempting
4776 * this interface, as it is not documented and injudicious use could smash
4777 * private variables.**
4779 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4780 * @param callable $callback The callback function (and object) to use for the tag
4781 * @throws MWException
4782 * @return callable|null The old value of the mTagHooks array associated with the hook
4784 public function setHook( $tag, callable
$callback ) {
4785 $tag = strtolower( $tag );
4786 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4787 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4789 $oldVal = $this->mTagHooks
[$tag] ??
null;
4790 $this->mTagHooks
[$tag] = $callback;
4791 if ( !in_array( $tag, $this->mStripList
) ) {
4792 $this->mStripList
[] = $tag;
4799 * As setHook(), but letting the contents be parsed.
4801 * Transparent tag hooks are like regular XML-style tag hooks, except they
4802 * operate late in the transformation sequence, on HTML instead of wikitext.
4804 * This is probably obsoleted by things dealing with parser frames?
4805 * The only extension currently using it is geoserver.
4808 * @todo better document or deprecate this
4810 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4811 * @param callable $callback The callback function (and object) to use for the tag
4812 * @throws MWException
4813 * @return callable|null The old value of the mTagHooks array associated with the hook
4815 public function setTransparentTagHook( $tag, callable
$callback ) {
4816 $tag = strtolower( $tag );
4817 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4818 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4820 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4821 $this->mTransparentTagHooks
[$tag] = $callback;
4827 * Remove all tag hooks
4829 public function clearTagHooks() {
4830 $this->mTagHooks
= [];
4831 $this->mFunctionTagHooks
= [];
4832 $this->mStripList
= $this->mDefaultStripList
;
4836 * Create a function, e.g. {{sum:1|2|3}}
4837 * The callback function should have the form:
4838 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4840 * Or with Parser::SFH_OBJECT_ARGS:
4841 * function myParserFunction( $parser, $frame, $args ) { ... }
4843 * The callback may either return the text result of the function, or an array with the text
4844 * in element 0, and a number of flags in the other elements. The names of the flags are
4845 * specified in the keys. Valid flags are:
4846 * found The text returned is valid, stop processing the template. This
4848 * nowiki Wiki markup in the return value should be escaped
4849 * isHTML The returned text is HTML, armour it against wikitext transformation
4851 * @param string $id The magic word ID
4852 * @param callable $callback The callback function (and object) to use
4853 * @param int $flags A combination of the following flags:
4854 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4856 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4857 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4858 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4859 * the arguments, and to control the way they are expanded.
4861 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4862 * arguments, for instance:
4863 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4865 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4866 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4867 * working if/when this is changed.
4869 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4872 * Please read the documentation in includes/parser/Preprocessor.php for more information
4873 * about the methods available in PPFrame and PPNode.
4875 * @throws MWException
4876 * @return string|callable The old callback function for this name, if any
4878 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4881 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4882 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4884 # Add to function cache
4885 $mw = $this->magicWordFactory
->get( $id );
4887 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4890 $synonyms = $mw->getSynonyms();
4891 $sensitive = intval( $mw->isCaseSensitive() );
4893 foreach ( $synonyms as $syn ) {
4895 if ( !$sensitive ) {
4896 $syn = $wgContLang->lc( $syn );
4899 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4902 # Remove trailing colon
4903 if ( substr( $syn, -1, 1 ) === ':' ) {
4904 $syn = substr( $syn, 0, -1 );
4906 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4912 * Get all registered function hook identifiers
4916 public function getFunctionHooks() {
4917 return array_keys( $this->mFunctionHooks
);
4921 * Create a tag function, e.g. "<test>some stuff</test>".
4922 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4923 * Unlike parser functions, their content is not preprocessed.
4924 * @param string $tag
4925 * @param callable $callback
4927 * @throws MWException
4930 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4931 $tag = strtolower( $tag );
4932 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4933 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4935 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4936 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4938 if ( !in_array( $tag, $this->mStripList
) ) {
4939 $this->mStripList
[] = $tag;
4946 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4947 * Placeholders created in Linker::link()
4949 * @param string &$text
4950 * @param int $options
4952 public function replaceLinkHolders( &$text, $options = 0 ) {
4953 $this->mLinkHolders
->replace( $text );
4957 * Replace "<!--LINK-->" link placeholders with plain text of links
4958 * (not HTML-formatted).
4960 * @param string $text
4963 public function replaceLinkHoldersText( $text ) {
4964 return $this->mLinkHolders
->replaceText( $text );
4968 * Renders an image gallery from a text with one line per image.
4969 * text labels may be given by using |-style alternative text. E.g.
4970 * Image:one.jpg|The number "1"
4971 * Image:tree.jpg|A tree
4972 * given as text will return the HTML of a gallery with two images,
4973 * labeled 'The number "1"' and
4976 * @param string $text
4977 * @param array $params
4978 * @return string HTML
4980 public function renderImageGallery( $text, $params ) {
4982 if ( isset( $params['mode'] ) ) {
4983 $mode = $params['mode'];
4987 $ig = ImageGalleryBase
::factory( $mode );
4988 } catch ( Exception
$e ) {
4989 // If invalid type set, fallback to default.
4990 $ig = ImageGalleryBase
::factory( false );
4993 $ig->setContextTitle( $this->mTitle
);
4994 $ig->setShowBytes( false );
4995 $ig->setShowDimensions( false );
4996 $ig->setShowFilename( false );
4997 $ig->setParser( $this );
4998 $ig->setHideBadImages();
4999 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5001 if ( isset( $params['showfilename'] ) ) {
5002 $ig->setShowFilename( true );
5004 $ig->setShowFilename( false );
5006 if ( isset( $params['caption'] ) ) {
5007 $caption = $params['caption'];
5008 $caption = htmlspecialchars( $caption );
5009 $caption = $this->replaceInternalLinks( $caption );
5010 $ig->setCaptionHtml( $caption );
5012 if ( isset( $params['perrow'] ) ) {
5013 $ig->setPerRow( $params['perrow'] );
5015 if ( isset( $params['widths'] ) ) {
5016 $ig->setWidths( $params['widths'] );
5018 if ( isset( $params['heights'] ) ) {
5019 $ig->setHeights( $params['heights'] );
5021 $ig->setAdditionalOptions( $params );
5023 // Avoid PHP 7.1 warning from passing $this by reference
5025 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5027 $lines = StringUtils
::explode( "\n", $text );
5028 foreach ( $lines as $line ) {
5029 # match lines like these:
5030 # Image:someimage.jpg|This is some image
5032 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5034 if ( count( $matches ) == 0 ) {
5038 if ( strpos( $matches[0], '%' ) !== false ) {
5039 $matches[1] = rawurldecode( $matches[1] );
5041 $title = Title
::newFromText( $matches[1], NS_FILE
);
5042 if ( is_null( $title ) ) {
5043 # Bogus title. Ignore these so we don't bomb out later.
5047 # We need to get what handler the file uses, to figure out parameters.
5048 # Note, a hook can overide the file name, and chose an entirely different
5049 # file (which potentially could be of a different type and have different handler).
5052 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5053 [ $this, $title, &$options, &$descQuery ] );
5054 # Don't register it now, as TraditionalImageGallery does that later.
5055 $file = $this->fetchFileNoRegister( $title, $options );
5056 $handler = $file ?
$file->getHandler() : false;
5059 'img_alt' => 'gallery-internal-alt',
5060 'img_link' => 'gallery-internal-link',
5063 $paramMap = $paramMap +
$handler->getParamMap();
5064 // We don't want people to specify per-image widths.
5065 // Additionally the width parameter would need special casing anyhow.
5066 unset( $paramMap['img_width'] );
5069 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5074 $handlerOptions = [];
5075 if ( isset( $matches[3] ) ) {
5076 // look for an |alt= definition while trying not to break existing
5077 // captions with multiple pipes (|) in it, until a more sensible grammar
5078 // is defined for images in galleries
5080 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5081 // splitting on '|' is a bit odd, and different from makeImage.
5082 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5083 // Protect LanguageConverter markup
5084 $parameterMatches = StringUtils
::delimiterExplode(
5085 '-{', '}-', '|', $matches[3], true /* nested */
5088 foreach ( $parameterMatches as $parameterMatch ) {
5089 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5091 $paramName = $paramMap[$magicName];
5093 switch ( $paramName ) {
5094 case 'gallery-internal-alt':
5095 $alt = $this->stripAltText( $match, false );
5097 case 'gallery-internal-link':
5098 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5099 $chars = self
::EXT_LINK_URL_CLASS
;
5100 $addr = self
::EXT_LINK_ADDR
;
5101 $prots = $this->mUrlProtocols
;
5102 // check to see if link matches an absolute url, if not then it must be a wiki link.
5103 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5104 // Result of LanguageConverter::markNoConversion
5105 // invoked on an external link.
5106 $linkValue = substr( $linkValue, 4, -2 );
5108 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5110 $this->mOutput
->addExternalLink( $link );
5112 $localLinkTitle = Title
::newFromText( $linkValue );
5113 if ( $localLinkTitle !== null ) {
5114 $this->mOutput
->addLink( $localLinkTitle );
5115 $link = $localLinkTitle->getLinkURL();
5120 // Must be a handler specific parameter.
5121 if ( $handler->validateParam( $paramName, $match ) ) {
5122 $handlerOptions[$paramName] = $match;
5124 // Guess not, consider it as caption.
5125 wfDebug( "$parameterMatch failed parameter validation\n" );
5126 $label = $parameterMatch;
5132 $label = $parameterMatch;
5137 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5139 $html = $ig->toHTML();
5140 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5145 * @param MediaHandler $handler
5148 public function getImageParams( $handler ) {
5150 $handlerClass = get_class( $handler );
5154 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5155 # Initialise static lists
5156 static $internalParamNames = [
5157 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5158 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5159 'bottom', 'text-bottom' ],
5160 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5161 'upright', 'border', 'link', 'alt', 'class' ],
5163 static $internalParamMap;
5164 if ( !$internalParamMap ) {
5165 $internalParamMap = [];
5166 foreach ( $internalParamNames as $type => $names ) {
5167 foreach ( $names as $name ) {
5168 // For grep: img_left, img_right, img_center, img_none,
5169 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5170 // img_bottom, img_text_bottom,
5171 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5172 // img_border, img_link, img_alt, img_class
5173 $magicName = str_replace( '-', '_', "img_$name" );
5174 $internalParamMap[$magicName] = [ $type, $name ];
5179 # Add handler params
5180 $paramMap = $internalParamMap;
5182 $handlerParamMap = $handler->getParamMap();
5183 foreach ( $handlerParamMap as $magic => $paramName ) {
5184 $paramMap[$magic] = [ 'handler', $paramName ];
5187 $this->mImageParams
[$handlerClass] = $paramMap;
5188 $this->mImageParamsMagicArray
[$handlerClass] =
5189 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5191 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5195 * Parse image options text and use it to make an image
5197 * @param Title $title
5198 * @param string $options
5199 * @param LinkHolderArray|bool $holders
5200 * @return string HTML
5202 public function makeImage( $title, $options, $holders = false ) {
5203 # Check if the options text is of the form "options|alt text"
5205 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5206 # * left no resizing, just left align. label is used for alt= only
5207 # * right same, but right aligned
5208 # * none same, but not aligned
5209 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5210 # * center center the image
5211 # * frame Keep original image size, no magnify-button.
5212 # * framed Same as "frame"
5213 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5214 # * upright reduce width for upright images, rounded to full __0 px
5215 # * border draw a 1px border around the image
5216 # * alt Text for HTML alt attribute (defaults to empty)
5217 # * class Set a class for img node
5218 # * link Set the target of the image link. Can be external, interwiki, or local
5219 # vertical-align values (no % or length right now):
5229 # Protect LanguageConverter markup when splitting into parts
5230 $parts = StringUtils
::delimiterExplode(
5231 '-{', '}-', '|', $options, true /* allow nesting */
5234 # Give extensions a chance to select the file revision for us
5237 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5238 [ $this, $title, &$options, &$descQuery ] );
5239 # Fetch and register the file (file title may be different via hooks)
5240 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5243 $handler = $file ?
$file->getHandler() : false;
5245 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5248 $this->addTrackingCategory( 'broken-file-category' );
5251 # Process the input parameters
5253 $params = [ 'frame' => [], 'handler' => [],
5254 'horizAlign' => [], 'vertAlign' => [] ];
5255 $seenformat = false;
5256 foreach ( $parts as $part ) {
5257 $part = trim( $part );
5258 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5260 if ( isset( $paramMap[$magicName] ) ) {
5261 list( $type, $paramName ) = $paramMap[$magicName];
5263 # Special case; width and height come in one variable together
5264 if ( $type === 'handler' && $paramName === 'width' ) {
5265 $parsedWidthParam = self
::parseWidthParam( $value );
5266 if ( isset( $parsedWidthParam['width'] ) ) {
5267 $width = $parsedWidthParam['width'];
5268 if ( $handler->validateParam( 'width', $width ) ) {
5269 $params[$type]['width'] = $width;
5273 if ( isset( $parsedWidthParam['height'] ) ) {
5274 $height = $parsedWidthParam['height'];
5275 if ( $handler->validateParam( 'height', $height ) ) {
5276 $params[$type]['height'] = $height;
5280 # else no validation -- T15436
5282 if ( $type === 'handler' ) {
5283 # Validate handler parameter
5284 $validated = $handler->validateParam( $paramName, $value );
5286 # Validate internal parameters
5287 switch ( $paramName ) {
5291 # @todo FIXME: Possibly check validity here for
5292 # manualthumb? downstream behavior seems odd with
5293 # missing manual thumbs.
5295 $value = $this->stripAltText( $value, $holders );
5298 $chars = self
::EXT_LINK_URL_CLASS
;
5299 $addr = self
::EXT_LINK_ADDR
;
5300 $prots = $this->mUrlProtocols
;
5301 if ( $value === '' ) {
5302 $paramName = 'no-link';
5305 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5306 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5307 $paramName = 'link-url';
5308 $this->mOutput
->addExternalLink( $value );
5309 if ( $this->mOptions
->getExternalLinkTarget() ) {
5310 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5315 $linkTitle = Title
::newFromText( $value );
5317 $paramName = 'link-title';
5318 $value = $linkTitle;
5319 $this->mOutput
->addLink( $linkTitle );
5327 // use first appearing option, discard others.
5328 $validated = !$seenformat;
5332 # Most other things appear to be empty or numeric...
5333 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5338 $params[$type][$paramName] = $value;
5342 if ( !$validated ) {
5347 # Process alignment parameters
5348 if ( $params['horizAlign'] ) {
5349 $params['frame']['align'] = key( $params['horizAlign'] );
5351 if ( $params['vertAlign'] ) {
5352 $params['frame']['valign'] = key( $params['vertAlign'] );
5355 $params['frame']['caption'] = $caption;
5357 # Will the image be presented in a frame, with the caption below?
5358 $imageIsFramed = isset( $params['frame']['frame'] )
5359 ||
isset( $params['frame']['framed'] )
5360 ||
isset( $params['frame']['thumbnail'] )
5361 ||
isset( $params['frame']['manualthumb'] );
5363 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5364 # came to also set the caption, ordinary text after the image -- which
5365 # makes no sense, because that just repeats the text multiple times in
5366 # screen readers. It *also* came to set the title attribute.
5367 # Now that we have an alt attribute, we should not set the alt text to
5368 # equal the caption: that's worse than useless, it just repeats the
5369 # text. This is the framed/thumbnail case. If there's no caption, we
5370 # use the unnamed parameter for alt text as well, just for the time be-
5371 # ing, if the unnamed param is set and the alt param is not.
5372 # For the future, we need to figure out if we want to tweak this more,
5373 # e.g., introducing a title= parameter for the title; ignoring the un-
5374 # named parameter entirely for images without a caption; adding an ex-
5375 # plicit caption= parameter and preserving the old magic unnamed para-
5377 if ( $imageIsFramed ) { # Framed image
5378 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5379 # No caption or alt text, add the filename as the alt text so
5380 # that screen readers at least get some description of the image
5381 $params['frame']['alt'] = $title->getText();
5383 # Do not set $params['frame']['title'] because tooltips don't make sense
5385 } else { # Inline image
5386 if ( !isset( $params['frame']['alt'] ) ) {
5387 # No alt text, use the "caption" for the alt text
5388 if ( $caption !== '' ) {
5389 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5391 # No caption, fall back to using the filename for the
5393 $params['frame']['alt'] = $title->getText();
5396 # Use the "caption" for the tooltip text
5397 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5400 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5402 # Linker does the rest
5403 $time = $options['time'] ??
false;
5404 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5405 $time, $descQuery, $this->mOptions
->getThumbSize() );
5407 # Give the handler a chance to modify the parser object
5409 $handler->parserTransformHook( $this, $file );
5416 * @param string $caption
5417 * @param LinkHolderArray|bool $holders
5418 * @return mixed|string
5420 protected function stripAltText( $caption, $holders ) {
5421 # Strip bad stuff out of the title (tooltip). We can't just use
5422 # replaceLinkHoldersText() here, because if this function is called
5423 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5425 $tooltip = $holders->replaceText( $caption );
5427 $tooltip = $this->replaceLinkHoldersText( $caption );
5430 # make sure there are no placeholders in thumbnail attributes
5431 # that are later expanded to html- so expand them now and
5433 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5434 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5440 * Set a flag in the output object indicating that the content is dynamic and
5441 * shouldn't be cached.
5442 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5444 public function disableCache() {
5445 wfDebug( "Parser output marked as uncacheable.\n" );
5446 if ( !$this->mOutput
) {
5447 throw new MWException( __METHOD__
.
5448 " can only be called when actually parsing something" );
5450 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5454 * Callback from the Sanitizer for expanding items found in HTML attribute
5455 * values, so they can be safely tested and escaped.
5457 * @param string &$text
5458 * @param bool|PPFrame $frame
5461 public function attributeStripCallback( &$text, $frame = false ) {
5462 $text = $this->replaceVariables( $text, $frame );
5463 $text = $this->mStripState
->unstripBoth( $text );
5472 public function getTags() {
5474 array_keys( $this->mTransparentTagHooks
),
5475 array_keys( $this->mTagHooks
),
5476 array_keys( $this->mFunctionTagHooks
)
5481 * Replace transparent tags in $text with the values given by the callbacks.
5483 * Transparent tag hooks are like regular XML-style tag hooks, except they
5484 * operate late in the transformation sequence, on HTML instead of wikitext.
5486 * @param string $text
5490 public function replaceTransparentTags( $text ) {
5492 $elements = array_keys( $this->mTransparentTagHooks
);
5493 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5496 foreach ( $matches as $marker => $data ) {
5497 list( $element, $content, $params, $tag ) = $data;
5498 $tagName = strtolower( $element );
5499 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5500 $output = call_user_func_array(
5501 $this->mTransparentTagHooks
[$tagName],
5502 [ $content, $params, $this ]
5507 $replacements[$marker] = $output;
5509 return strtr( $text, $replacements );
5513 * Break wikitext input into sections, and either pull or replace
5514 * some particular section's text.
5516 * External callers should use the getSection and replaceSection methods.
5518 * @param string $text Page wikitext
5519 * @param string|int $sectionId A section identifier string of the form:
5520 * "<flag1> - <flag2> - ... - <section number>"
5522 * Currently the only recognised flag is "T", which means the target section number
5523 * was derived during a template inclusion parse, in other words this is a template
5524 * section edit link. If no flags are given, it was an ordinary section edit link.
5525 * This flag is required to avoid a section numbering mismatch when a section is
5526 * enclosed by "<includeonly>" (T8563).
5528 * The section number 0 pulls the text before the first heading; other numbers will
5529 * pull the given section along with its lower-level subsections. If the section is
5530 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5532 * Section 0 is always considered to exist, even if it only contains the empty
5533 * string. If $text is the empty string and section 0 is replaced, $newText is
5536 * @param string $mode One of "get" or "replace"
5537 * @param string $newText Replacement text for section data.
5538 * @return string For "get", the extracted section text.
5539 * for "replace", the whole page with the section replaced.
5541 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5542 global $wgTitle; # not generally used but removes an ugly failure mode
5544 $magicScopeVariable = $this->lock();
5545 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5547 $frame = $this->getPreprocessor()->newFrame();
5549 # Process section extraction flags
5551 $sectionParts = explode( '-', $sectionId );
5552 $sectionIndex = array_pop( $sectionParts );
5553 foreach ( $sectionParts as $part ) {
5554 if ( $part === 'T' ) {
5555 $flags |
= self
::PTD_FOR_INCLUSION
;
5559 # Check for empty input
5560 if ( strval( $text ) === '' ) {
5561 # Only sections 0 and T-0 exist in an empty document
5562 if ( $sectionIndex == 0 ) {
5563 if ( $mode === 'get' ) {
5569 if ( $mode === 'get' ) {
5577 # Preprocess the text
5578 $root = $this->preprocessToDom( $text, $flags );
5580 # <h> nodes indicate section breaks
5581 # They can only occur at the top level, so we can find them by iterating the root's children
5582 $node = $root->getFirstChild();
5584 # Find the target section
5585 if ( $sectionIndex == 0 ) {
5586 # Section zero doesn't nest, level=big
5587 $targetLevel = 1000;
5590 if ( $node->getName() === 'h' ) {
5591 $bits = $node->splitHeading();
5592 if ( $bits['i'] == $sectionIndex ) {
5593 $targetLevel = $bits['level'];
5597 if ( $mode === 'replace' ) {
5598 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5600 $node = $node->getNextSibling();
5606 if ( $mode === 'get' ) {
5613 # Find the end of the section, including nested sections
5615 if ( $node->getName() === 'h' ) {
5616 $bits = $node->splitHeading();
5617 $curLevel = $bits['level'];
5618 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5622 if ( $mode === 'get' ) {
5623 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5625 $node = $node->getNextSibling();
5628 # Write out the remainder (in replace mode only)
5629 if ( $mode === 'replace' ) {
5630 # Output the replacement text
5631 # Add two newlines on -- trailing whitespace in $newText is conventionally
5632 # stripped by the editor, so we need both newlines to restore the paragraph gap
5633 # Only add trailing whitespace if there is newText
5634 if ( $newText != "" ) {
5635 $outText .= $newText . "\n\n";
5639 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5640 $node = $node->getNextSibling();
5644 if ( is_string( $outText ) ) {
5645 # Re-insert stripped tags
5646 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5653 * This function returns the text of a section, specified by a number ($section).
5654 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5655 * the first section before any such heading (section 0).
5657 * If a section contains subsections, these are also returned.
5659 * @param string $text Text to look in
5660 * @param string|int $sectionId Section identifier as a number or string
5661 * (e.g. 0, 1 or 'T-1').
5662 * @param string $defaultText Default to return if section is not found
5664 * @return string Text of the requested section
5666 public function getSection( $text, $sectionId, $defaultText = '' ) {
5667 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5671 * This function returns $oldtext after the content of the section
5672 * specified by $section has been replaced with $text. If the target
5673 * section does not exist, $oldtext is returned unchanged.
5675 * @param string $oldText Former text of the article
5676 * @param string|int $sectionId Section identifier as a number or string
5677 * (e.g. 0, 1 or 'T-1').
5678 * @param string $newText Replacing text
5680 * @return string Modified text
5682 public function replaceSection( $oldText, $sectionId, $newText ) {
5683 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5687 * Get the ID of the revision we are parsing
5691 public function getRevisionId() {
5692 return $this->mRevisionId
;
5696 * Get the revision object for $this->mRevisionId
5698 * @return Revision|null Either a Revision object or null
5699 * @since 1.23 (public since 1.23)
5701 public function getRevisionObject() {
5702 if ( !is_null( $this->mRevisionObject
) ) {
5703 return $this->mRevisionObject
;
5705 if ( is_null( $this->mRevisionId
) ) {
5709 $rev = call_user_func(
5710 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5713 # If the parse is for a new revision, then the callback should have
5714 # already been set to force the object and should match mRevisionId.
5715 # If not, try to fetch by mRevisionId for sanity.
5716 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5717 $rev = Revision
::newFromId( $this->mRevisionId
);
5720 $this->mRevisionObject
= $rev;
5722 return $this->mRevisionObject
;
5726 * Get the timestamp associated with the current revision, adjusted for
5727 * the default server-local timestamp
5730 public function getRevisionTimestamp() {
5731 if ( is_null( $this->mRevisionTimestamp
) ) {
5734 $revObject = $this->getRevisionObject();
5735 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5737 # The cryptic '' timezone parameter tells to use the site-default
5738 # timezone offset instead of the user settings.
5739 # Since this value will be saved into the parser cache, served
5740 # to other users, and potentially even used inside links and such,
5741 # it needs to be consistent for all visitors.
5742 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5745 return $this->mRevisionTimestamp
;
5749 * Get the name of the user that edited the last revision
5751 * @return string User name
5753 public function getRevisionUser() {
5754 if ( is_null( $this->mRevisionUser
) ) {
5755 $revObject = $this->getRevisionObject();
5757 # if this template is subst: the revision id will be blank,
5758 # so just use the current user's name
5760 $this->mRevisionUser
= $revObject->getUserText();
5761 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5762 $this->mRevisionUser
= $this->getUser()->getName();
5765 return $this->mRevisionUser
;
5769 * Get the size of the revision
5771 * @return int|null Revision size
5773 public function getRevisionSize() {
5774 if ( is_null( $this->mRevisionSize
) ) {
5775 $revObject = $this->getRevisionObject();
5777 # if this variable is subst: the revision id will be blank,
5778 # so just use the parser input size, because the own substituation
5779 # will change the size.
5781 $this->mRevisionSize
= $revObject->getSize();
5783 $this->mRevisionSize
= $this->mInputSize
;
5786 return $this->mRevisionSize
;
5790 * Mutator for $mDefaultSort
5792 * @param string $sort New value
5794 public function setDefaultSort( $sort ) {
5795 $this->mDefaultSort
= $sort;
5796 $this->mOutput
->setProperty( 'defaultsort', $sort );
5800 * Accessor for $mDefaultSort
5801 * Will use the empty string if none is set.
5803 * This value is treated as a prefix, so the
5804 * empty string is equivalent to sorting by
5809 public function getDefaultSort() {
5810 if ( $this->mDefaultSort
!== false ) {
5811 return $this->mDefaultSort
;
5818 * Accessor for $mDefaultSort
5819 * Unlike getDefaultSort(), will return false if none is set
5821 * @return string|bool
5823 public function getCustomDefaultSort() {
5824 return $this->mDefaultSort
;
5827 private static function getSectionNameFromStrippedText( $text ) {
5828 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5829 $text = Sanitizer
::decodeCharReferences( $text );
5830 $text = self
::normalizeSectionName( $text );
5834 private static function makeAnchor( $sectionName ) {
5835 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5838 private static function makeLegacyAnchor( $sectionName ) {
5839 global $wgFragmentMode;
5840 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5841 // ForAttribute() and ForLink() are the same for legacy encoding
5842 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5844 $id = Sanitizer
::escapeIdForLink( $sectionName );
5851 * Try to guess the section anchor name based on a wikitext fragment
5852 * presumably extracted from a heading, for example "Header" from
5855 * @param string $text
5856 * @return string Anchor (starting with '#')
5858 public function guessSectionNameFromWikiText( $text ) {
5859 # Strip out wikitext links(they break the anchor)
5860 $text = $this->stripSectionName( $text );
5861 $sectionName = self
::getSectionNameFromStrippedText( $text );
5862 return self
::makeAnchor( $sectionName );
5866 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5867 * instead, if possible. For use in redirects, since various versions
5868 * of Microsoft browsers interpret Location: headers as something other
5869 * than UTF-8, resulting in breakage.
5871 * @param string $text The section name
5872 * @return string Anchor (starting with '#')
5874 public function guessLegacySectionNameFromWikiText( $text ) {
5875 # Strip out wikitext links(they break the anchor)
5876 $text = $this->stripSectionName( $text );
5877 $sectionName = self
::getSectionNameFromStrippedText( $text );
5878 return self
::makeLegacyAnchor( $sectionName );
5882 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5883 * @param string $text Section name (plain text)
5884 * @return string Anchor (starting with '#')
5886 public static function guessSectionNameFromStrippedText( $text ) {
5887 $sectionName = self
::getSectionNameFromStrippedText( $text );
5888 return self
::makeAnchor( $sectionName );
5892 * Apply the same normalization as code making links to this section would
5894 * @param string $text
5897 private static function normalizeSectionName( $text ) {
5898 # T90902: ensure the same normalization is applied for IDs as to links
5899 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5902 $parts = $titleParser->splitTitleString( "#$text" );
5903 } catch ( MalformedTitleException
$ex ) {
5906 return $parts['fragment'];
5910 * Strips a text string of wikitext for use in a section anchor
5912 * Accepts a text string and then removes all wikitext from the
5913 * string and leaves only the resultant text (i.e. the result of
5914 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5915 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5916 * to create valid section anchors by mimicing the output of the
5917 * parser when headings are parsed.
5919 * @param string $text Text string to be stripped of wikitext
5920 * for use in a Section anchor
5921 * @return string Filtered text string
5923 public function stripSectionName( $text ) {
5924 # Strip internal link markup
5925 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5926 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5928 # Strip external link markup
5929 # @todo FIXME: Not tolerant to blank link text
5930 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5931 # on how many empty links there are on the page - need to figure that out.
5932 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5934 # Parse wikitext quotes (italics & bold)
5935 $text = $this->doQuotes( $text );
5938 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5943 * strip/replaceVariables/unstrip for preprocessor regression testing
5945 * @param string $text
5946 * @param Title $title
5947 * @param ParserOptions $options
5948 * @param int $outputType
5952 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5953 $outputType = self
::OT_HTML
5955 $magicScopeVariable = $this->lock();
5956 $this->startParse( $title, $options, $outputType, true );
5958 $text = $this->replaceVariables( $text );
5959 $text = $this->mStripState
->unstripBoth( $text );
5960 $text = Sanitizer
::removeHTMLtags( $text );
5965 * @param string $text
5966 * @param Title $title
5967 * @param ParserOptions $options
5970 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5971 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5975 * @param string $text
5976 * @param Title $title
5977 * @param ParserOptions $options
5980 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5981 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5985 * Call a callback function on all regions of the given text that are not
5986 * inside strip markers, and replace those regions with the return value
5987 * of the callback. For example, with input:
5991 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5992 * two strings will be replaced with the value returned by the callback in
5996 * @param callable $callback
6000 public function markerSkipCallback( $s, $callback ) {
6003 while ( $i < strlen( $s ) ) {
6004 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6005 if ( $markerStart === false ) {
6006 $out .= call_user_func( $callback, substr( $s, $i ) );
6009 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6010 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6011 if ( $markerEnd === false ) {
6012 $out .= substr( $s, $markerStart );
6015 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6016 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6025 * Remove any strip markers found in the given text.
6027 * @param string $text
6030 public function killMarkers( $text ) {
6031 return $this->mStripState
->killMarkers( $text );
6035 * Save the parser state required to convert the given half-parsed text to
6036 * HTML. "Half-parsed" in this context means the output of
6037 * recursiveTagParse() or internalParse(). This output has strip markers
6038 * from replaceVariables (extensionSubstitution() etc.), and link
6039 * placeholders from replaceLinkHolders().
6041 * Returns an array which can be serialized and stored persistently. This
6042 * array can later be loaded into another parser instance with
6043 * unserializeHalfParsedText(). The text can then be safely incorporated into
6044 * the return value of a parser hook.
6046 * @deprecated since 1.31
6047 * @param string $text
6051 public function serializeHalfParsedText( $text ) {
6052 wfDeprecated( __METHOD__
, '1.31' );
6055 'version' => self
::HALF_PARSED_VERSION
,
6056 'stripState' => $this->mStripState
->getSubState( $text ),
6057 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6063 * Load the parser state given in the $data array, which is assumed to
6064 * have been generated by serializeHalfParsedText(). The text contents is
6065 * extracted from the array, and its markers are transformed into markers
6066 * appropriate for the current Parser instance. This transformed text is
6067 * returned, and can be safely included in the return value of a parser
6070 * If the $data array has been stored persistently, the caller should first
6071 * check whether it is still valid, by calling isValidHalfParsedText().
6073 * @deprecated since 1.31
6074 * @param array $data Serialized data
6075 * @throws MWException
6078 public function unserializeHalfParsedText( $data ) {
6079 wfDeprecated( __METHOD__
, '1.31' );
6080 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6081 throw new MWException( __METHOD__
. ': invalid version' );
6084 # First, extract the strip state.
6085 $texts = [ $data['text'] ];
6086 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6088 # Now renumber links
6089 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6091 # Should be good to go.
6096 * Returns true if the given array, presumed to be generated by
6097 * serializeHalfParsedText(), is compatible with the current version of the
6100 * @deprecated since 1.31
6101 * @param array $data
6105 public function isValidHalfParsedText( $data ) {
6106 wfDeprecated( __METHOD__
, '1.31' );
6107 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6111 * Parsed a width param of imagelink like 300px or 200x300px
6113 * @param string $value
6114 * @param bool $parseHeight
6119 public static function parseWidthParam( $value, $parseHeight = true ) {
6120 $parsedWidthParam = [];
6121 if ( $value === '' ) {
6122 return $parsedWidthParam;
6125 # (T15500) In both cases (width/height and width only),
6126 # permit trailing "px" for backward compatibility.
6127 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6128 $width = intval( $m[1] );
6129 $height = intval( $m[2] );
6130 $parsedWidthParam['width'] = $width;
6131 $parsedWidthParam['height'] = $height;
6132 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6133 $width = intval( $value );
6134 $parsedWidthParam['width'] = $width;
6136 return $parsedWidthParam;
6140 * Lock the current instance of the parser.
6142 * This is meant to stop someone from calling the parser
6143 * recursively and messing up all the strip state.
6145 * @throws MWException If parser is in a parse
6146 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6148 protected function lock() {
6149 if ( $this->mInParse
) {
6150 throw new MWException( "Parser state cleared while parsing. "
6151 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6154 // Save the backtrace when locking, so that if some code tries locking again,
6155 // we can print the lock owner's backtrace for easier debugging
6157 $this->mInParse
= $e->getTraceAsString();
6159 $recursiveCheck = new ScopedCallback( function () {
6160 $this->mInParse
= false;
6163 return $recursiveCheck;
6167 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6169 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6170 * or if there is more than one <p/> tag in the input HTML.
6172 * @param string $html
6176 public static function stripOuterParagraph( $html ) {
6178 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6179 if ( strpos( $m[1], '</p>' ) === false ) {
6188 * Return this parser if it is not doing anything, otherwise
6189 * get a fresh parser. You can use this method by doing
6190 * $myParser = $wgParser->getFreshParser(), or more simply
6191 * $wgParser->getFreshParser()->parse( ... );
6192 * if you're unsure if $wgParser is safe to use.
6195 * @return Parser A parser object that is not parsing anything
6197 public function getFreshParser() {
6198 global $wgParserConf;
6199 if ( $this->mInParse
) {
6200 return new $wgParserConf['class']( $wgParserConf );
6207 * Set's up the PHP implementation of OOUI for use in this request
6208 * and instructs OutputPage to enable OOUI for itself.
6212 public function enableOOUI() {
6213 OutputPage
::setupOOUI();
6214 $this->mOutput
->setEnableOOUI( true );