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;
266 public function __construct( $conf = [] ) {
267 $this->mConf
= $conf;
268 $this->mUrlProtocols
= wfUrlProtocols();
269 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
270 self
::EXT_LINK_ADDR
.
271 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
272 if ( isset( $conf['preprocessorClass'] ) ) {
273 $this->mPreprocessorClass
= $conf['preprocessorClass'];
274 } elseif ( defined( 'HPHP_VERSION' ) ) {
275 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
276 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
277 } elseif ( extension_loaded( 'domxml' ) ) {
278 # PECL extension that conflicts with the core DOM extension (T15770)
279 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
280 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
281 } elseif ( extension_loaded( 'dom' ) ) {
282 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
284 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
286 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
290 * Reduce memory usage to reduce the impact of circular references
292 public function __destruct() {
293 if ( isset( $this->mLinkHolders
) ) {
294 unset( $this->mLinkHolders
);
296 foreach ( $this as $name => $value ) {
297 unset( $this->$name );
302 * Allow extensions to clean up when the parser is cloned
304 public function __clone() {
305 $this->mInParse
= false;
307 // T58226: When you create a reference "to" an object field, that
308 // makes the object field itself be a reference too (until the other
309 // reference goes out of scope). When cloning, any field that's a
310 // reference is copied as a reference in the new object. Both of these
311 // are defined PHP5 behaviors, as inconvenient as it is for us when old
312 // hooks from PHP4 days are passing fields by reference.
313 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
314 // Make a non-reference copy of the field, then rebind the field to
315 // reference the new copy.
321 Hooks
::run( 'ParserCloned', [ $this ] );
325 * Do various kinds of initialisation on the first call of the parser
327 public function firstCallInit() {
328 if ( !$this->mFirstCall
) {
331 $this->mFirstCall
= false;
333 CoreParserFunctions
::register( $this );
334 CoreTagHooks
::register( $this );
335 $this->initialiseVariables();
337 // Avoid PHP 7.1 warning from passing $this by reference
339 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
347 public function clearState() {
348 if ( $this->mFirstCall
) {
349 $this->firstCallInit();
351 $this->mOutput
= new ParserOutput
;
352 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
353 $this->mAutonumber
= 0;
354 $this->mIncludeCount
= [];
355 $this->mLinkHolders
= new LinkHolderArray( $this );
357 $this->mRevisionObject
= $this->mRevisionTimestamp
=
358 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
359 $this->mVarCache
= [];
361 $this->mLangLinkLanguages
= [];
362 $this->currentRevisionCache
= null;
364 $this->mStripState
= new StripState( $this );
366 # Clear these on every parse, T6549
367 $this->mTplRedirCache
= $this->mTplDomCache
= [];
369 $this->mShowToc
= true;
370 $this->mForceTocPosition
= false;
371 $this->mIncludeSizes
= [
375 $this->mPPNodeCount
= 0;
376 $this->mGeneratedPPNodeCount
= 0;
377 $this->mHighestExpansionDepth
= 0;
378 $this->mDefaultSort
= false;
379 $this->mHeadings
= [];
380 $this->mDoubleUnderscores
= [];
381 $this->mExpensiveFunctionCount
= 0;
384 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
385 $this->mPreprocessor
= null;
388 $this->mProfiler
= new SectionProfiler();
390 // Avoid PHP 7.1 warning from passing $this by reference
392 Hooks
::run( 'ParserClearState', [ &$parser ] );
396 * Convert wikitext to HTML
397 * Do not call this function recursively.
399 * @param string $text Text we want to parse
400 * @param Title $title
401 * @param ParserOptions $options
402 * @param bool $linestart
403 * @param bool $clearState
404 * @param int $revid Number to pass in {{REVISIONID}}
405 * @return ParserOutput A ParserOutput
407 public function parse(
408 $text, Title
$title, ParserOptions
$options,
409 $linestart = true, $clearState = true, $revid = null
412 // We use U+007F DELETE to construct strip markers, so we have to make
413 // sure that this character does not occur in the input text.
414 $text = strtr( $text, "\x7f", "?" );
415 $magicScopeVariable = $this->lock();
417 // Strip U+0000 NULL (T159174)
418 $text = str_replace( "\000", '', $text );
420 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
422 $this->currentRevisionCache
= null;
423 $this->mInputSize
= strlen( $text );
424 if ( $this->mOptions
->getEnableLimitReport() ) {
425 $this->mOutput
->resetParseStartTime();
428 $oldRevisionId = $this->mRevisionId
;
429 $oldRevisionObject = $this->mRevisionObject
;
430 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
431 $oldRevisionUser = $this->mRevisionUser
;
432 $oldRevisionSize = $this->mRevisionSize
;
433 if ( $revid !== null ) {
434 $this->mRevisionId
= $revid;
435 $this->mRevisionObject
= null;
436 $this->mRevisionTimestamp
= null;
437 $this->mRevisionUser
= null;
438 $this->mRevisionSize
= null;
441 // Avoid PHP 7.1 warning from passing $this by reference
443 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
445 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
446 $text = $this->internalParse( $text );
447 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
449 $text = $this->internalParseHalfParsed( $text, true, $linestart );
452 * A converted title will be provided in the output object if title and
453 * content conversion are enabled, the article text does not contain
454 * a conversion-suppressing double-underscore tag, and no
455 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
456 * automatic link conversion.
458 if ( !( $options->getDisableTitleConversion()
459 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
460 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
461 ||
$this->mOutput
->getDisplayTitle() !== false )
463 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
464 if ( $convruletitle ) {
465 $this->mOutput
->setTitleText( $convruletitle );
467 $titleText = $this->getTargetLanguage()->convertTitle( $title );
468 $this->mOutput
->setTitleText( $titleText );
472 # Compute runtime adaptive expiry if set
473 $this->mOutput
->finalizeAdaptiveCacheExpiry();
475 # Warn if too many heavyweight parser functions were used
476 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
477 $this->limitationWarn( 'expensive-parserfunction',
478 $this->mExpensiveFunctionCount
,
479 $this->mOptions
->getExpensiveParserFunctionLimit()
483 # Information on limits, for the benefit of users who try to skirt them
484 if ( $this->mOptions
->getEnableLimitReport() ) {
485 $text .= $this->makeLimitReport();
488 # Wrap non-interface parser output in a <div> so it can be targeted
490 $class = $this->mOptions
->getWrapOutputClass();
491 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
492 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
495 $this->mOutput
->setText( $text );
497 $this->mRevisionId
= $oldRevisionId;
498 $this->mRevisionObject
= $oldRevisionObject;
499 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
500 $this->mRevisionUser
= $oldRevisionUser;
501 $this->mRevisionSize
= $oldRevisionSize;
502 $this->mInputSize
= false;
503 $this->currentRevisionCache
= null;
505 return $this->mOutput
;
509 * Set the limit report data in the current ParserOutput, and return the
510 * limit report HTML comment.
514 protected function makeLimitReport() {
515 global $wgShowHostnames;
517 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
519 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
520 if ( $cpuTime !== null ) {
521 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
522 sprintf( "%.3f", $cpuTime )
526 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
527 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
528 sprintf( "%.3f", $wallTime )
531 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
532 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
534 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
535 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
537 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
538 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
540 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
541 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
543 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
544 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
546 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
547 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
550 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
551 $this->mOutput
->setLimitReportData( $key, $value );
554 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
556 $limitReport = "NewPP limit report\n";
557 if ( $wgShowHostnames ) {
558 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
560 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
561 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
562 $limitReport .= 'Dynamic content: ' .
563 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
566 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
567 if ( Hooks
::run( 'ParserLimitReportFormat',
568 [ $key, &$value, &$limitReport, false, false ]
570 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
571 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
572 ->inLanguage( 'en' )->useDatabase( false );
573 if ( !$valueMsg->exists() ) {
574 $valueMsg = new RawMessage( '$1' );
576 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
577 $valueMsg->params( $value );
578 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
582 // Since we're not really outputting HTML, decode the entities and
583 // then re-encode the things that need hiding inside HTML comments.
584 $limitReport = htmlspecialchars_decode( $limitReport );
585 // Run deprecated hook
586 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
588 // Sanitize for comment. Note '‐' in the replacement is U+2010,
589 // which looks much like the problematic '-'.
590 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
591 $text = "\n<!-- \n$limitReport-->\n";
593 // Add on template profiling data in human/machine readable way
594 $dataByFunc = $this->mProfiler
->getFunctionStats();
595 uasort( $dataByFunc, function ( $a, $b ) {
596 return $b['real'] <=> $a['real']; // descending order
599 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
600 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
601 $item['%real'], $item['real'], $item['calls'],
602 htmlspecialchars( $item['name'] ) );
604 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
605 $text .= implode( "\n", $profileReport ) . "\n-->\n";
607 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
609 // Add other cache related metadata
610 if ( $wgShowHostnames ) {
611 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
613 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
614 $this->mOutput
->getCacheTime() );
615 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
616 $this->mOutput
->getCacheExpiry() );
617 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
618 $this->mOutput
->hasDynamicContent() );
620 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
621 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
622 $this->mTitle
->getPrefixedDBkey() );
628 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
629 * can be called from an extension tag hook.
631 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
632 * instead, which means that lists and links have not been fully parsed yet,
633 * and strip markers are still present.
635 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
637 * Use this function if you're a parser tag hook and you want to parse
638 * wikitext before or after applying additional transformations, and you
639 * intend to *return the result as hook output*, which will cause it to go
640 * through the rest of parsing process automatically.
642 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
643 * $text are not expanded
645 * @param string $text Text extension wants to have parsed
646 * @param bool|PPFrame $frame The frame to use for expanding any template variables
647 * @return string UNSAFE half-parsed HTML
649 public function recursiveTagParse( $text, $frame = false ) {
650 // Avoid PHP 7.1 warning from passing $this by reference
652 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
653 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
654 $text = $this->internalParse( $text, false, $frame );
659 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
660 * point can be called from an extension tag hook.
662 * The output of this function is fully-parsed HTML that is safe for output.
663 * If you're a parser tag hook, you might want to use recursiveTagParse()
666 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
667 * $text are not expanded
671 * @param string $text Text extension wants to have parsed
672 * @param bool|PPFrame $frame The frame to use for expanding any template variables
673 * @return string Fully parsed HTML
675 public function recursiveTagParseFully( $text, $frame = false ) {
676 $text = $this->recursiveTagParse( $text, $frame );
677 $text = $this->internalParseHalfParsed( $text, false );
682 * Expand templates and variables in the text, producing valid, static wikitext.
683 * Also removes comments.
684 * Do not call this function recursively.
685 * @param string $text
686 * @param Title $title
687 * @param ParserOptions $options
688 * @param int|null $revid
689 * @param bool|PPFrame $frame
690 * @return mixed|string
692 public function preprocess( $text, Title
$title = null,
693 ParserOptions
$options, $revid = null, $frame = false
695 $magicScopeVariable = $this->lock();
696 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
697 if ( $revid !== null ) {
698 $this->mRevisionId
= $revid;
700 // Avoid PHP 7.1 warning from passing $this by reference
702 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
703 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
704 $text = $this->replaceVariables( $text, $frame );
705 $text = $this->mStripState
->unstripBoth( $text );
710 * Recursive parser entry point that can be called from an extension tag
713 * @param string $text Text to be expanded
714 * @param bool|PPFrame $frame The frame to use for expanding any template variables
718 public function recursivePreprocess( $text, $frame = false ) {
719 $text = $this->replaceVariables( $text, $frame );
720 $text = $this->mStripState
->unstripBoth( $text );
725 * Process the wikitext for the "?preload=" feature. (T7210)
727 * "<noinclude>", "<includeonly>" etc. are parsed as for template
728 * transclusion, comments, templates, arguments, tags hooks and parser
729 * functions are untouched.
731 * @param string $text
732 * @param Title $title
733 * @param ParserOptions $options
734 * @param array $params
737 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
738 $msg = new RawMessage( $text );
739 $text = $msg->params( $params )->plain();
741 # Parser (re)initialisation
742 $magicScopeVariable = $this->lock();
743 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
745 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
746 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
747 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
748 $text = $this->mStripState
->unstripBoth( $text );
753 * Set the current user.
754 * Should only be used when doing pre-save transform.
756 * @param User|null $user User object or null (to reset)
758 public function setUser( $user ) {
759 $this->mUser
= $user;
763 * Set the context title
767 public function setTitle( $t ) {
769 $t = Title
::newFromText( 'NO TITLE' );
772 if ( $t->hasFragment() ) {
773 # Strip the fragment to avoid various odd effects
774 $this->mTitle
= $t->createFragmentTarget( '' );
781 * Accessor for the Title object
785 public function getTitle() {
786 return $this->mTitle
;
790 * Accessor/mutator for the Title object
792 * @param Title $x Title object or null to just get the current one
795 public function Title( $x = null ) {
796 return wfSetVar( $this->mTitle
, $x );
800 * Set the output type
802 * @param int $ot New value
804 public function setOutputType( $ot ) {
805 $this->mOutputType
= $ot;
808 'html' => $ot == self
::OT_HTML
,
809 'wiki' => $ot == self
::OT_WIKI
,
810 'pre' => $ot == self
::OT_PREPROCESS
,
811 'plain' => $ot == self
::OT_PLAIN
,
816 * Accessor/mutator for the output type
818 * @param int|null $x New value or null to just get the current one
821 public function OutputType( $x = null ) {
822 return wfSetVar( $this->mOutputType
, $x );
826 * Get the ParserOutput object
828 * @return ParserOutput
830 public function getOutput() {
831 return $this->mOutput
;
835 * Get the ParserOptions object
837 * @return ParserOptions
839 public function getOptions() {
840 return $this->mOptions
;
844 * Accessor/mutator for the ParserOptions object
846 * @param ParserOptions $x New value or null to just get the current one
847 * @return ParserOptions Current ParserOptions object
849 public function Options( $x = null ) {
850 return wfSetVar( $this->mOptions
, $x );
856 public function nextLinkID() {
857 return $this->mLinkID++
;
863 public function setLinkID( $id ) {
864 $this->mLinkID
= $id;
868 * Get a language object for use in parser functions such as {{FORMATNUM:}}
871 public function getFunctionLang() {
872 return $this->getTargetLanguage();
876 * Get the target language for the content being parsed. This is usually the
877 * language that the content is in.
881 * @throws MWException
884 public function getTargetLanguage() {
885 $target = $this->mOptions
->getTargetLanguage();
887 if ( $target !== null ) {
889 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
890 return $this->mOptions
->getUserLangObj();
891 } elseif ( is_null( $this->mTitle
) ) {
892 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
895 return $this->mTitle
->getPageLanguage();
899 * Get the language object for language conversion
900 * @deprecated since 1.32, just use getTargetLanguage()
901 * @return Language|null
903 public function getConverterLanguage() {
904 return $this->getTargetLanguage();
908 * Get a User object either from $this->mUser, if set, or from the
909 * ParserOptions object otherwise
913 public function getUser() {
914 if ( !is_null( $this->mUser
) ) {
917 return $this->mOptions
->getUser();
921 * Get a preprocessor object
923 * @return Preprocessor
925 public function getPreprocessor() {
926 if ( !isset( $this->mPreprocessor
) ) {
927 $class = $this->mPreprocessorClass
;
928 $this->mPreprocessor
= new $class( $this );
930 return $this->mPreprocessor
;
934 * Get a LinkRenderer instance to make links with
937 * @return LinkRenderer
939 public function getLinkRenderer() {
940 if ( !$this->mLinkRenderer
) {
941 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
942 ->getLinkRendererFactory()->create();
943 $this->mLinkRenderer
->setStubThreshold(
944 $this->getOptions()->getStubThreshold()
948 return $this->mLinkRenderer
;
952 * Replaces all occurrences of HTML-style comments and the given tags
953 * in the text with a random marker and returns the next text. The output
954 * parameter $matches will be an associative array filled with data in
961 * [ 'param' => 'x' ],
962 * '<element param="x">tag content</element>' ]
965 * @param array $elements List of element names. Comments are always extracted.
966 * @param string $text Source text string.
967 * @param array &$matches Out parameter, Array: extracted tags
968 * @return string Stripped text
970 public static function extractTagsAndParams( $elements, $text, &$matches ) {
975 $taglist = implode( '|', $elements );
976 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
978 while ( $text != '' ) {
979 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
981 if ( count( $p ) < 5 ) {
984 if ( count( $p ) > 5 ) {
998 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
999 $stripped .= $marker;
1001 if ( $close === '/>' ) {
1002 # Empty element tag, <tag />
1007 if ( $element === '!--' ) {
1010 $end = "/(<\\/$element\\s*>)/i";
1012 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1014 if ( count( $q ) < 3 ) {
1015 # No end tag -- let it run out to the end of the text.
1024 $matches[$marker] = [ $element,
1026 Sanitizer
::decodeTagAttributes( $attributes ),
1027 "<$element$attributes$close$content$tail" ];
1033 * Get a list of strippable XML-like elements
1037 public function getStripList() {
1038 return $this->mStripList
;
1042 * Add an item to the strip state
1043 * Returns the unique tag which must be inserted into the stripped text
1044 * The tag will be replaced with the original text in unstrip()
1046 * @param string $text
1050 public function insertStripItem( $text ) {
1051 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1052 $this->mMarkerIndex++
;
1053 $this->mStripState
->addGeneral( $marker, $text );
1058 * parse the wiki syntax used to render tables
1061 * @param string $text
1064 public function doTableStuff( $text ) {
1065 $lines = StringUtils
::explode( "\n", $text );
1067 $td_history = []; # Is currently a td tag open?
1068 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1069 $tr_history = []; # Is currently a tr tag open?
1070 $tr_attributes = []; # history of tr attributes
1071 $has_opened_tr = []; # Did this table open a <tr> element?
1072 $indent_level = 0; # indent level of the table
1074 foreach ( $lines as $outLine ) {
1075 $line = trim( $outLine );
1077 if ( $line === '' ) { # empty line, go to next line
1078 $out .= $outLine . "\n";
1082 $first_character = $line[0];
1083 $first_two = substr( $line, 0, 2 );
1086 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1087 # First check if we are starting a new table
1088 $indent_level = strlen( $matches[1] );
1090 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1091 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1093 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1094 array_push( $td_history, false );
1095 array_push( $last_tag_history, '' );
1096 array_push( $tr_history, false );
1097 array_push( $tr_attributes, '' );
1098 array_push( $has_opened_tr, false );
1099 } elseif ( count( $td_history ) == 0 ) {
1100 # Don't do any of the following
1101 $out .= $outLine . "\n";
1103 } elseif ( $first_two === '|}' ) {
1104 # We are ending a table
1105 $line = '</table>' . substr( $line, 2 );
1106 $last_tag = array_pop( $last_tag_history );
1108 if ( !array_pop( $has_opened_tr ) ) {
1109 $line = "<tr><td></td></tr>{$line}";
1112 if ( array_pop( $tr_history ) ) {
1113 $line = "</tr>{$line}";
1116 if ( array_pop( $td_history ) ) {
1117 $line = "</{$last_tag}>{$line}";
1119 array_pop( $tr_attributes );
1120 if ( $indent_level > 0 ) {
1121 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1125 } elseif ( $first_two === '|-' ) {
1126 # Now we have a table row
1127 $line = preg_replace( '#^\|-+#', '', $line );
1129 # Whats after the tag is now only attributes
1130 $attributes = $this->mStripState
->unstripBoth( $line );
1131 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1132 array_pop( $tr_attributes );
1133 array_push( $tr_attributes, $attributes );
1136 $last_tag = array_pop( $last_tag_history );
1137 array_pop( $has_opened_tr );
1138 array_push( $has_opened_tr, true );
1140 if ( array_pop( $tr_history ) ) {
1144 if ( array_pop( $td_history ) ) {
1145 $line = "</{$last_tag}>{$line}";
1149 array_push( $tr_history, false );
1150 array_push( $td_history, false );
1151 array_push( $last_tag_history, '' );
1152 } elseif ( $first_character === '|'
1153 ||
$first_character === '!'
1154 ||
$first_two === '|+'
1156 # This might be cell elements, td, th or captions
1157 if ( $first_two === '|+' ) {
1158 $first_character = '+';
1159 $line = substr( $line, 2 );
1161 $line = substr( $line, 1 );
1164 // Implies both are valid for table headings.
1165 if ( $first_character === '!' ) {
1166 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1169 # Split up multiple cells on the same line.
1170 # FIXME : This can result in improper nesting of tags processed
1171 # by earlier parser steps.
1172 $cells = explode( '||', $line );
1176 # Loop through each table cell
1177 foreach ( $cells as $cell ) {
1179 if ( $first_character !== '+' ) {
1180 $tr_after = array_pop( $tr_attributes );
1181 if ( !array_pop( $tr_history ) ) {
1182 $previous = "<tr{$tr_after}>\n";
1184 array_push( $tr_history, true );
1185 array_push( $tr_attributes, '' );
1186 array_pop( $has_opened_tr );
1187 array_push( $has_opened_tr, true );
1190 $last_tag = array_pop( $last_tag_history );
1192 if ( array_pop( $td_history ) ) {
1193 $previous = "</{$last_tag}>\n{$previous}";
1196 if ( $first_character === '|' ) {
1198 } elseif ( $first_character === '!' ) {
1200 } elseif ( $first_character === '+' ) {
1201 $last_tag = 'caption';
1206 array_push( $last_tag_history, $last_tag );
1208 # A cell could contain both parameters and data
1209 $cell_data = explode( '|', $cell, 2 );
1211 # T2553: Note that a '|' inside an invalid link should not
1212 # be mistaken as delimiting cell parameters
1213 # Bug T153140: Neither should language converter markup.
1214 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1215 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1216 } elseif ( count( $cell_data ) == 1 ) {
1217 // Whitespace in cells is trimmed
1218 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1220 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1221 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1222 // Whitespace in cells is trimmed
1223 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1227 array_push( $td_history, true );
1230 $out .= $outLine . "\n";
1233 # Closing open td, tr && table
1234 while ( count( $td_history ) > 0 ) {
1235 if ( array_pop( $td_history ) ) {
1238 if ( array_pop( $tr_history ) ) {
1241 if ( !array_pop( $has_opened_tr ) ) {
1242 $out .= "<tr><td></td></tr>\n";
1245 $out .= "</table>\n";
1248 # Remove trailing line-ending (b/c)
1249 if ( substr( $out, -1 ) === "\n" ) {
1250 $out = substr( $out, 0, -1 );
1253 # special case: don't return empty table
1254 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1262 * Helper function for parse() that transforms wiki markup into half-parsed
1263 * HTML. Only called for $mOutputType == self::OT_HTML.
1267 * @param string $text The text to parse
1268 * @param bool $isMain Whether this is being called from the main parse() function
1269 * @param PPFrame|bool $frame A pre-processor frame
1273 public function internalParse( $text, $isMain = true, $frame = false ) {
1276 // Avoid PHP 7.1 warning from passing $this by reference
1279 # Hook to suspend the parser in this state
1280 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1284 # if $frame is provided, then use $frame for replacing any variables
1286 # use frame depth to infer how include/noinclude tags should be handled
1287 # depth=0 means this is the top-level document; otherwise it's an included document
1288 if ( !$frame->depth
) {
1291 $flag = self
::PTD_FOR_INCLUSION
;
1293 $dom = $this->preprocessToDom( $text, $flag );
1294 $text = $frame->expand( $dom );
1296 # if $frame is not provided, then use old-style replaceVariables
1297 $text = $this->replaceVariables( $text );
1300 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1301 $text = Sanitizer
::removeHTMLtags(
1303 [ $this, 'attributeStripCallback' ],
1305 array_keys( $this->mTransparentTagHooks
),
1307 [ $this, 'addTrackingCategory' ]
1309 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1311 # Tables need to come after variable replacement for things to work
1312 # properly; putting them before other transformations should keep
1313 # exciting things like link expansions from showing up in surprising
1315 $text = $this->doTableStuff( $text );
1317 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1319 $text = $this->doDoubleUnderscore( $text );
1321 $text = $this->doHeadings( $text );
1322 $text = $this->replaceInternalLinks( $text );
1323 $text = $this->doAllQuotes( $text );
1324 $text = $this->replaceExternalLinks( $text );
1326 # replaceInternalLinks may sometimes leave behind
1327 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1328 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1330 $text = $this->doMagicLinks( $text );
1331 $text = $this->formatHeadings( $text, $origText, $isMain );
1337 * Helper function for parse() that transforms half-parsed HTML into fully
1340 * @param string $text
1341 * @param bool $isMain
1342 * @param bool $linestart
1345 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1346 $text = $this->mStripState
->unstripGeneral( $text );
1348 // Avoid PHP 7.1 warning from passing $this by reference
1352 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1355 # Clean up special characters, only run once, next-to-last before doBlockLevels
1357 # French spaces, last one Guillemet-left
1358 # only if there is something before the space
1359 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1360 # french spaces, Guillemet-right
1361 '/(\\302\\253) /' => '\\1 ',
1362 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1364 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1366 $text = $this->doBlockLevels( $text, $linestart );
1368 $this->replaceLinkHolders( $text );
1371 * The input doesn't get language converted if
1373 * b) Content isn't converted
1374 * c) It's a conversion table
1375 * d) it is an interface message (which is in the user language)
1377 if ( !( $this->mOptions
->getDisableContentConversion()
1378 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1380 if ( !$this->mOptions
->getInterfaceMessage() ) {
1381 # The position of the convert() call should not be changed. it
1382 # assumes that the links are all replaced and the only thing left
1383 # is the <nowiki> mark.
1384 $text = $this->getTargetLanguage()->convert( $text );
1388 $text = $this->mStripState
->unstripNoWiki( $text );
1391 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1394 $text = $this->replaceTransparentTags( $text );
1395 $text = $this->mStripState
->unstripGeneral( $text );
1397 $text = Sanitizer
::normalizeCharReferences( $text );
1399 if ( MWTidy
::isEnabled() ) {
1400 if ( $this->mOptions
->getTidy() ) {
1401 $text = MWTidy
::tidy( $text );
1404 # attempt to sanitize at least some nesting problems
1405 # (T4702 and quite a few others)
1407 # ''Something [http://www.cool.com cool''] -->
1408 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1409 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1410 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1411 # fix up an anchor inside another anchor, only
1412 # at least for a single single nested link (T5695)
1413 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1414 '\\1\\2</a>\\3</a>\\1\\4</a>',
1415 # fix div inside inline elements- doBlockLevels won't wrap a line which
1416 # contains a div, so fix it up here; replace
1417 # div with escaped text
1418 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1419 '\\1\\3<div\\5>\\6</div>\\8\\9',
1420 # remove empty italic or bold tag pairs, some
1421 # introduced by rules above
1422 '/<([bi])><\/\\1>/' => '',
1425 $text = preg_replace(
1426 array_keys( $tidyregs ),
1427 array_values( $tidyregs ),
1432 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1439 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1440 * magic external links.
1445 * @param string $text
1449 public function doMagicLinks( $text ) {
1450 $prots = wfUrlProtocolsWithoutProtRel();
1451 $urlChar = self
::EXT_LINK_URL_CLASS
;
1452 $addr = self
::EXT_LINK_ADDR
;
1453 $space = self
::SPACE_NOT_NL
; # non-newline space
1454 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1455 $spaces = "$space++"; # possessive match of 1 or more spaces
1456 $text = preg_replace_callback(
1458 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1459 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1460 (\b # m[3]: Free external links
1462 ($addr$urlChar*) # m[4]: Post-protocol path
1464 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1466 \bISBN $spaces ( # m[6]: ISBN, capture number
1467 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1468 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1469 [0-9Xx] # check digit
1471 )!xu", [ $this, 'magicLinkCallback' ], $text );
1476 * @throws MWException
1478 * @return string HTML
1480 public function magicLinkCallback( $m ) {
1481 if ( isset( $m[1] ) && $m[1] !== '' ) {
1484 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1487 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1488 # Free external link
1489 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1490 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1492 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1493 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1498 $cssClass = 'mw-magiclink-rfc';
1499 $trackingCat = 'magiclink-tracking-rfc';
1501 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1502 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1506 $urlmsg = 'pubmedurl';
1507 $cssClass = 'mw-magiclink-pmid';
1508 $trackingCat = 'magiclink-tracking-pmid';
1511 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1512 substr( $m[0], 0, 20 ) . '"' );
1514 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1515 $this->addTrackingCategory( $trackingCat );
1516 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1517 } elseif ( isset( $m[6] ) && $m[6] !== ''
1518 && $this->mOptions
->getMagicISBNLinks()
1522 $space = self
::SPACE_NOT_NL
; # non-newline space
1523 $isbn = preg_replace( "/$space/", ' ', $isbn );
1524 $num = strtr( $isbn, [
1529 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1530 return $this->getLinkRenderer()->makeKnownLink(
1531 SpecialPage
::getTitleFor( 'Booksources', $num ),
1534 'class' => 'internal mw-magiclink-isbn',
1535 'title' => false // suppress title attribute
1544 * Make a free external link, given a user-supplied URL
1546 * @param string $url
1547 * @param int $numPostProto
1548 * The number of characters after the protocol.
1549 * @return string HTML
1552 public function makeFreeExternalLink( $url, $numPostProto ) {
1555 # The characters '<' and '>' (which were escaped by
1556 # removeHTMLtags()) should not be included in
1557 # URLs, per RFC 2396.
1558 # Make terminate a URL as well (bug T84937)
1561 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1566 $trail = substr( $url, $m2[0][1] ) . $trail;
1567 $url = substr( $url, 0, $m2[0][1] );
1570 # Move trailing punctuation to $trail
1572 # If there is no left bracket, then consider right brackets fair game too
1573 if ( strpos( $url, '(' ) === false ) {
1577 $urlRev = strrev( $url );
1578 $numSepChars = strspn( $urlRev, $sep );
1579 # Don't break a trailing HTML entity by moving the ; into $trail
1580 # This is in hot code, so use substr_compare to avoid having to
1581 # create a new string object for the comparison
1582 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1583 # more optimization: instead of running preg_match with a $
1584 # anchor, which can be slow, do the match on the reversed
1585 # string starting at the desired offset.
1586 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1587 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1591 if ( $numSepChars ) {
1592 $trail = substr( $url, -$numSepChars ) . $trail;
1593 $url = substr( $url, 0, -$numSepChars );
1596 # Verify that we still have a real URL after trail removal, and
1597 # not just lone protocol
1598 if ( strlen( $trail ) >= $numPostProto ) {
1599 return $url . $trail;
1602 $url = Sanitizer
::cleanUrl( $url );
1604 # Is this an external image?
1605 $text = $this->maybeMakeExternalImage( $url );
1606 if ( $text === false ) {
1607 # Not an image, make a link
1608 $text = Linker
::makeExternalLink( $url,
1609 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1611 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1612 # Register it in the output object...
1613 $this->mOutput
->addExternalLink( $url );
1615 return $text . $trail;
1619 * Parse headers and return html
1623 * @param string $text
1627 public function doHeadings( $text ) {
1628 for ( $i = 6; $i >= 1; --$i ) {
1629 $h = str_repeat( '=', $i );
1630 // Trim non-newline whitespace from headings
1631 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1632 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1638 * Replace single quotes with HTML markup
1641 * @param string $text
1643 * @return string The altered text
1645 public function doAllQuotes( $text ) {
1647 $lines = StringUtils
::explode( "\n", $text );
1648 foreach ( $lines as $line ) {
1649 $outtext .= $this->doQuotes( $line ) . "\n";
1651 $outtext = substr( $outtext, 0, -1 );
1656 * Helper function for doAllQuotes()
1658 * @param string $text
1662 public function doQuotes( $text ) {
1663 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1664 $countarr = count( $arr );
1665 if ( $countarr == 1 ) {
1669 // First, do some preliminary work. This may shift some apostrophes from
1670 // being mark-up to being text. It also counts the number of occurrences
1671 // of bold and italics mark-ups.
1674 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1675 $thislen = strlen( $arr[$i] );
1676 // If there are ever four apostrophes, assume the first is supposed to
1677 // be text, and the remaining three constitute mark-up for bold text.
1678 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1679 if ( $thislen == 4 ) {
1680 $arr[$i - 1] .= "'";
1683 } elseif ( $thislen > 5 ) {
1684 // If there are more than 5 apostrophes in a row, assume they're all
1685 // text except for the last 5.
1686 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1687 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1691 // Count the number of occurrences of bold and italics mark-ups.
1692 if ( $thislen == 2 ) {
1694 } elseif ( $thislen == 3 ) {
1696 } elseif ( $thislen == 5 ) {
1702 // If there is an odd number of both bold and italics, it is likely
1703 // that one of the bold ones was meant to be an apostrophe followed
1704 // by italics. Which one we cannot know for certain, but it is more
1705 // likely to be one that has a single-letter word before it.
1706 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1707 $firstsingleletterword = -1;
1708 $firstmultiletterword = -1;
1710 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1711 if ( strlen( $arr[$i] ) == 3 ) {
1712 $x1 = substr( $arr[$i - 1], -1 );
1713 $x2 = substr( $arr[$i - 1], -2, 1 );
1714 if ( $x1 === ' ' ) {
1715 if ( $firstspace == -1 ) {
1718 } elseif ( $x2 === ' ' ) {
1719 $firstsingleletterword = $i;
1720 // if $firstsingleletterword is set, we don't
1721 // look at the other options, so we can bail early.
1724 if ( $firstmultiletterword == -1 ) {
1725 $firstmultiletterword = $i;
1731 // If there is a single-letter word, use it!
1732 if ( $firstsingleletterword > -1 ) {
1733 $arr[$firstsingleletterword] = "''";
1734 $arr[$firstsingleletterword - 1] .= "'";
1735 } elseif ( $firstmultiletterword > -1 ) {
1736 // If not, but there's a multi-letter word, use that one.
1737 $arr[$firstmultiletterword] = "''";
1738 $arr[$firstmultiletterword - 1] .= "'";
1739 } elseif ( $firstspace > -1 ) {
1740 // ... otherwise use the first one that has neither.
1741 // (notice that it is possible for all three to be -1 if, for example,
1742 // there is only one pentuple-apostrophe in the line)
1743 $arr[$firstspace] = "''";
1744 $arr[$firstspace - 1] .= "'";
1748 // Now let's actually convert our apostrophic mush to HTML!
1753 foreach ( $arr as $r ) {
1754 if ( ( $i %
2 ) == 0 ) {
1755 if ( $state === 'both' ) {
1761 $thislen = strlen( $r );
1762 if ( $thislen == 2 ) {
1763 if ( $state === 'i' ) {
1766 } elseif ( $state === 'bi' ) {
1769 } elseif ( $state === 'ib' ) {
1770 $output .= '</b></i><b>';
1772 } elseif ( $state === 'both' ) {
1773 $output .= '<b><i>' . $buffer . '</i>';
1775 } else { // $state can be 'b' or ''
1779 } elseif ( $thislen == 3 ) {
1780 if ( $state === 'b' ) {
1783 } elseif ( $state === 'bi' ) {
1784 $output .= '</i></b><i>';
1786 } elseif ( $state === 'ib' ) {
1789 } elseif ( $state === 'both' ) {
1790 $output .= '<i><b>' . $buffer . '</b>';
1792 } else { // $state can be 'i' or ''
1796 } elseif ( $thislen == 5 ) {
1797 if ( $state === 'b' ) {
1798 $output .= '</b><i>';
1800 } elseif ( $state === 'i' ) {
1801 $output .= '</i><b>';
1803 } elseif ( $state === 'bi' ) {
1804 $output .= '</i></b>';
1806 } elseif ( $state === 'ib' ) {
1807 $output .= '</b></i>';
1809 } elseif ( $state === 'both' ) {
1810 $output .= '<i><b>' . $buffer . '</b></i>';
1812 } else { // ($state == '')
1820 // Now close all remaining tags. Notice that the order is important.
1821 if ( $state === 'b' ||
$state === 'ib' ) {
1824 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1827 if ( $state === 'bi' ) {
1830 // There might be lonely ''''', so make sure we have a buffer
1831 if ( $state === 'both' && $buffer ) {
1832 $output .= '<b><i>' . $buffer . '</i></b>';
1838 * Replace external links (REL)
1840 * Note: this is all very hackish and the order of execution matters a lot.
1841 * Make sure to run tests/parser/parserTests.php if you change this code.
1845 * @param string $text
1847 * @throws MWException
1850 public function replaceExternalLinks( $text ) {
1851 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1852 if ( $bits === false ) {
1853 throw new MWException( "PCRE needs to be compiled with "
1854 . "--enable-unicode-properties in order for MediaWiki to function" );
1856 $s = array_shift( $bits );
1859 while ( $i < count( $bits ) ) {
1862 $text = $bits[$i++
];
1863 $trail = $bits[$i++
];
1865 # The characters '<' and '>' (which were escaped by
1866 # removeHTMLtags()) should not be included in
1867 # URLs, per RFC 2396.
1869 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1870 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1871 $url = substr( $url, 0, $m2[0][1] );
1874 # If the link text is an image URL, replace it with an <img> tag
1875 # This happened by accident in the original parser, but some people used it extensively
1876 $img = $this->maybeMakeExternalImage( $text );
1877 if ( $img !== false ) {
1883 # Set linktype for CSS
1886 # No link text, e.g. [http://domain.tld/some.link]
1887 if ( $text == '' ) {
1889 $langObj = $this->getTargetLanguage();
1890 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1891 $linktype = 'autonumber';
1893 # Have link text, e.g. [http://domain.tld/some.link text]s
1895 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1898 // Excluding protocol-relative URLs may avoid many false positives.
1899 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1900 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1903 $url = Sanitizer
::cleanUrl( $url );
1905 # Use the encoded URL
1906 # This means that users can paste URLs directly into the text
1907 # Funny characters like ö aren't valid in URLs anyway
1908 # This was changed in August 2004
1909 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1910 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1912 # Register link in the output object.
1913 $this->mOutput
->addExternalLink( $url );
1920 * Get the rel attribute for a particular external link.
1923 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1924 * nofollow if appropriate
1925 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1926 * @return string|null Rel attribute for $url
1928 public static function getExternalLinkRel( $url = false, $title = null ) {
1929 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1930 $ns = $title ?
$title->getNamespace() : false;
1931 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1932 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1940 * Get an associative array of additional HTML attributes appropriate for a
1941 * particular external link. This currently may include rel => nofollow
1942 * (depending on configuration, namespace, and the URL's domain) and/or a
1943 * target attribute (depending on configuration).
1945 * @param string $url URL to extract the domain from for rel =>
1946 * nofollow if appropriate
1947 * @return array Associative array of HTML attributes
1949 public function getExternalLinkAttribs( $url ) {
1951 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1953 $target = $this->mOptions
->getExternalLinkTarget();
1955 $attribs['target'] = $target;
1956 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1957 // T133507. New windows can navigate parent cross-origin.
1958 // Including noreferrer due to lacking browser
1959 // support of noopener. Eventually noreferrer should be removed.
1960 if ( $rel !== '' ) {
1963 $rel .= 'noreferrer noopener';
1966 $attribs['rel'] = $rel;
1971 * Replace unusual escape codes in a URL with their equivalent characters
1973 * This generally follows the syntax defined in RFC 3986, with special
1974 * consideration for HTTP query strings.
1976 * @param string $url
1979 public static function normalizeLinkUrl( $url ) {
1980 # First, make sure unsafe characters are encoded
1981 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1983 return rawurlencode( $m[0] );
1989 $end = strlen( $url );
1991 # Fragment part - 'fragment'
1992 $start = strpos( $url, '#' );
1993 if ( $start !== false && $start < $end ) {
1994 $ret = self
::normalizeUrlComponent(
1995 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1999 # Query part - 'query' minus &=+;
2000 $start = strpos( $url, '?' );
2001 if ( $start !== false && $start < $end ) {
2002 $ret = self
::normalizeUrlComponent(
2003 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2007 # Scheme and path part - 'pchar'
2008 # (we assume no userinfo or encoded colons in the host)
2009 $ret = self
::normalizeUrlComponent(
2010 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2015 private static function normalizeUrlComponent( $component, $unsafe ) {
2016 $callback = function ( $matches ) use ( $unsafe ) {
2017 $char = urldecode( $matches[0] );
2018 $ord = ord( $char );
2019 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2023 # Leave it escaped, but use uppercase for a-f
2024 return strtoupper( $matches[0] );
2027 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2031 * make an image if it's allowed, either through the global
2032 * option, through the exception, or through the on-wiki whitelist
2034 * @param string $url
2038 private function maybeMakeExternalImage( $url ) {
2039 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2040 $imagesexception = !empty( $imagesfrom );
2042 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2043 if ( $imagesexception && is_array( $imagesfrom ) ) {
2044 $imagematch = false;
2045 foreach ( $imagesfrom as $match ) {
2046 if ( strpos( $url, $match ) === 0 ) {
2051 } elseif ( $imagesexception ) {
2052 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2054 $imagematch = false;
2057 if ( $this->mOptions
->getAllowExternalImages()
2058 ||
( $imagesexception && $imagematch )
2060 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2062 $text = Linker
::makeExternalImage( $url );
2065 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2066 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2068 $whitelist = explode(
2070 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2073 foreach ( $whitelist as $entry ) {
2074 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2075 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2078 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2079 # Image matches a whitelist entry
2080 $text = Linker
::makeExternalImage( $url );
2089 * Process [[ ]] wikilinks
2093 * @return string Processed text
2097 public function replaceInternalLinks( $s ) {
2098 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2103 * Process [[ ]] wikilinks (RIL)
2105 * @throws MWException
2106 * @return LinkHolderArray
2110 public function replaceInternalLinks2( &$s ) {
2111 global $wgExtraInterlanguageLinkPrefixes;
2113 static $tc = false, $e1, $e1_img;
2114 # the % is needed to support urlencoded titles as well
2116 $tc = Title
::legalChars() . '#%';
2117 # Match a link having the form [[namespace:link|alternate]]trail
2118 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2119 # Match cases where there is no "]]", which might still be images
2120 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2123 $holders = new LinkHolderArray( $this );
2125 # split the entire text string on occurrences of [[
2126 $a = StringUtils
::explode( '[[', ' ' . $s );
2127 # get the first element (all text up to first [[), and remove the space we added
2130 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2131 $s = substr( $s, 1 );
2133 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2135 if ( $useLinkPrefixExtension ) {
2136 # Match the end of a line for a word that's not followed by whitespace,
2137 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2139 $charset = $wgContLang->linkPrefixCharset();
2140 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2143 if ( is_null( $this->mTitle
) ) {
2144 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2146 $nottalk = !$this->mTitle
->isTalkPage();
2148 if ( $useLinkPrefixExtension ) {
2150 if ( preg_match( $e2, $s, $m ) ) {
2151 $first_prefix = $m[2];
2153 $first_prefix = false;
2159 $useSubpages = $this->areSubpagesAllowed();
2161 # Loop for each link
2162 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2163 # Check for excessive memory usage
2164 if ( $holders->isBig() ) {
2166 # Do the existence check, replace the link holders and clear the array
2167 $holders->replace( $s );
2171 if ( $useLinkPrefixExtension ) {
2172 if ( preg_match( $e2, $s, $m ) ) {
2179 if ( $first_prefix ) {
2180 $prefix = $first_prefix;
2181 $first_prefix = false;
2185 $might_be_img = false;
2187 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2189 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2190 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2191 # the real problem is with the $e1 regex
2193 # Still some problems for cases where the ] is meant to be outside punctuation,
2194 # and no image is in sight. See T4095.
2196 && substr( $m[3], 0, 1 ) === ']'
2197 && strpos( $text, '[' ) !== false
2199 $text .= ']'; # so that replaceExternalLinks($text) works later
2200 $m[3] = substr( $m[3], 1 );
2202 # fix up urlencoded title texts
2203 if ( strpos( $m[1], '%' ) !== false ) {
2204 # Should anchors '#' also be rejected?
2205 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2208 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2209 # Invalid, but might be an image with a link in its caption
2210 $might_be_img = true;
2212 if ( strpos( $m[1], '%' ) !== false ) {
2213 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2216 } else { # Invalid form; output directly
2217 $s .= $prefix . '[[' . $line;
2221 $origLink = ltrim( $m[1], ' ' );
2223 # Don't allow internal links to pages containing
2224 # PROTO: where PROTO is a valid URL protocol; these
2225 # should be external links.
2226 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2227 $s .= $prefix . '[[' . $line;
2231 # Make subpage if necessary
2232 if ( $useSubpages ) {
2233 $link = $this->maybeDoSubpageLink( $origLink, $text );
2238 // \x7f isn't a default legal title char, so most likely strip
2239 // markers will force us into the "invalid form" path above. But,
2240 // just in case, let's assert that xmlish tags aren't valid in
2241 // the title position.
2242 $unstrip = $this->mStripState
->killMarkers( $link );
2243 $noMarkers = ( $unstrip === $link );
2245 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2246 if ( $nt === null ) {
2247 $s .= $prefix . '[[' . $line;
2251 $ns = $nt->getNamespace();
2252 $iw = $nt->getInterwiki();
2254 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2256 if ( $might_be_img ) { # if this is actually an invalid link
2257 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2260 # look at the next 'line' to see if we can close it there
2262 $next_line = $a->current();
2263 if ( $next_line === false ||
$next_line === null ) {
2266 $m = explode( ']]', $next_line, 3 );
2267 if ( count( $m ) == 3 ) {
2268 # the first ]] closes the inner link, the second the image
2270 $text .= "[[{$m[0]}]]{$m[1]}";
2273 } elseif ( count( $m ) == 2 ) {
2274 # if there's exactly one ]] that's fine, we'll keep looking
2275 $text .= "[[{$m[0]}]]{$m[1]}";
2277 # if $next_line is invalid too, we need look no further
2278 $text .= '[[' . $next_line;
2283 # we couldn't find the end of this imageLink, so output it raw
2284 # but don't ignore what might be perfectly normal links in the text we've examined
2285 $holders->merge( $this->replaceInternalLinks2( $text ) );
2286 $s .= "{$prefix}[[$link|$text";
2287 # note: no $trail, because without an end, there *is* no trail
2290 } else { # it's not an image, so output it raw
2291 $s .= "{$prefix}[[$link|$text";
2292 # note: no $trail, because without an end, there *is* no trail
2297 $wasblank = ( $text == '' );
2301 # Strip off leading ':'
2302 $text = substr( $text, 1 );
2305 # T6598 madness. Handle the quotes only if they come from the alternate part
2306 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2307 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2308 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2309 $text = $this->doQuotes( $text );
2312 # Link not escaped by : , create the various objects
2313 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2316 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2317 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2318 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2321 # T26502: filter duplicates
2322 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2323 $this->mLangLinkLanguages
[$iw] = true;
2324 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2328 * Strip the whitespace interwiki links produce, see T10897
2330 $s = rtrim( $s . $prefix ) . $trail; # T175416
2334 if ( $ns == NS_FILE
) {
2335 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2337 # if no parameters were passed, $text
2338 # becomes something like "File:Foo.png",
2339 # which we don't want to pass on to the
2343 # recursively parse links inside the image caption
2344 # actually, this will parse them in any other parameters, too,
2345 # but it might be hard to fix that, and it doesn't matter ATM
2346 $text = $this->replaceExternalLinks( $text );
2347 $holders->merge( $this->replaceInternalLinks2( $text ) );
2349 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2350 $s .= $prefix . $this->armorLinks(
2351 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2354 } elseif ( $ns == NS_CATEGORY
) {
2356 * Strip the whitespace Category links produce, see T2087
2358 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2361 $sortkey = $this->getDefaultSort();
2365 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2366 $sortkey = str_replace( "\n", '', $sortkey );
2367 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2368 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2374 # Self-link checking. For some languages, variants of the title are checked in
2375 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2376 # for linking to a different variant.
2377 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2378 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2382 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2383 # @todo FIXME: Should do batch file existence checks, see comment below
2384 if ( $ns == NS_MEDIA
) {
2385 # Give extensions a chance to select the file revision for us
2388 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2389 [ $this, $nt, &$options, &$descQuery ] );
2390 # Fetch and register the file (file title may be different via hooks)
2391 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2392 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2393 $s .= $prefix . $this->armorLinks(
2394 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2398 # Some titles, such as valid special pages or files in foreign repos, should
2399 # be shown as bluelinks even though they're not included in the page table
2400 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2401 # batch file existence checks for NS_FILE and NS_MEDIA
2402 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2403 $this->mOutput
->addLink( $nt );
2404 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2406 # Links will be added to the output link list after checking
2407 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2414 * Render a forced-blue link inline; protect against double expansion of
2415 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2416 * Since this little disaster has to split off the trail text to avoid
2417 * breaking URLs in the following text without breaking trails on the
2418 * wiki links, it's been made into a horrible function.
2421 * @param string $text
2422 * @param string $trail
2423 * @param string $prefix
2424 * @return string HTML-wikitext mix oh yuck
2426 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2427 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2429 if ( $text == '' ) {
2430 $text = htmlspecialchars( $nt->getPrefixedText() );
2433 $link = $this->getLinkRenderer()->makeKnownLink(
2434 $nt, new HtmlArmor( "$prefix$text$inside" )
2437 return $this->armorLinks( $link ) . $trail;
2441 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2442 * going to go through further parsing steps before inline URL expansion.
2444 * Not needed quite as much as it used to be since free links are a bit
2445 * more sensible these days. But bracketed links are still an issue.
2447 * @param string $text More-or-less HTML
2448 * @return string Less-or-more HTML with NOPARSE bits
2450 public function armorLinks( $text ) {
2451 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2452 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2456 * Return true if subpage links should be expanded on this page.
2459 public function areSubpagesAllowed() {
2460 # Some namespaces don't allow subpages
2461 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2465 * Handle link to subpage if necessary
2467 * @param string $target The source of the link
2468 * @param string &$text The link text, modified as necessary
2469 * @return string The full name of the link
2472 public function maybeDoSubpageLink( $target, &$text ) {
2473 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2477 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2479 * @param string $text
2480 * @param bool $linestart Whether or not this is at the start of a line.
2482 * @return string The lists rendered as HTML
2484 public function doBlockLevels( $text, $linestart ) {
2485 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2489 * Return value of a magic variable (like PAGENAME)
2493 * @param string $index Magic variable identifier as mapped in MagicWord::$mVariableIDs
2494 * @param bool|PPFrame $frame
2496 * @throws MWException
2499 public function getVariableValue( $index, $frame = false ) {
2500 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2501 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2503 if ( is_null( $this->mTitle
) ) {
2504 // If no title set, bad things are going to happen
2505 // later. Title should always be set since this
2506 // should only be called in the middle of a parse
2507 // operation (but the unit-tests do funky stuff)
2508 throw new MWException( __METHOD__
. ' Should only be '
2509 . ' called while parsing (no title set)' );
2512 // Avoid PHP 7.1 warning from passing $this by reference
2516 * Some of these require message or data lookups and can be
2517 * expensive to check many times.
2519 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2520 if ( isset( $this->mVarCache
[$index] ) ) {
2521 return $this->mVarCache
[$index];
2525 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2526 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2528 $pageLang = $this->getFunctionLang();
2534 case 'currentmonth':
2535 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2537 case 'currentmonth1':
2538 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2540 case 'currentmonthname':
2541 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2543 case 'currentmonthnamegen':
2544 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2546 case 'currentmonthabbrev':
2547 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2550 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2553 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2556 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2559 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2561 case 'localmonthname':
2562 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2564 case 'localmonthnamegen':
2565 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2567 case 'localmonthabbrev':
2568 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2571 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2574 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2577 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2580 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2582 case 'fullpagename':
2583 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2585 case 'fullpagenamee':
2586 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2589 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2591 case 'subpagenamee':
2592 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2594 case 'rootpagename':
2595 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2597 case 'rootpagenamee':
2598 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2601 $this->mTitle
->getRootText()
2604 case 'basepagename':
2605 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2607 case 'basepagenamee':
2608 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2611 $this->mTitle
->getBaseText()
2614 case 'talkpagename':
2615 if ( $this->mTitle
->canHaveTalkPage() ) {
2616 $talkPage = $this->mTitle
->getTalkPage();
2617 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2622 case 'talkpagenamee':
2623 if ( $this->mTitle
->canHaveTalkPage() ) {
2624 $talkPage = $this->mTitle
->getTalkPage();
2625 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2630 case 'subjectpagename':
2631 $subjPage = $this->mTitle
->getSubjectPage();
2632 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2634 case 'subjectpagenamee':
2635 $subjPage = $this->mTitle
->getSubjectPage();
2636 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2638 case 'pageid': // requested in T25427
2639 $pageid = $this->getTitle()->getArticleID();
2640 if ( $pageid == 0 ) {
2641 # 0 means the page doesn't exist in the database,
2642 # which means the user is previewing a new page.
2643 # The vary-revision flag must be set, because the magic word
2644 # will have a different value once the page is saved.
2645 $this->mOutput
->setFlag( 'vary-revision' );
2646 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2648 $value = $pageid ?
: null;
2651 # Let the edit saving system know we should parse the page
2652 # *after* a revision ID has been assigned.
2653 $this->mOutput
->setFlag( 'vary-revision-id' );
2654 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2655 $value = $this->mRevisionId
;
2656 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2657 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2658 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2662 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2664 case 'revisionday2':
2665 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2667 case 'revisionmonth':
2668 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2670 case 'revisionmonth1':
2671 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2673 case 'revisionyear':
2674 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2676 case 'revisiontimestamp':
2677 # Let the edit saving system know we should parse the page
2678 # *after* a revision ID has been assigned. This is for null edits.
2679 $this->mOutput
->setFlag( 'vary-revision' );
2680 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2681 $value = $this->getRevisionTimestamp();
2683 case 'revisionuser':
2684 # Let the edit saving system know we should parse the page
2685 # *after* a revision ID has been assigned for null edits.
2686 $this->mOutput
->setFlag( 'vary-user' );
2687 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2688 $value = $this->getRevisionUser();
2690 case 'revisionsize':
2691 $value = $this->getRevisionSize();
2694 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2697 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2699 case 'namespacenumber':
2700 $value = $this->mTitle
->getNamespace();
2703 $value = $this->mTitle
->canHaveTalkPage()
2704 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2708 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2710 case 'subjectspace':
2711 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2713 case 'subjectspacee':
2714 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2716 case 'currentdayname':
2717 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2720 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2723 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2726 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2729 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2730 # int to remove the padding
2731 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2734 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2736 case 'localdayname':
2737 $value = $pageLang->getWeekdayName(
2738 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2742 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2745 $value = $pageLang->time(
2746 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2752 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2755 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2756 # int to remove the padding
2757 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2760 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2762 case 'numberofarticles':
2763 $value = $pageLang->formatNum( SiteStats
::articles() );
2765 case 'numberoffiles':
2766 $value = $pageLang->formatNum( SiteStats
::images() );
2768 case 'numberofusers':
2769 $value = $pageLang->formatNum( SiteStats
::users() );
2771 case 'numberofactiveusers':
2772 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2774 case 'numberofpages':
2775 $value = $pageLang->formatNum( SiteStats
::pages() );
2777 case 'numberofadmins':
2778 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2780 case 'numberofedits':
2781 $value = $pageLang->formatNum( SiteStats
::edits() );
2783 case 'currenttimestamp':
2784 $value = wfTimestamp( TS_MW
, $ts );
2786 case 'localtimestamp':
2787 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2789 case 'currentversion':
2790 $value = SpecialVersion
::getVersion();
2793 return $wgArticlePath;
2799 return $wgServerName;
2801 return $wgScriptPath;
2803 return $wgStylePath;
2804 case 'directionmark':
2805 return $pageLang->getDirMark();
2806 case 'contentlanguage':
2807 global $wgLanguageCode;
2808 return $wgLanguageCode;
2809 case 'pagelanguage':
2810 $value = $pageLang->getCode();
2812 case 'cascadingsources':
2813 $value = CoreParserFunctions
::cascadingsources( $this );
2818 'ParserGetVariableValueSwitch',
2819 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2826 $this->mVarCache
[$index] = $value;
2835 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2836 * @param string $variable Parser variable name
2839 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2842 # Get the timezone-adjusted timestamp to be used for this revision
2843 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2844 # Possibly set vary-revision if there is not yet an associated revision
2845 if ( !$this->getRevisionObject() ) {
2846 # Get the timezone-adjusted timestamp $mtts seconds in the future
2848 $wgContLang->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2853 if ( $resNow !== $resThen ) {
2854 # Let the edit saving system know we should parse the page
2855 # *after* a revision ID has been assigned. This is for null edits.
2856 $this->mOutput
->setFlag( 'vary-revision' );
2857 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2865 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2869 public function initialiseVariables() {
2870 $variableIDs = MagicWord
::getVariableIDs();
2871 $substIDs = MagicWord
::getSubstIDs();
2873 $this->mVariables
= new MagicWordArray( $variableIDs );
2874 $this->mSubstWords
= new MagicWordArray( $substIDs );
2878 * Preprocess some wikitext and return the document tree.
2879 * This is the ghost of replace_variables().
2881 * @param string $text The text to parse
2882 * @param int $flags Bitwise combination of:
2883 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2884 * included. Default is to assume a direct page view.
2886 * The generated DOM tree must depend only on the input text and the flags.
2887 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2889 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2890 * change in the DOM tree for a given text, must be passed through the section identifier
2891 * in the section edit link and thus back to extractSections().
2893 * The output of this function is currently only cached in process memory, but a persistent
2894 * cache may be implemented at a later date which takes further advantage of these strict
2895 * dependency requirements.
2899 public function preprocessToDom( $text, $flags = 0 ) {
2900 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2905 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2911 public static function splitWhitespace( $s ) {
2912 $ltrimmed = ltrim( $s );
2913 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2914 $trimmed = rtrim( $ltrimmed );
2915 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2917 $w2 = substr( $ltrimmed, -$diff );
2921 return [ $w1, $trimmed, $w2 ];
2925 * Replace magic variables, templates, and template arguments
2926 * with the appropriate text. Templates are substituted recursively,
2927 * taking care to avoid infinite loops.
2929 * Note that the substitution depends on value of $mOutputType:
2930 * self::OT_WIKI: only {{subst:}} templates
2931 * self::OT_PREPROCESS: templates but not extension tags
2932 * self::OT_HTML: all templates and extension tags
2934 * @param string $text The text to transform
2935 * @param bool|PPFrame $frame Object describing the arguments passed to the
2936 * template. Arguments may also be provided as an associative array, as
2937 * was the usual case before MW1.12. Providing arguments this way may be
2938 * useful for extensions wishing to perform variable replacement
2940 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2941 * double-brace expansion.
2944 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2945 # Is there any text? Also, Prevent too big inclusions!
2946 $textSize = strlen( $text );
2947 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2951 if ( $frame === false ) {
2952 $frame = $this->getPreprocessor()->newFrame();
2953 } elseif ( !( $frame instanceof PPFrame
) ) {
2954 wfDebug( __METHOD__
. " called using plain parameters instead of "
2955 . "a PPFrame instance. Creating custom frame.\n" );
2956 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2959 $dom = $this->preprocessToDom( $text );
2960 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2961 $text = $frame->expand( $dom, $flags );
2967 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2969 * @param array $args
2973 public static function createAssocArgs( $args ) {
2976 foreach ( $args as $arg ) {
2977 $eqpos = strpos( $arg, '=' );
2978 if ( $eqpos === false ) {
2979 $assocArgs[$index++
] = $arg;
2981 $name = trim( substr( $arg, 0, $eqpos ) );
2982 $value = trim( substr( $arg, $eqpos +
1 ) );
2983 if ( $value === false ) {
2986 if ( $name !== false ) {
2987 $assocArgs[$name] = $value;
2996 * Warn the user when a parser limitation is reached
2997 * Will warn at most once the user per limitation type
2999 * The results are shown during preview and run through the Parser (See EditPage.php)
3001 * @param string $limitationType Should be one of:
3002 * 'expensive-parserfunction' (corresponding messages:
3003 * 'expensive-parserfunction-warning',
3004 * 'expensive-parserfunction-category')
3005 * 'post-expand-template-argument' (corresponding messages:
3006 * 'post-expand-template-argument-warning',
3007 * 'post-expand-template-argument-category')
3008 * 'post-expand-template-inclusion' (corresponding messages:
3009 * 'post-expand-template-inclusion-warning',
3010 * 'post-expand-template-inclusion-category')
3011 * 'node-count-exceeded' (corresponding messages:
3012 * 'node-count-exceeded-warning',
3013 * 'node-count-exceeded-category')
3014 * 'expansion-depth-exceeded' (corresponding messages:
3015 * 'expansion-depth-exceeded-warning',
3016 * 'expansion-depth-exceeded-category')
3017 * @param string|int|null $current Current value
3018 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3019 * exceeded, provide the values (optional)
3021 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3022 # does no harm if $current and $max are present but are unnecessary for the message
3023 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3024 # only during preview, and that would split the parser cache unnecessarily.
3025 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3027 $this->mOutput
->addWarning( $warning );
3028 $this->addTrackingCategory( "$limitationType-category" );
3032 * Return the text of a template, after recursively
3033 * replacing any variables or templates within the template.
3035 * @param array $piece The parts of the template
3036 * $piece['title']: the title, i.e. the part before the |
3037 * $piece['parts']: the parameter array
3038 * $piece['lineStart']: whether the brace was at the start of a line
3039 * @param PPFrame $frame The current frame, contains template arguments
3041 * @return string The text of the template
3043 public function braceSubstitution( $piece, $frame ) {
3046 // $text has been filled
3048 // wiki markup in $text should be escaped
3050 // $text is HTML, armour it against wikitext transformation
3052 // Force interwiki transclusion to be done in raw mode not rendered
3053 $forceRawInterwiki = false;
3054 // $text is a DOM node needing expansion in a child frame
3055 $isChildObj = false;
3056 // $text is a DOM node needing expansion in the current frame
3057 $isLocalObj = false;
3059 # Title object, where $text came from
3062 # $part1 is the bit before the first |, and must contain only title characters.
3063 # Various prefixes will be stripped from it later.
3064 $titleWithSpaces = $frame->expand( $piece['title'] );
3065 $part1 = trim( $titleWithSpaces );
3068 # Original title text preserved for various purposes
3069 $originalTitle = $part1;
3071 # $args is a list of argument nodes, starting from index 0, not including $part1
3072 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3073 # below won't work b/c this $args isn't an object
3074 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3076 $profileSection = null; // profile templates
3080 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3082 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3083 # Decide whether to expand template or keep wikitext as-is.
3084 if ( $this->ot
['wiki'] ) {
3085 if ( $substMatch === false ) {
3086 $literal = true; # literal when in PST with no prefix
3088 $literal = false; # expand when in PST with subst: or safesubst:
3091 if ( $substMatch == 'subst' ) {
3092 $literal = true; # literal when not in PST with plain subst:
3094 $literal = false; # expand when not in PST with safesubst: or no prefix
3098 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3105 if ( !$found && $args->getLength() == 0 ) {
3106 $id = $this->mVariables
->matchStartToEnd( $part1 );
3107 if ( $id !== false ) {
3108 $text = $this->getVariableValue( $id, $frame );
3109 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3110 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3116 # MSG, MSGNW and RAW
3119 $mwMsgnw = MagicWord
::get( 'msgnw' );
3120 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3123 # Remove obsolete MSG:
3124 $mwMsg = MagicWord
::get( 'msg' );
3125 $mwMsg->matchStartAndRemove( $part1 );
3129 $mwRaw = MagicWord
::get( 'raw' );
3130 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3131 $forceRawInterwiki = true;
3137 $colonPos = strpos( $part1, ':' );
3138 if ( $colonPos !== false ) {
3139 $func = substr( $part1, 0, $colonPos );
3140 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3141 $argsLength = $args->getLength();
3142 for ( $i = 0; $i < $argsLength; $i++
) {
3143 $funcArgs[] = $args->item( $i );
3146 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3148 // Extract any forwarded flags
3149 if ( isset( $result['title'] ) ) {
3150 $title = $result['title'];
3152 if ( isset( $result['found'] ) ) {
3153 $found = $result['found'];
3155 if ( array_key_exists( 'text', $result ) ) {
3157 $text = $result['text'];
3159 if ( isset( $result['nowiki'] ) ) {
3160 $nowiki = $result['nowiki'];
3162 if ( isset( $result['isHTML'] ) ) {
3163 $isHTML = $result['isHTML'];
3165 if ( isset( $result['forceRawInterwiki'] ) ) {
3166 $forceRawInterwiki = $result['forceRawInterwiki'];
3168 if ( isset( $result['isChildObj'] ) ) {
3169 $isChildObj = $result['isChildObj'];
3171 if ( isset( $result['isLocalObj'] ) ) {
3172 $isLocalObj = $result['isLocalObj'];
3177 # Finish mangling title and then check for loops.
3178 # Set $title to a Title object and $titleText to the PDBK
3181 # Split the title into page and subpage
3183 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3184 if ( $part1 !== $relative ) {
3186 $ns = $this->mTitle
->getNamespace();
3188 $title = Title
::newFromText( $part1, $ns );
3190 $titleText = $title->getPrefixedText();
3191 # Check for language variants if the template is not found
3192 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3193 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3195 # Do recursion depth check
3196 $limit = $this->mOptions
->getMaxTemplateDepth();
3197 if ( $frame->depth
>= $limit ) {
3199 $text = '<span class="error">'
3200 . wfMessage( 'parser-template-recursion-depth-warning' )
3201 ->numParams( $limit )->inContentLanguage()->text()
3207 # Load from database
3208 if ( !$found && $title ) {
3209 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3210 if ( !$title->isExternal() ) {
3211 if ( $title->isSpecialPage()
3212 && $this->mOptions
->getAllowSpecialInclusion()
3213 && $this->ot
['html']
3215 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3216 // Pass the template arguments as URL parameters.
3217 // "uselang" will have no effect since the Language object
3218 // is forced to the one defined in ParserOptions.
3220 $argsLength = $args->getLength();
3221 for ( $i = 0; $i < $argsLength; $i++
) {
3222 $bits = $args->item( $i )->splitArg();
3223 if ( strval( $bits['index'] ) === '' ) {
3224 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3225 $value = trim( $frame->expand( $bits['value'] ) );
3226 $pageArgs[$name] = $value;
3230 // Create a new context to execute the special page
3231 $context = new RequestContext
;
3232 $context->setTitle( $title );
3233 $context->setRequest( new FauxRequest( $pageArgs ) );
3234 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3235 $context->setUser( $this->getUser() );
3237 // If this page is cached, then we better not be per user.
3238 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3240 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3241 $ret = SpecialPageFactory
::capturePath(
3242 $title, $context, $this->getLinkRenderer() );
3244 $text = $context->getOutput()->getHTML();
3245 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3248 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3249 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3250 $specialPage->maxIncludeCacheTime()
3254 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3255 $found = false; # access denied
3256 wfDebug( __METHOD__
. ": template inclusion denied for " .
3257 $title->getPrefixedDBkey() . "\n" );
3259 list( $text, $title ) = $this->getTemplateDom( $title );
3260 if ( $text !== false ) {
3266 # If the title is valid but undisplayable, make a link to it
3267 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3268 $text = "[[:$titleText]]";
3271 } elseif ( $title->isTrans() ) {
3272 # Interwiki transclusion
3273 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3274 $text = $this->interwikiTransclude( $title, 'render' );
3277 $text = $this->interwikiTransclude( $title, 'raw' );
3278 # Preprocess it like a template
3279 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3285 # Do infinite loop check
3286 # This has to be done after redirect resolution to avoid infinite loops via redirects
3287 if ( !$frame->loopCheck( $title ) ) {
3289 $text = '<span class="error">'
3290 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3292 $this->addTrackingCategory( 'template-loop-category' );
3293 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3294 wfEscapeWikiText( $titleText ) )->text() );
3295 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3299 # If we haven't found text to substitute by now, we're done
3300 # Recover the source wikitext and return it
3302 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3303 if ( $profileSection ) {
3304 $this->mProfiler
->scopedProfileOut( $profileSection );
3306 return [ 'object' => $text ];
3309 # Expand DOM-style return values in a child frame
3310 if ( $isChildObj ) {
3311 # Clean up argument array
3312 $newFrame = $frame->newChild( $args, $title );
3315 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3316 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3317 # Expansion is eligible for the empty-frame cache
3318 $text = $newFrame->cachedExpand( $titleText, $text );
3320 # Uncached expansion
3321 $text = $newFrame->expand( $text );
3324 if ( $isLocalObj && $nowiki ) {
3325 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3326 $isLocalObj = false;
3329 if ( $profileSection ) {
3330 $this->mProfiler
->scopedProfileOut( $profileSection );
3333 # Replace raw HTML by a placeholder
3335 $text = $this->insertStripItem( $text );
3336 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3337 # Escape nowiki-style return values
3338 $text = wfEscapeWikiText( $text );
3339 } elseif ( is_string( $text )
3340 && !$piece['lineStart']
3341 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3343 # T2529: if the template begins with a table or block-level
3344 # element, it should be treated as beginning a new line.
3345 # This behavior is somewhat controversial.
3346 $text = "\n" . $text;
3349 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3350 # Error, oversize inclusion
3351 if ( $titleText !== false ) {
3352 # Make a working, properly escaped link if possible (T25588)
3353 $text = "[[:$titleText]]";
3355 # This will probably not be a working link, but at least it may
3356 # provide some hint of where the problem is
3357 preg_replace( '/^:/', '', $originalTitle );
3358 $text = "[[:$originalTitle]]";
3360 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3361 . 'post-expand include size too large -->' );
3362 $this->limitationWarn( 'post-expand-template-inclusion' );
3365 if ( $isLocalObj ) {
3366 $ret = [ 'object' => $text ];
3368 $ret = [ 'text' => $text ];
3375 * Call a parser function and return an array with text and flags.
3377 * The returned array will always contain a boolean 'found', indicating
3378 * whether the parser function was found or not. It may also contain the
3380 * text: string|object, resulting wikitext or PP DOM object
3381 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3382 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3383 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3384 * nowiki: bool, wiki markup in $text should be escaped
3387 * @param PPFrame $frame The current frame, contains template arguments
3388 * @param string $function Function name
3389 * @param array $args Arguments to the function
3390 * @throws MWException
3393 public function callParserFunction( $frame, $function, array $args = [] ) {
3396 # Case sensitive functions
3397 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3398 $function = $this->mFunctionSynonyms
[1][$function];
3400 # Case insensitive functions
3401 $function = $wgContLang->lc( $function );
3402 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3403 $function = $this->mFunctionSynonyms
[0][$function];
3405 return [ 'found' => false ];
3409 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3411 // Avoid PHP 7.1 warning from passing $this by reference
3414 $allArgs = [ &$parser ];
3415 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3416 # Convert arguments to PPNodes and collect for appending to $allArgs
3418 foreach ( $args as $k => $v ) {
3419 if ( $v instanceof PPNode ||
$k === 0 ) {
3422 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3426 # Add a frame parameter, and pass the arguments as an array
3427 $allArgs[] = $frame;
3428 $allArgs[] = $funcArgs;
3430 # Convert arguments to plain text and append to $allArgs
3431 foreach ( $args as $k => $v ) {
3432 if ( $v instanceof PPNode
) {
3433 $allArgs[] = trim( $frame->expand( $v ) );
3434 } elseif ( is_int( $k ) && $k >= 0 ) {
3435 $allArgs[] = trim( $v );
3437 $allArgs[] = trim( "$k=$v" );
3442 $result = $callback( ...$allArgs );
3444 # The interface for function hooks allows them to return a wikitext
3445 # string or an array containing the string and any flags. This mungs
3446 # things around to match what this method should return.
3447 if ( !is_array( $result ) ) {
3453 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3454 $result['text'] = $result[0];
3456 unset( $result[0] );
3463 $preprocessFlags = 0;
3464 if ( isset( $result['noparse'] ) ) {
3465 $noparse = $result['noparse'];
3467 if ( isset( $result['preprocessFlags'] ) ) {
3468 $preprocessFlags = $result['preprocessFlags'];
3472 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3473 $result['isChildObj'] = true;
3480 * Get the semi-parsed DOM representation of a template with a given title,
3481 * and its redirect destination title. Cached.
3483 * @param Title $title
3487 public function getTemplateDom( $title ) {
3488 $cacheTitle = $title;
3489 $titleText = $title->getPrefixedDBkey();
3491 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3492 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3493 $title = Title
::makeTitle( $ns, $dbk );
3494 $titleText = $title->getPrefixedDBkey();
3496 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3497 return [ $this->mTplDomCache
[$titleText], $title ];
3500 # Cache miss, go to the database
3501 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3503 if ( $text === false ) {
3504 $this->mTplDomCache
[$titleText] = false;
3505 return [ false, $title ];
3508 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3509 $this->mTplDomCache
[$titleText] = $dom;
3511 if ( !$title->equals( $cacheTitle ) ) {
3512 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3513 [ $title->getNamespace(), $title->getDBkey() ];
3516 return [ $dom, $title ];
3520 * Fetch the current revision of a given title. Note that the revision
3521 * (and even the title) may not exist in the database, so everything
3522 * contributing to the output of the parser should use this method
3523 * where possible, rather than getting the revisions themselves. This
3524 * method also caches its results, so using it benefits performance.
3527 * @param Title $title
3530 public function fetchCurrentRevisionOfTitle( $title ) {
3531 $cacheKey = $title->getPrefixedDBkey();
3532 if ( !$this->currentRevisionCache
) {
3533 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3535 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3536 $this->currentRevisionCache
->set( $cacheKey,
3537 // Defaults to Parser::statelessFetchRevision()
3538 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3541 return $this->currentRevisionCache
->get( $cacheKey );
3545 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3546 * without passing them on to it.
3549 * @param Title $title
3550 * @param Parser|bool $parser
3551 * @return Revision|bool False if missing
3553 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3554 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3560 * Fetch the unparsed text of a template and register a reference to it.
3561 * @param Title $title
3562 * @return array ( string or false, Title )
3564 public function fetchTemplateAndTitle( $title ) {
3565 // Defaults to Parser::statelessFetchTemplate()
3566 $templateCb = $this->mOptions
->getTemplateCallback();
3567 $stuff = call_user_func( $templateCb, $title, $this );
3568 // We use U+007F DELETE to distinguish strip markers from regular text.
3569 $text = $stuff['text'];
3570 if ( is_string( $stuff['text'] ) ) {
3571 $text = strtr( $text, "\x7f", "?" );
3573 $finalTitle = $stuff['finalTitle'] ??
$title;
3574 if ( isset( $stuff['deps'] ) ) {
3575 foreach ( $stuff['deps'] as $dep ) {
3576 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3577 if ( $dep['title']->equals( $this->getTitle() ) ) {
3578 // If we transclude ourselves, the final result
3579 // will change based on the new version of the page
3580 $this->mOutput
->setFlag( 'vary-revision' );
3584 return [ $text, $finalTitle ];
3588 * Fetch the unparsed text of a template and register a reference to it.
3589 * @param Title $title
3590 * @return string|bool
3592 public function fetchTemplate( $title ) {
3593 return $this->fetchTemplateAndTitle( $title )[0];
3597 * Static function to get a template
3598 * Can be overridden via ParserOptions::setTemplateCallback().
3600 * @param Title $title
3601 * @param bool|Parser $parser
3605 public static function statelessFetchTemplate( $title, $parser = false ) {
3606 $text = $skip = false;
3607 $finalTitle = $title;
3610 # Loop to fetch the article, with up to 1 redirect
3611 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3612 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3613 # Give extensions a chance to select the revision instead
3614 $id = false; # Assume current
3615 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3616 [ $parser, $title, &$skip, &$id ] );
3622 'page_id' => $title->getArticleID(),
3629 $rev = Revision
::newFromId( $id );
3630 } elseif ( $parser ) {
3631 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3633 $rev = Revision
::newFromTitle( $title );
3635 $rev_id = $rev ?
$rev->getId() : 0;
3636 # If there is no current revision, there is no page
3637 if ( $id === false && !$rev ) {
3638 $linkCache = LinkCache
::singleton();
3639 $linkCache->addBadLinkObj( $title );
3644 'page_id' => $title->getArticleID(),
3645 'rev_id' => $rev_id ];
3646 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3647 # We fetched a rev from a different title; register it too...
3649 'title' => $rev->getTitle(),
3650 'page_id' => $rev->getPage(),
3651 'rev_id' => $rev_id ];
3655 $content = $rev->getContent();
3656 $text = $content ?
$content->getWikitextForTransclusion() : null;
3658 Hooks
::run( 'ParserFetchTemplate',
3659 [ $parser, $title, $rev, &$text, &$deps ] );
3661 if ( $text === false ||
$text === null ) {
3665 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3667 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3668 if ( !$message->exists() ) {
3672 $content = $message->content();
3673 $text = $message->plain();
3681 $finalTitle = $title;
3682 $title = $content->getRedirectTarget();
3686 'finalTitle' => $finalTitle,
3691 * Fetch a file and its title and register a reference to it.
3692 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3693 * @param Title $title
3694 * @param array $options Array of options to RepoGroup::findFile
3696 * @deprecated since 1.32, use fetchFileAndTitle instead
3698 public function fetchFile( $title, $options = [] ) {
3699 wfDeprecated( __METHOD__
, '1.32' );
3700 return $this->fetchFileAndTitle( $title, $options )[0];
3704 * Fetch a file and its title and register a reference to it.
3705 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3706 * @param Title $title
3707 * @param array $options Array of options to RepoGroup::findFile
3708 * @return array ( File or false, Title of file )
3710 public function fetchFileAndTitle( $title, $options = [] ) {
3711 $file = $this->fetchFileNoRegister( $title, $options );
3713 $time = $file ?
$file->getTimestamp() : false;
3714 $sha1 = $file ?
$file->getSha1() : false;
3715 # Register the file as a dependency...
3716 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3717 if ( $file && !$title->equals( $file->getTitle() ) ) {
3718 # Update fetched file title
3719 $title = $file->getTitle();
3720 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3722 return [ $file, $title ];
3726 * Helper function for fetchFileAndTitle.
3728 * Also useful if you need to fetch a file but not use it yet,
3729 * for example to get the file's handler.
3731 * @param Title $title
3732 * @param array $options Array of options to RepoGroup::findFile
3735 protected function fetchFileNoRegister( $title, $options = [] ) {
3736 if ( isset( $options['broken'] ) ) {
3737 $file = false; // broken thumbnail forced by hook
3738 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3739 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3740 } else { // get by (name,timestamp)
3741 $file = wfFindFile( $title, $options );
3747 * Transclude an interwiki link.
3749 * @param Title $title
3750 * @param string $action
3754 public function interwikiTransclude( $title, $action ) {
3755 global $wgEnableScaryTranscluding;
3757 if ( !$wgEnableScaryTranscluding ) {
3758 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3761 $url = $title->getFullURL( [ 'action' => $action ] );
3763 if ( strlen( $url ) > 255 ) {
3764 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3766 return $this->fetchScaryTemplateMaybeFromCache( $url );
3770 * @param string $url
3771 * @return mixed|string
3773 public function fetchScaryTemplateMaybeFromCache( $url ) {
3774 global $wgTranscludeCacheExpiry;
3775 $dbr = wfGetDB( DB_REPLICA
);
3776 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3777 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3778 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3780 return $obj->tc_contents
;
3783 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3784 $status = $req->execute(); // Status object
3785 if ( $status->isOK() ) {
3786 $text = $req->getContent();
3787 } elseif ( $req->getStatus() != 200 ) {
3788 // Though we failed to fetch the content, this status is useless.
3789 return wfMessage( 'scarytranscludefailed-httpstatus' )
3790 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3792 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3795 $dbw = wfGetDB( DB_MASTER
);
3796 $dbw->replace( 'transcache', [ 'tc_url' ], [
3798 'tc_time' => $dbw->timestamp( time() ),
3799 'tc_contents' => $text
3805 * Triple brace replacement -- used for template arguments
3808 * @param array $piece
3809 * @param PPFrame $frame
3813 public function argSubstitution( $piece, $frame ) {
3815 $parts = $piece['parts'];
3816 $nameWithSpaces = $frame->expand( $piece['title'] );
3817 $argName = trim( $nameWithSpaces );
3819 $text = $frame->getArgument( $argName );
3820 if ( $text === false && $parts->getLength() > 0
3821 && ( $this->ot
['html']
3823 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3826 # No match in frame, use the supplied default
3827 $object = $parts->item( 0 )->getChildren();
3829 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3830 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3831 $this->limitationWarn( 'post-expand-template-argument' );
3834 if ( $text === false && $object === false ) {
3836 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3838 if ( $error !== false ) {
3841 if ( $object !== false ) {
3842 $ret = [ 'object' => $object ];
3844 $ret = [ 'text' => $text ];
3851 * Return the text to be used for a given extension tag.
3852 * This is the ghost of strip().
3854 * @param array $params Associative array of parameters:
3855 * name PPNode for the tag name
3856 * attr PPNode for unparsed text where tag attributes are thought to be
3857 * attributes Optional associative array of parsed attributes
3858 * inner Contents of extension element
3859 * noClose Original text did not have a close tag
3860 * @param PPFrame $frame
3862 * @throws MWException
3865 public function extensionSubstitution( $params, $frame ) {
3866 static $errorStr = '<span class="error">';
3867 static $errorLen = 20;
3869 $name = $frame->expand( $params['name'] );
3870 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3871 // Probably expansion depth or node count exceeded. Just punt the
3876 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3877 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3882 // We can't safely check if the expansion for $content resulted in an
3883 // error, because the content could happen to be the error string
3885 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3887 $marker = self
::MARKER_PREFIX
. "-$name-"
3888 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3890 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3891 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3892 if ( $isFunctionTag ) {
3893 $markerType = 'none';
3895 $markerType = 'general';
3897 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3898 $name = strtolower( $name );
3899 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3900 if ( isset( $params['attributes'] ) ) {
3901 $attributes = $attributes +
$params['attributes'];
3904 if ( isset( $this->mTagHooks
[$name] ) ) {
3905 $output = call_user_func_array( $this->mTagHooks
[$name],
3906 [ $content, $attributes, $this, $frame ] );
3907 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3908 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3910 // Avoid PHP 7.1 warning from passing $this by reference
3912 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3914 $output = '<span class="error">Invalid tag extension name: ' .
3915 htmlspecialchars( $name ) . '</span>';
3918 if ( is_array( $output ) ) {
3921 $output = $flags[0];
3922 if ( isset( $flags['markerType'] ) ) {
3923 $markerType = $flags['markerType'];
3927 if ( is_null( $attrText ) ) {
3930 if ( isset( $params['attributes'] ) ) {
3931 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3932 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3933 htmlspecialchars( $attrValue ) . '"';
3936 if ( $content === null ) {
3937 $output = "<$name$attrText/>";
3939 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3940 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3944 $output = "<$name$attrText>$content$close";
3948 if ( $markerType === 'none' ) {
3950 } elseif ( $markerType === 'nowiki' ) {
3951 $this->mStripState
->addNoWiki( $marker, $output );
3952 } elseif ( $markerType === 'general' ) {
3953 $this->mStripState
->addGeneral( $marker, $output );
3955 throw new MWException( __METHOD__
. ': invalid marker type' );
3961 * Increment an include size counter
3963 * @param string $type The type of expansion
3964 * @param int $size The size of the text
3965 * @return bool False if this inclusion would take it over the maximum, true otherwise
3967 public function incrementIncludeSize( $type, $size ) {
3968 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3971 $this->mIncludeSizes
[$type] +
= $size;
3977 * Increment the expensive function count
3979 * @return bool False if the limit has been exceeded
3981 public function incrementExpensiveFunctionCount() {
3982 $this->mExpensiveFunctionCount++
;
3983 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3987 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3988 * Fills $this->mDoubleUnderscores, returns the modified text
3990 * @param string $text
3994 public function doDoubleUnderscore( $text ) {
3995 # The position of __TOC__ needs to be recorded
3996 $mw = MagicWord
::get( 'toc' );
3997 if ( $mw->match( $text ) ) {
3998 $this->mShowToc
= true;
3999 $this->mForceTocPosition
= true;
4001 # Set a placeholder. At the end we'll fill it in with the TOC.
4002 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4004 # Only keep the first one.
4005 $text = $mw->replace( '', $text );
4008 # Now match and remove the rest of them
4009 $mwa = MagicWord
::getDoubleUnderscoreArray();
4010 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4012 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4013 $this->mOutput
->mNoGallery
= true;
4015 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4016 $this->mShowToc
= false;
4018 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4019 && $this->mTitle
->getNamespace() == NS_CATEGORY
4021 $this->addTrackingCategory( 'hidden-category-category' );
4023 # (T10068) Allow control over whether robots index a page.
4024 # __INDEX__ always overrides __NOINDEX__, see T16899
4025 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4026 $this->mOutput
->setIndexPolicy( 'noindex' );
4027 $this->addTrackingCategory( 'noindex-category' );
4029 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4030 $this->mOutput
->setIndexPolicy( 'index' );
4031 $this->addTrackingCategory( 'index-category' );
4034 # Cache all double underscores in the database
4035 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4036 $this->mOutput
->setProperty( $key, '' );
4043 * @see ParserOutput::addTrackingCategory()
4044 * @param string $msg Message key
4045 * @return bool Whether the addition was successful
4047 public function addTrackingCategory( $msg ) {
4048 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4052 * This function accomplishes several tasks:
4053 * 1) Auto-number headings if that option is enabled
4054 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4055 * 3) Add a Table of contents on the top for users who have enabled the option
4056 * 4) Auto-anchor headings
4058 * It loops through all headlines, collects the necessary data, then splits up the
4059 * string and re-inserts the newly formatted headlines.
4061 * @param string $text
4062 * @param string $origText Original, untouched wikitext
4063 * @param bool $isMain
4064 * @return mixed|string
4067 public function formatHeadings( $text, $origText, $isMain = true ) {
4068 global $wgMaxTocLevel;
4070 # Inhibit editsection links if requested in the page
4071 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4072 $maybeShowEditLink = false;
4074 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4077 # Get all headlines for numbering them and adding funky stuff like [edit]
4078 # links - this is for later, but we need the number of headlines right now
4079 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4080 # be trimmed here since whitespace in HTML headings is significant.
4082 $numMatches = preg_match_all(
4083 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4088 # if there are fewer than 4 headlines in the article, do not show TOC
4089 # unless it's been explicitly enabled.
4090 $enoughToc = $this->mShowToc
&&
4091 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4093 # Allow user to stipulate that a page should have a "new section"
4094 # link added via __NEWSECTIONLINK__
4095 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4096 $this->mOutput
->setNewSection( true );
4099 # Allow user to remove the "new section"
4100 # link via __NONEWSECTIONLINK__
4101 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4102 $this->mOutput
->hideNewSection( true );
4105 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4106 # override above conditions and always show TOC above first header
4107 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4108 $this->mShowToc
= true;
4116 # Ugh .. the TOC should have neat indentation levels which can be
4117 # passed to the skin functions. These are determined here
4121 $sublevelCount = [];
4127 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4128 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4129 $oldType = $this->mOutputType
;
4130 $this->setOutputType( self
::OT_WIKI
);
4131 $frame = $this->getPreprocessor()->newFrame();
4132 $root = $this->preprocessToDom( $origText );
4133 $node = $root->getFirstChild();
4138 $headlines = $numMatches !== false ?
$matches[3] : [];
4140 foreach ( $headlines as $headline ) {
4141 $isTemplate = false;
4143 $sectionIndex = false;
4145 $markerMatches = [];
4146 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4147 $serial = $markerMatches[1];
4148 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4149 $isTemplate = ( $titleText != $baseTitleText );
4150 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4154 $prevlevel = $level;
4156 $level = $matches[1][$headlineCount];
4158 if ( $level > $prevlevel ) {
4159 # Increase TOC level
4161 $sublevelCount[$toclevel] = 0;
4162 if ( $toclevel < $wgMaxTocLevel ) {
4163 $prevtoclevel = $toclevel;
4164 $toc .= Linker
::tocIndent();
4167 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4168 # Decrease TOC level, find level to jump to
4170 for ( $i = $toclevel; $i > 0; $i-- ) {
4171 if ( $levelCount[$i] == $level ) {
4172 # Found last matching level
4175 } elseif ( $levelCount[$i] < $level ) {
4176 # Found first matching level below current level
4184 if ( $toclevel < $wgMaxTocLevel ) {
4185 if ( $prevtoclevel < $wgMaxTocLevel ) {
4186 # Unindent only if the previous toc level was shown :p
4187 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4188 $prevtoclevel = $toclevel;
4190 $toc .= Linker
::tocLineEnd();
4194 # No change in level, end TOC line
4195 if ( $toclevel < $wgMaxTocLevel ) {
4196 $toc .= Linker
::tocLineEnd();
4200 $levelCount[$toclevel] = $level;
4202 # count number of headlines for each level
4203 $sublevelCount[$toclevel]++
;
4205 for ( $i = 1; $i <= $toclevel; $i++
) {
4206 if ( !empty( $sublevelCount[$i] ) ) {
4210 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4215 # The safe header is a version of the header text safe to use for links
4217 # Remove link placeholders by the link text.
4218 # <!--LINK number-->
4220 # link text with suffix
4221 # Do this before unstrip since link text can contain strip markers
4222 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4224 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4225 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4227 # Strip out HTML (first regex removes any tag not allowed)
4229 # * <sup> and <sub> (T10393)
4233 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4234 # * <s> and <strike> (T35715)
4235 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4236 # to allow setting directionality in toc items.
4237 $tocline = preg_replace(
4239 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4240 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4246 # Strip '<span></span>', which is the result from the above if
4247 # <span id="foo"></span> is used to produce an additional anchor
4249 $tocline = str_replace( '<span></span>', '', $tocline );
4251 $tocline = trim( $tocline );
4253 # For the anchor, strip out HTML-y stuff period
4254 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4255 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4257 # Save headline for section edit hint before it's escaped
4258 $headlineHint = $safeHeadline;
4260 # Decode HTML entities
4261 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4263 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4265 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4266 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4267 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4268 if ( $fallbackHeadline === $safeHeadline ) {
4269 # No reason to have both (in fact, we can't)
4270 $fallbackHeadline = false;
4273 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4274 # @todo FIXME: We may be changing them depending on the current locale.
4275 $arrayKey = strtolower( $safeHeadline );
4276 if ( $fallbackHeadline === false ) {
4277 $fallbackArrayKey = false;
4279 $fallbackArrayKey = strtolower( $fallbackHeadline );
4282 # Create the anchor for linking from the TOC to the section
4283 $anchor = $safeHeadline;
4284 $fallbackAnchor = $fallbackHeadline;
4285 if ( isset( $refers[$arrayKey] ) ) {
4286 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4287 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4289 $linkAnchor .= "_$i";
4290 $refers["${arrayKey}_$i"] = true;
4292 $refers[$arrayKey] = true;
4294 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4295 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4296 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4297 $fallbackAnchor .= "_$i";
4298 $refers["${fallbackArrayKey}_$i"] = true;
4300 $refers[$fallbackArrayKey] = true;
4303 # Don't number the heading if it is the only one (looks silly)
4304 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4305 # the two are different if the line contains a link
4306 $headline = Html
::element(
4308 [ 'class' => 'mw-headline-number' ],
4310 ) . ' ' . $headline;
4313 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4314 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4315 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4318 # Add the section to the section tree
4319 # Find the DOM node for this header
4320 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4321 while ( $node && !$noOffset ) {
4322 if ( $node->getName() === 'h' ) {
4323 $bits = $node->splitHeading();
4324 if ( $bits['i'] == $sectionIndex ) {
4328 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4329 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4330 $node = $node->getNextSibling();
4333 'toclevel' => $toclevel,
4336 'number' => $numbering,
4337 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4338 'fromtitle' => $titleText,
4339 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4340 'anchor' => $anchor,
4343 # give headline the correct <h#> tag
4344 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4345 // Output edit section links as markers with styles that can be customized by skins
4346 if ( $isTemplate ) {
4347 # Put a T flag in the section identifier, to indicate to extractSections()
4348 # that sections inside <includeonly> should be counted.
4349 $editsectionPage = $titleText;
4350 $editsectionSection = "T-$sectionIndex";
4351 $editsectionContent = null;
4353 $editsectionPage = $this->mTitle
->getPrefixedText();
4354 $editsectionSection = $sectionIndex;
4355 $editsectionContent = $headlineHint;
4357 // We use a bit of pesudo-xml for editsection markers. The
4358 // language converter is run later on. Using a UNIQ style marker
4359 // leads to the converter screwing up the tokens when it
4360 // converts stuff. And trying to insert strip tags fails too. At
4361 // this point all real inputted tags have already been escaped,
4362 // so we don't have to worry about a user trying to input one of
4363 // these markers directly. We use a page and section attribute
4364 // to stop the language converter from converting these
4365 // important bits of data, but put the headline hint inside a
4366 // content block because the language converter is supposed to
4367 // be able to convert that piece of data.
4368 // Gets replaced with html in ParserOutput::getText
4369 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4370 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4371 if ( $editsectionContent !== null ) {
4372 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4379 $head[$headlineCount] = Linker
::makeHeadline( $level,
4380 $matches['attrib'][$headlineCount], $anchor, $headline,
4381 $editlink, $fallbackAnchor );
4386 $this->setOutputType( $oldType );
4388 # Never ever show TOC if no headers
4389 if ( $numVisible < 1 ) {
4394 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4395 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4397 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4398 $this->mOutput
->setTOCHTML( $toc );
4399 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4403 $this->mOutput
->setSections( $tocraw );
4406 # split up and insert constructed headlines
4407 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4410 // build an array of document sections
4412 foreach ( $blocks as $block ) {
4413 // $head is zero-based, sections aren't.
4414 if ( empty( $head[$i - 1] ) ) {
4415 $sections[$i] = $block;
4417 $sections[$i] = $head[$i - 1] . $block;
4421 * Send a hook, one per section.
4422 * The idea here is to be able to make section-level DIVs, but to do so in a
4423 * lower-impact, more correct way than r50769
4426 * $section : the section number
4427 * &$sectionContent : ref to the content of the section
4428 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4430 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4435 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4436 // append the TOC at the beginning
4437 // Top anchor now in skin
4438 $sections[0] = $sections[0] . $toc . "\n";
4441 $full .= implode( '', $sections );
4443 if ( $this->mForceTocPosition
) {
4444 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4451 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4452 * conversion, substituting signatures, {{subst:}} templates, etc.
4454 * @param string $text The text to transform
4455 * @param Title $title The Title object for the current article
4456 * @param User $user The User object describing the current user
4457 * @param ParserOptions $options Parsing options
4458 * @param bool $clearState Whether to clear the parser state first
4459 * @return string The altered wiki markup
4461 public function preSaveTransform( $text, Title
$title, User
$user,
4462 ParserOptions
$options, $clearState = true
4464 if ( $clearState ) {
4465 $magicScopeVariable = $this->lock();
4467 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4468 $this->setUser( $user );
4470 // Strip U+0000 NULL (T159174)
4471 $text = str_replace( "\000", '', $text );
4473 // We still normalize line endings for backwards-compatibility
4474 // with other code that just calls PST, but this should already
4475 // be handled in TextContent subclasses
4476 $text = TextContent
::normalizeLineEndings( $text );
4478 if ( $options->getPreSaveTransform() ) {
4479 $text = $this->pstPass2( $text, $user );
4481 $text = $this->mStripState
->unstripBoth( $text );
4483 $this->setUser( null ); # Reset
4489 * Pre-save transform helper function
4491 * @param string $text
4496 private function pstPass2( $text, $user ) {
4499 # Note: This is the timestamp saved as hardcoded wikitext to
4500 # the database, we use $wgContLang here in order to give
4501 # everyone the same signature and use the default one rather
4502 # than the one selected in each user's preferences.
4504 $ts = $this->mOptions
->getTimestamp();
4505 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4506 $ts = $timestamp->format( 'YmdHis' );
4507 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4509 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4511 # Variable replacement
4512 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4513 $text = $this->replaceVariables( $text );
4515 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4516 # which may corrupt this parser instance via its wfMessage()->text() call-
4519 if ( strpos( $text, '~~~' ) !== false ) {
4520 $sigText = $this->getUserSig( $user );
4521 $text = strtr( $text, [
4523 '~~~~' => "$sigText $d",
4526 # The main two signature forms used above are time-sensitive
4527 $this->mOutput
->setFlag( 'user-signature' );
4530 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4531 $tc = '[' . Title
::legalChars() . ']';
4532 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4534 // [[ns:page (context)|]]
4535 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4536 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4537 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4538 // [[ns:page (context), context|]] (using either single or double-width comma)
4539 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4540 // [[|page]] (reverse pipe trick: add context from page title)
4541 $p2 = "/\[\[\\|($tc+)]]/";
4543 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4544 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4545 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4546 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4548 $t = $this->mTitle
->getText();
4550 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4551 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4552 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4553 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4555 # if there's no context, don't bother duplicating the title
4556 $text = preg_replace( $p2, '[[\\1]]', $text );
4563 * Fetch the user's signature text, if any, and normalize to
4564 * validated, ready-to-insert wikitext.
4565 * If you have pre-fetched the nickname or the fancySig option, you can
4566 * specify them here to save a database query.
4567 * Do not reuse this parser instance after calling getUserSig(),
4568 * as it may have changed if it's the $wgParser.
4570 * @param User &$user
4571 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4572 * @param bool|null $fancySig whether the nicknname is the complete signature
4573 * or null to use default value
4576 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4577 global $wgMaxSigChars;
4579 $username = $user->getName();
4581 # If not given, retrieve from the user object.
4582 if ( $nickname === false ) {
4583 $nickname = $user->getOption( 'nickname' );
4586 if ( is_null( $fancySig ) ) {
4587 $fancySig = $user->getBoolOption( 'fancysig' );
4590 $nickname = $nickname == null ?
$username : $nickname;
4592 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4593 $nickname = $username;
4594 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4595 } elseif ( $fancySig !== false ) {
4596 # Sig. might contain markup; validate this
4597 if ( $this->validateSig( $nickname ) !== false ) {
4598 # Validated; clean up (if needed) and return it
4599 return $this->cleanSig( $nickname, true );
4601 # Failed to validate; fall back to the default
4602 $nickname = $username;
4603 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4607 # Make sure nickname doesnt get a sig in a sig
4608 $nickname = self
::cleanSigInSig( $nickname );
4610 # If we're still here, make it a link to the user page
4611 $userText = wfEscapeWikiText( $username );
4612 $nickText = wfEscapeWikiText( $nickname );
4613 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4615 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4616 ->title( $this->getTitle() )->text();
4620 * Check that the user's signature contains no bad XML
4622 * @param string $text
4623 * @return string|bool An expanded string, or false if invalid.
4625 public function validateSig( $text ) {
4626 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4630 * Clean up signature text
4632 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4633 * 2) Substitute all transclusions
4635 * @param string $text
4636 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4637 * @return string Signature text
4639 public function cleanSig( $text, $parsing = false ) {
4642 $magicScopeVariable = $this->lock();
4643 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4646 # Option to disable this feature
4647 if ( !$this->mOptions
->getCleanSignatures() ) {
4651 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4652 # => Move this logic to braceSubstitution()
4653 $substWord = MagicWord
::get( 'subst' );
4654 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4655 $substText = '{{' . $substWord->getSynonym( 0 );
4657 $text = preg_replace( $substRegex, $substText, $text );
4658 $text = self
::cleanSigInSig( $text );
4659 $dom = $this->preprocessToDom( $text );
4660 $frame = $this->getPreprocessor()->newFrame();
4661 $text = $frame->expand( $dom );
4664 $text = $this->mStripState
->unstripBoth( $text );
4671 * Strip 3, 4 or 5 tildes out of signatures.
4673 * @param string $text
4674 * @return string Signature text with /~{3,5}/ removed
4676 public static function cleanSigInSig( $text ) {
4677 $text = preg_replace( '/~{3,5}/', '', $text );
4682 * Set up some variables which are usually set up in parse()
4683 * so that an external function can call some class members with confidence
4685 * @param Title|null $title
4686 * @param ParserOptions $options
4687 * @param int $outputType
4688 * @param bool $clearState
4690 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4691 $outputType, $clearState = true
4693 $this->startParse( $title, $options, $outputType, $clearState );
4697 * @param Title|null $title
4698 * @param ParserOptions $options
4699 * @param int $outputType
4700 * @param bool $clearState
4702 private function startParse( Title
$title = null, ParserOptions
$options,
4703 $outputType, $clearState = true
4705 $this->setTitle( $title );
4706 $this->mOptions
= $options;
4707 $this->setOutputType( $outputType );
4708 if ( $clearState ) {
4709 $this->clearState();
4714 * Wrapper for preprocess()
4716 * @param string $text The text to preprocess
4717 * @param ParserOptions $options
4718 * @param Title|null $title Title object or null to use $wgTitle
4721 public function transformMsg( $text, $options, $title = null ) {
4722 static $executing = false;
4724 # Guard against infinite recursion
4735 $text = $this->preprocess( $text, $title, $options );
4742 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4743 * The callback should have the following form:
4744 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4746 * Transform and return $text. Use $parser for any required context, e.g. use
4747 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4749 * Hooks may return extended information by returning an array, of which the
4750 * first numbered element (index 0) must be the return string, and all other
4751 * entries are extracted into local variables within an internal function
4752 * in the Parser class.
4754 * This interface (introduced r61913) appears to be undocumented, but
4755 * 'markerType' is used by some core tag hooks to override which strip
4756 * array their results are placed in. **Use great caution if attempting
4757 * this interface, as it is not documented and injudicious use could smash
4758 * private variables.**
4760 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4761 * @param callable $callback The callback function (and object) to use for the tag
4762 * @throws MWException
4763 * @return callable|null The old value of the mTagHooks array associated with the hook
4765 public function setHook( $tag, callable
$callback ) {
4766 $tag = strtolower( $tag );
4767 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4768 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4770 $oldVal = $this->mTagHooks
[$tag] ??
null;
4771 $this->mTagHooks
[$tag] = $callback;
4772 if ( !in_array( $tag, $this->mStripList
) ) {
4773 $this->mStripList
[] = $tag;
4780 * As setHook(), but letting the contents be parsed.
4782 * Transparent tag hooks are like regular XML-style tag hooks, except they
4783 * operate late in the transformation sequence, on HTML instead of wikitext.
4785 * This is probably obsoleted by things dealing with parser frames?
4786 * The only extension currently using it is geoserver.
4789 * @todo better document or deprecate this
4791 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4792 * @param callable $callback The callback function (and object) to use for the tag
4793 * @throws MWException
4794 * @return callable|null The old value of the mTagHooks array associated with the hook
4796 public function setTransparentTagHook( $tag, callable
$callback ) {
4797 $tag = strtolower( $tag );
4798 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4799 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4801 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4802 $this->mTransparentTagHooks
[$tag] = $callback;
4808 * Remove all tag hooks
4810 public function clearTagHooks() {
4811 $this->mTagHooks
= [];
4812 $this->mFunctionTagHooks
= [];
4813 $this->mStripList
= $this->mDefaultStripList
;
4817 * Create a function, e.g. {{sum:1|2|3}}
4818 * The callback function should have the form:
4819 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4821 * Or with Parser::SFH_OBJECT_ARGS:
4822 * function myParserFunction( $parser, $frame, $args ) { ... }
4824 * The callback may either return the text result of the function, or an array with the text
4825 * in element 0, and a number of flags in the other elements. The names of the flags are
4826 * specified in the keys. Valid flags are:
4827 * found The text returned is valid, stop processing the template. This
4829 * nowiki Wiki markup in the return value should be escaped
4830 * isHTML The returned text is HTML, armour it against wikitext transformation
4832 * @param string $id The magic word ID
4833 * @param callable $callback The callback function (and object) to use
4834 * @param int $flags A combination of the following flags:
4835 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4837 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4838 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4839 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4840 * the arguments, and to control the way they are expanded.
4842 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4843 * arguments, for instance:
4844 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4846 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4847 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4848 * working if/when this is changed.
4850 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4853 * Please read the documentation in includes/parser/Preprocessor.php for more information
4854 * about the methods available in PPFrame and PPNode.
4856 * @throws MWException
4857 * @return string|callable The old callback function for this name, if any
4859 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4862 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4863 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4865 # Add to function cache
4866 $mw = MagicWord
::get( $id );
4868 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4871 $synonyms = $mw->getSynonyms();
4872 $sensitive = intval( $mw->isCaseSensitive() );
4874 foreach ( $synonyms as $syn ) {
4876 if ( !$sensitive ) {
4877 $syn = $wgContLang->lc( $syn );
4880 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4883 # Remove trailing colon
4884 if ( substr( $syn, -1, 1 ) === ':' ) {
4885 $syn = substr( $syn, 0, -1 );
4887 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4893 * Get all registered function hook identifiers
4897 public function getFunctionHooks() {
4898 return array_keys( $this->mFunctionHooks
);
4902 * Create a tag function, e.g. "<test>some stuff</test>".
4903 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4904 * Unlike parser functions, their content is not preprocessed.
4905 * @param string $tag
4906 * @param callable $callback
4908 * @throws MWException
4911 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4912 $tag = strtolower( $tag );
4913 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4914 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4916 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4917 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4919 if ( !in_array( $tag, $this->mStripList
) ) {
4920 $this->mStripList
[] = $tag;
4927 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4928 * Placeholders created in Linker::link()
4930 * @param string &$text
4931 * @param int $options
4933 public function replaceLinkHolders( &$text, $options = 0 ) {
4934 $this->mLinkHolders
->replace( $text );
4938 * Replace "<!--LINK-->" link placeholders with plain text of links
4939 * (not HTML-formatted).
4941 * @param string $text
4944 public function replaceLinkHoldersText( $text ) {
4945 return $this->mLinkHolders
->replaceText( $text );
4949 * Renders an image gallery from a text with one line per image.
4950 * text labels may be given by using |-style alternative text. E.g.
4951 * Image:one.jpg|The number "1"
4952 * Image:tree.jpg|A tree
4953 * given as text will return the HTML of a gallery with two images,
4954 * labeled 'The number "1"' and
4957 * @param string $text
4958 * @param array $params
4959 * @return string HTML
4961 public function renderImageGallery( $text, $params ) {
4963 if ( isset( $params['mode'] ) ) {
4964 $mode = $params['mode'];
4968 $ig = ImageGalleryBase
::factory( $mode );
4969 } catch ( Exception
$e ) {
4970 // If invalid type set, fallback to default.
4971 $ig = ImageGalleryBase
::factory( false );
4974 $ig->setContextTitle( $this->mTitle
);
4975 $ig->setShowBytes( false );
4976 $ig->setShowDimensions( false );
4977 $ig->setShowFilename( false );
4978 $ig->setParser( $this );
4979 $ig->setHideBadImages();
4980 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
4982 if ( isset( $params['showfilename'] ) ) {
4983 $ig->setShowFilename( true );
4985 $ig->setShowFilename( false );
4987 if ( isset( $params['caption'] ) ) {
4988 $caption = $params['caption'];
4989 $caption = htmlspecialchars( $caption );
4990 $caption = $this->replaceInternalLinks( $caption );
4991 $ig->setCaptionHtml( $caption );
4993 if ( isset( $params['perrow'] ) ) {
4994 $ig->setPerRow( $params['perrow'] );
4996 if ( isset( $params['widths'] ) ) {
4997 $ig->setWidths( $params['widths'] );
4999 if ( isset( $params['heights'] ) ) {
5000 $ig->setHeights( $params['heights'] );
5002 $ig->setAdditionalOptions( $params );
5004 // Avoid PHP 7.1 warning from passing $this by reference
5006 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5008 $lines = StringUtils
::explode( "\n", $text );
5009 foreach ( $lines as $line ) {
5010 # match lines like these:
5011 # Image:someimage.jpg|This is some image
5013 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5015 if ( count( $matches ) == 0 ) {
5019 if ( strpos( $matches[0], '%' ) !== false ) {
5020 $matches[1] = rawurldecode( $matches[1] );
5022 $title = Title
::newFromText( $matches[1], NS_FILE
);
5023 if ( is_null( $title ) ) {
5024 # Bogus title. Ignore these so we don't bomb out later.
5028 # We need to get what handler the file uses, to figure out parameters.
5029 # Note, a hook can overide the file name, and chose an entirely different
5030 # file (which potentially could be of a different type and have different handler).
5033 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5034 [ $this, $title, &$options, &$descQuery ] );
5035 # Don't register it now, as TraditionalImageGallery does that later.
5036 $file = $this->fetchFileNoRegister( $title, $options );
5037 $handler = $file ?
$file->getHandler() : false;
5040 'img_alt' => 'gallery-internal-alt',
5041 'img_link' => 'gallery-internal-link',
5044 $paramMap = $paramMap +
$handler->getParamMap();
5045 // We don't want people to specify per-image widths.
5046 // Additionally the width parameter would need special casing anyhow.
5047 unset( $paramMap['img_width'] );
5050 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5055 $handlerOptions = [];
5056 if ( isset( $matches[3] ) ) {
5057 // look for an |alt= definition while trying not to break existing
5058 // captions with multiple pipes (|) in it, until a more sensible grammar
5059 // is defined for images in galleries
5061 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5062 // splitting on '|' is a bit odd, and different from makeImage.
5063 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5064 // Protect LanguageConverter markup
5065 $parameterMatches = StringUtils
::delimiterExplode(
5066 '-{', '}-', '|', $matches[3], true /* nested */
5069 foreach ( $parameterMatches as $parameterMatch ) {
5070 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5072 $paramName = $paramMap[$magicName];
5074 switch ( $paramName ) {
5075 case 'gallery-internal-alt':
5076 $alt = $this->stripAltText( $match, false );
5078 case 'gallery-internal-link':
5079 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5080 $chars = self
::EXT_LINK_URL_CLASS
;
5081 $addr = self
::EXT_LINK_ADDR
;
5082 $prots = $this->mUrlProtocols
;
5083 // check to see if link matches an absolute url, if not then it must be a wiki link.
5084 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5085 // Result of LanguageConverter::markNoConversion
5086 // invoked on an external link.
5087 $linkValue = substr( $linkValue, 4, -2 );
5089 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5091 $this->mOutput
->addExternalLink( $link );
5093 $localLinkTitle = Title
::newFromText( $linkValue );
5094 if ( $localLinkTitle !== null ) {
5095 $this->mOutput
->addLink( $localLinkTitle );
5096 $link = $localLinkTitle->getLinkURL();
5101 // Must be a handler specific parameter.
5102 if ( $handler->validateParam( $paramName, $match ) ) {
5103 $handlerOptions[$paramName] = $match;
5105 // Guess not, consider it as caption.
5106 wfDebug( "$parameterMatch failed parameter validation\n" );
5107 $label = $parameterMatch;
5113 $label = $parameterMatch;
5118 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5120 $html = $ig->toHTML();
5121 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5126 * @param MediaHandler $handler
5129 public function getImageParams( $handler ) {
5131 $handlerClass = get_class( $handler );
5135 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5136 # Initialise static lists
5137 static $internalParamNames = [
5138 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5139 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5140 'bottom', 'text-bottom' ],
5141 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5142 'upright', 'border', 'link', 'alt', 'class' ],
5144 static $internalParamMap;
5145 if ( !$internalParamMap ) {
5146 $internalParamMap = [];
5147 foreach ( $internalParamNames as $type => $names ) {
5148 foreach ( $names as $name ) {
5149 // For grep: img_left, img_right, img_center, img_none,
5150 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5151 // img_bottom, img_text_bottom,
5152 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5153 // img_border, img_link, img_alt, img_class
5154 $magicName = str_replace( '-', '_', "img_$name" );
5155 $internalParamMap[$magicName] = [ $type, $name ];
5160 # Add handler params
5161 $paramMap = $internalParamMap;
5163 $handlerParamMap = $handler->getParamMap();
5164 foreach ( $handlerParamMap as $magic => $paramName ) {
5165 $paramMap[$magic] = [ 'handler', $paramName ];
5168 $this->mImageParams
[$handlerClass] = $paramMap;
5169 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5171 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5175 * Parse image options text and use it to make an image
5177 * @param Title $title
5178 * @param string $options
5179 * @param LinkHolderArray|bool $holders
5180 * @return string HTML
5182 public function makeImage( $title, $options, $holders = false ) {
5183 # Check if the options text is of the form "options|alt text"
5185 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5186 # * left no resizing, just left align. label is used for alt= only
5187 # * right same, but right aligned
5188 # * none same, but not aligned
5189 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5190 # * center center the image
5191 # * frame Keep original image size, no magnify-button.
5192 # * framed Same as "frame"
5193 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5194 # * upright reduce width for upright images, rounded to full __0 px
5195 # * border draw a 1px border around the image
5196 # * alt Text for HTML alt attribute (defaults to empty)
5197 # * class Set a class for img node
5198 # * link Set the target of the image link. Can be external, interwiki, or local
5199 # vertical-align values (no % or length right now):
5209 # Protect LanguageConverter markup when splitting into parts
5210 $parts = StringUtils
::delimiterExplode(
5211 '-{', '}-', '|', $options, true /* allow nesting */
5214 # Give extensions a chance to select the file revision for us
5217 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5218 [ $this, $title, &$options, &$descQuery ] );
5219 # Fetch and register the file (file title may be different via hooks)
5220 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5223 $handler = $file ?
$file->getHandler() : false;
5225 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5228 $this->addTrackingCategory( 'broken-file-category' );
5231 # Process the input parameters
5233 $params = [ 'frame' => [], 'handler' => [],
5234 'horizAlign' => [], 'vertAlign' => [] ];
5235 $seenformat = false;
5236 foreach ( $parts as $part ) {
5237 $part = trim( $part );
5238 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5240 if ( isset( $paramMap[$magicName] ) ) {
5241 list( $type, $paramName ) = $paramMap[$magicName];
5243 # Special case; width and height come in one variable together
5244 if ( $type === 'handler' && $paramName === 'width' ) {
5245 $parsedWidthParam = self
::parseWidthParam( $value );
5246 if ( isset( $parsedWidthParam['width'] ) ) {
5247 $width = $parsedWidthParam['width'];
5248 if ( $handler->validateParam( 'width', $width ) ) {
5249 $params[$type]['width'] = $width;
5253 if ( isset( $parsedWidthParam['height'] ) ) {
5254 $height = $parsedWidthParam['height'];
5255 if ( $handler->validateParam( 'height', $height ) ) {
5256 $params[$type]['height'] = $height;
5260 # else no validation -- T15436
5262 if ( $type === 'handler' ) {
5263 # Validate handler parameter
5264 $validated = $handler->validateParam( $paramName, $value );
5266 # Validate internal parameters
5267 switch ( $paramName ) {
5271 # @todo FIXME: Possibly check validity here for
5272 # manualthumb? downstream behavior seems odd with
5273 # missing manual thumbs.
5275 $value = $this->stripAltText( $value, $holders );
5278 $chars = self
::EXT_LINK_URL_CLASS
;
5279 $addr = self
::EXT_LINK_ADDR
;
5280 $prots = $this->mUrlProtocols
;
5281 if ( $value === '' ) {
5282 $paramName = 'no-link';
5285 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5286 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5287 $paramName = 'link-url';
5288 $this->mOutput
->addExternalLink( $value );
5289 if ( $this->mOptions
->getExternalLinkTarget() ) {
5290 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5295 $linkTitle = Title
::newFromText( $value );
5297 $paramName = 'link-title';
5298 $value = $linkTitle;
5299 $this->mOutput
->addLink( $linkTitle );
5307 // use first appearing option, discard others.
5308 $validated = !$seenformat;
5312 # Most other things appear to be empty or numeric...
5313 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5318 $params[$type][$paramName] = $value;
5322 if ( !$validated ) {
5327 # Process alignment parameters
5328 if ( $params['horizAlign'] ) {
5329 $params['frame']['align'] = key( $params['horizAlign'] );
5331 if ( $params['vertAlign'] ) {
5332 $params['frame']['valign'] = key( $params['vertAlign'] );
5335 $params['frame']['caption'] = $caption;
5337 # Will the image be presented in a frame, with the caption below?
5338 $imageIsFramed = isset( $params['frame']['frame'] )
5339 ||
isset( $params['frame']['framed'] )
5340 ||
isset( $params['frame']['thumbnail'] )
5341 ||
isset( $params['frame']['manualthumb'] );
5343 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5344 # came to also set the caption, ordinary text after the image -- which
5345 # makes no sense, because that just repeats the text multiple times in
5346 # screen readers. It *also* came to set the title attribute.
5347 # Now that we have an alt attribute, we should not set the alt text to
5348 # equal the caption: that's worse than useless, it just repeats the
5349 # text. This is the framed/thumbnail case. If there's no caption, we
5350 # use the unnamed parameter for alt text as well, just for the time be-
5351 # ing, if the unnamed param is set and the alt param is not.
5352 # For the future, we need to figure out if we want to tweak this more,
5353 # e.g., introducing a title= parameter for the title; ignoring the un-
5354 # named parameter entirely for images without a caption; adding an ex-
5355 # plicit caption= parameter and preserving the old magic unnamed para-
5357 if ( $imageIsFramed ) { # Framed image
5358 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5359 # No caption or alt text, add the filename as the alt text so
5360 # that screen readers at least get some description of the image
5361 $params['frame']['alt'] = $title->getText();
5363 # Do not set $params['frame']['title'] because tooltips don't make sense
5365 } else { # Inline image
5366 if ( !isset( $params['frame']['alt'] ) ) {
5367 # No alt text, use the "caption" for the alt text
5368 if ( $caption !== '' ) {
5369 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5371 # No caption, fall back to using the filename for the
5373 $params['frame']['alt'] = $title->getText();
5376 # Use the "caption" for the tooltip text
5377 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5380 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5382 # Linker does the rest
5383 $time = $options['time'] ??
false;
5384 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5385 $time, $descQuery, $this->mOptions
->getThumbSize() );
5387 # Give the handler a chance to modify the parser object
5389 $handler->parserTransformHook( $this, $file );
5396 * @param string $caption
5397 * @param LinkHolderArray|bool $holders
5398 * @return mixed|string
5400 protected function stripAltText( $caption, $holders ) {
5401 # Strip bad stuff out of the title (tooltip). We can't just use
5402 # replaceLinkHoldersText() here, because if this function is called
5403 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5405 $tooltip = $holders->replaceText( $caption );
5407 $tooltip = $this->replaceLinkHoldersText( $caption );
5410 # make sure there are no placeholders in thumbnail attributes
5411 # that are later expanded to html- so expand them now and
5413 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5414 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5420 * Set a flag in the output object indicating that the content is dynamic and
5421 * shouldn't be cached.
5422 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5424 public function disableCache() {
5425 wfDebug( "Parser output marked as uncacheable.\n" );
5426 if ( !$this->mOutput
) {
5427 throw new MWException( __METHOD__
.
5428 " can only be called when actually parsing something" );
5430 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5434 * Callback from the Sanitizer for expanding items found in HTML attribute
5435 * values, so they can be safely tested and escaped.
5437 * @param string &$text
5438 * @param bool|PPFrame $frame
5441 public function attributeStripCallback( &$text, $frame = false ) {
5442 $text = $this->replaceVariables( $text, $frame );
5443 $text = $this->mStripState
->unstripBoth( $text );
5452 public function getTags() {
5454 array_keys( $this->mTransparentTagHooks
),
5455 array_keys( $this->mTagHooks
),
5456 array_keys( $this->mFunctionTagHooks
)
5461 * Replace transparent tags in $text with the values given by the callbacks.
5463 * Transparent tag hooks are like regular XML-style tag hooks, except they
5464 * operate late in the transformation sequence, on HTML instead of wikitext.
5466 * @param string $text
5470 public function replaceTransparentTags( $text ) {
5472 $elements = array_keys( $this->mTransparentTagHooks
);
5473 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5476 foreach ( $matches as $marker => $data ) {
5477 list( $element, $content, $params, $tag ) = $data;
5478 $tagName = strtolower( $element );
5479 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5480 $output = call_user_func_array(
5481 $this->mTransparentTagHooks
[$tagName],
5482 [ $content, $params, $this ]
5487 $replacements[$marker] = $output;
5489 return strtr( $text, $replacements );
5493 * Break wikitext input into sections, and either pull or replace
5494 * some particular section's text.
5496 * External callers should use the getSection and replaceSection methods.
5498 * @param string $text Page wikitext
5499 * @param string|int $sectionId A section identifier string of the form:
5500 * "<flag1> - <flag2> - ... - <section number>"
5502 * Currently the only recognised flag is "T", which means the target section number
5503 * was derived during a template inclusion parse, in other words this is a template
5504 * section edit link. If no flags are given, it was an ordinary section edit link.
5505 * This flag is required to avoid a section numbering mismatch when a section is
5506 * enclosed by "<includeonly>" (T8563).
5508 * The section number 0 pulls the text before the first heading; other numbers will
5509 * pull the given section along with its lower-level subsections. If the section is
5510 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5512 * Section 0 is always considered to exist, even if it only contains the empty
5513 * string. If $text is the empty string and section 0 is replaced, $newText is
5516 * @param string $mode One of "get" or "replace"
5517 * @param string $newText Replacement text for section data.
5518 * @return string For "get", the extracted section text.
5519 * for "replace", the whole page with the section replaced.
5521 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5522 global $wgTitle; # not generally used but removes an ugly failure mode
5524 $magicScopeVariable = $this->lock();
5525 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5527 $frame = $this->getPreprocessor()->newFrame();
5529 # Process section extraction flags
5531 $sectionParts = explode( '-', $sectionId );
5532 $sectionIndex = array_pop( $sectionParts );
5533 foreach ( $sectionParts as $part ) {
5534 if ( $part === 'T' ) {
5535 $flags |
= self
::PTD_FOR_INCLUSION
;
5539 # Check for empty input
5540 if ( strval( $text ) === '' ) {
5541 # Only sections 0 and T-0 exist in an empty document
5542 if ( $sectionIndex == 0 ) {
5543 if ( $mode === 'get' ) {
5549 if ( $mode === 'get' ) {
5557 # Preprocess the text
5558 $root = $this->preprocessToDom( $text, $flags );
5560 # <h> nodes indicate section breaks
5561 # They can only occur at the top level, so we can find them by iterating the root's children
5562 $node = $root->getFirstChild();
5564 # Find the target section
5565 if ( $sectionIndex == 0 ) {
5566 # Section zero doesn't nest, level=big
5567 $targetLevel = 1000;
5570 if ( $node->getName() === 'h' ) {
5571 $bits = $node->splitHeading();
5572 if ( $bits['i'] == $sectionIndex ) {
5573 $targetLevel = $bits['level'];
5577 if ( $mode === 'replace' ) {
5578 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5580 $node = $node->getNextSibling();
5586 if ( $mode === 'get' ) {
5593 # Find the end of the section, including nested sections
5595 if ( $node->getName() === 'h' ) {
5596 $bits = $node->splitHeading();
5597 $curLevel = $bits['level'];
5598 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5602 if ( $mode === 'get' ) {
5603 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5605 $node = $node->getNextSibling();
5608 # Write out the remainder (in replace mode only)
5609 if ( $mode === 'replace' ) {
5610 # Output the replacement text
5611 # Add two newlines on -- trailing whitespace in $newText is conventionally
5612 # stripped by the editor, so we need both newlines to restore the paragraph gap
5613 # Only add trailing whitespace if there is newText
5614 if ( $newText != "" ) {
5615 $outText .= $newText . "\n\n";
5619 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5620 $node = $node->getNextSibling();
5624 if ( is_string( $outText ) ) {
5625 # Re-insert stripped tags
5626 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5633 * This function returns the text of a section, specified by a number ($section).
5634 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5635 * the first section before any such heading (section 0).
5637 * If a section contains subsections, these are also returned.
5639 * @param string $text Text to look in
5640 * @param string|int $sectionId Section identifier as a number or string
5641 * (e.g. 0, 1 or 'T-1').
5642 * @param string $defaultText Default to return if section is not found
5644 * @return string Text of the requested section
5646 public function getSection( $text, $sectionId, $defaultText = '' ) {
5647 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5651 * This function returns $oldtext after the content of the section
5652 * specified by $section has been replaced with $text. If the target
5653 * section does not exist, $oldtext is returned unchanged.
5655 * @param string $oldText Former text of the article
5656 * @param string|int $sectionId Section identifier as a number or string
5657 * (e.g. 0, 1 or 'T-1').
5658 * @param string $newText Replacing text
5660 * @return string Modified text
5662 public function replaceSection( $oldText, $sectionId, $newText ) {
5663 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5667 * Get the ID of the revision we are parsing
5671 public function getRevisionId() {
5672 return $this->mRevisionId
;
5676 * Get the revision object for $this->mRevisionId
5678 * @return Revision|null Either a Revision object or null
5679 * @since 1.23 (public since 1.23)
5681 public function getRevisionObject() {
5682 if ( !is_null( $this->mRevisionObject
) ) {
5683 return $this->mRevisionObject
;
5685 if ( is_null( $this->mRevisionId
) ) {
5689 $rev = call_user_func(
5690 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5693 # If the parse is for a new revision, then the callback should have
5694 # already been set to force the object and should match mRevisionId.
5695 # If not, try to fetch by mRevisionId for sanity.
5696 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5697 $rev = Revision
::newFromId( $this->mRevisionId
);
5700 $this->mRevisionObject
= $rev;
5702 return $this->mRevisionObject
;
5706 * Get the timestamp associated with the current revision, adjusted for
5707 * the default server-local timestamp
5710 public function getRevisionTimestamp() {
5711 if ( is_null( $this->mRevisionTimestamp
) ) {
5714 $revObject = $this->getRevisionObject();
5715 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5717 # The cryptic '' timezone parameter tells to use the site-default
5718 # timezone offset instead of the user settings.
5719 # Since this value will be saved into the parser cache, served
5720 # to other users, and potentially even used inside links and such,
5721 # it needs to be consistent for all visitors.
5722 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5725 return $this->mRevisionTimestamp
;
5729 * Get the name of the user that edited the last revision
5731 * @return string User name
5733 public function getRevisionUser() {
5734 if ( is_null( $this->mRevisionUser
) ) {
5735 $revObject = $this->getRevisionObject();
5737 # if this template is subst: the revision id will be blank,
5738 # so just use the current user's name
5740 $this->mRevisionUser
= $revObject->getUserText();
5741 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5742 $this->mRevisionUser
= $this->getUser()->getName();
5745 return $this->mRevisionUser
;
5749 * Get the size of the revision
5751 * @return int|null Revision size
5753 public function getRevisionSize() {
5754 if ( is_null( $this->mRevisionSize
) ) {
5755 $revObject = $this->getRevisionObject();
5757 # if this variable is subst: the revision id will be blank,
5758 # so just use the parser input size, because the own substituation
5759 # will change the size.
5761 $this->mRevisionSize
= $revObject->getSize();
5763 $this->mRevisionSize
= $this->mInputSize
;
5766 return $this->mRevisionSize
;
5770 * Mutator for $mDefaultSort
5772 * @param string $sort New value
5774 public function setDefaultSort( $sort ) {
5775 $this->mDefaultSort
= $sort;
5776 $this->mOutput
->setProperty( 'defaultsort', $sort );
5780 * Accessor for $mDefaultSort
5781 * Will use the empty string if none is set.
5783 * This value is treated as a prefix, so the
5784 * empty string is equivalent to sorting by
5789 public function getDefaultSort() {
5790 if ( $this->mDefaultSort
!== false ) {
5791 return $this->mDefaultSort
;
5798 * Accessor for $mDefaultSort
5799 * Unlike getDefaultSort(), will return false if none is set
5801 * @return string|bool
5803 public function getCustomDefaultSort() {
5804 return $this->mDefaultSort
;
5807 private static function getSectionNameFromStrippedText( $text ) {
5808 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5809 $text = Sanitizer
::decodeCharReferences( $text );
5810 $text = self
::normalizeSectionName( $text );
5814 private static function makeAnchor( $sectionName ) {
5815 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5818 private static function makeLegacyAnchor( $sectionName ) {
5819 global $wgFragmentMode;
5820 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5821 // ForAttribute() and ForLink() are the same for legacy encoding
5822 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5824 $id = Sanitizer
::escapeIdForLink( $sectionName );
5831 * Try to guess the section anchor name based on a wikitext fragment
5832 * presumably extracted from a heading, for example "Header" from
5835 * @param string $text
5836 * @return string Anchor (starting with '#')
5838 public function guessSectionNameFromWikiText( $text ) {
5839 # Strip out wikitext links(they break the anchor)
5840 $text = $this->stripSectionName( $text );
5841 $sectionName = self
::getSectionNameFromStrippedText( $text );
5842 return self
::makeAnchor( $sectionName );
5846 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5847 * instead, if possible. For use in redirects, since various versions
5848 * of Microsoft browsers interpret Location: headers as something other
5849 * than UTF-8, resulting in breakage.
5851 * @param string $text The section name
5852 * @return string Anchor (starting with '#')
5854 public function guessLegacySectionNameFromWikiText( $text ) {
5855 # Strip out wikitext links(they break the anchor)
5856 $text = $this->stripSectionName( $text );
5857 $sectionName = self
::getSectionNameFromStrippedText( $text );
5858 return self
::makeLegacyAnchor( $sectionName );
5862 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5863 * @param string $text Section name (plain text)
5864 * @return string Anchor (starting with '#')
5866 public static function guessSectionNameFromStrippedText( $text ) {
5867 $sectionName = self
::getSectionNameFromStrippedText( $text );
5868 return self
::makeAnchor( $sectionName );
5872 * Apply the same normalization as code making links to this section would
5874 * @param string $text
5877 private static function normalizeSectionName( $text ) {
5878 # T90902: ensure the same normalization is applied for IDs as to links
5879 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5882 $parts = $titleParser->splitTitleString( "#$text" );
5883 } catch ( MalformedTitleException
$ex ) {
5886 return $parts['fragment'];
5890 * Strips a text string of wikitext for use in a section anchor
5892 * Accepts a text string and then removes all wikitext from the
5893 * string and leaves only the resultant text (i.e. the result of
5894 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5895 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5896 * to create valid section anchors by mimicing the output of the
5897 * parser when headings are parsed.
5899 * @param string $text Text string to be stripped of wikitext
5900 * for use in a Section anchor
5901 * @return string Filtered text string
5903 public function stripSectionName( $text ) {
5904 # Strip internal link markup
5905 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5906 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5908 # Strip external link markup
5909 # @todo FIXME: Not tolerant to blank link text
5910 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5911 # on how many empty links there are on the page - need to figure that out.
5912 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5914 # Parse wikitext quotes (italics & bold)
5915 $text = $this->doQuotes( $text );
5918 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5923 * strip/replaceVariables/unstrip for preprocessor regression testing
5925 * @param string $text
5926 * @param Title $title
5927 * @param ParserOptions $options
5928 * @param int $outputType
5932 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5933 $outputType = self
::OT_HTML
5935 $magicScopeVariable = $this->lock();
5936 $this->startParse( $title, $options, $outputType, true );
5938 $text = $this->replaceVariables( $text );
5939 $text = $this->mStripState
->unstripBoth( $text );
5940 $text = Sanitizer
::removeHTMLtags( $text );
5945 * @param string $text
5946 * @param Title $title
5947 * @param ParserOptions $options
5950 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5951 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5955 * @param string $text
5956 * @param Title $title
5957 * @param ParserOptions $options
5960 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5961 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5965 * Call a callback function on all regions of the given text that are not
5966 * inside strip markers, and replace those regions with the return value
5967 * of the callback. For example, with input:
5971 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5972 * two strings will be replaced with the value returned by the callback in
5976 * @param callable $callback
5980 public function markerSkipCallback( $s, $callback ) {
5983 while ( $i < strlen( $s ) ) {
5984 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
5985 if ( $markerStart === false ) {
5986 $out .= call_user_func( $callback, substr( $s, $i ) );
5989 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5990 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5991 if ( $markerEnd === false ) {
5992 $out .= substr( $s, $markerStart );
5995 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5996 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6005 * Remove any strip markers found in the given text.
6007 * @param string $text
6010 public function killMarkers( $text ) {
6011 return $this->mStripState
->killMarkers( $text );
6015 * Save the parser state required to convert the given half-parsed text to
6016 * HTML. "Half-parsed" in this context means the output of
6017 * recursiveTagParse() or internalParse(). This output has strip markers
6018 * from replaceVariables (extensionSubstitution() etc.), and link
6019 * placeholders from replaceLinkHolders().
6021 * Returns an array which can be serialized and stored persistently. This
6022 * array can later be loaded into another parser instance with
6023 * unserializeHalfParsedText(). The text can then be safely incorporated into
6024 * the return value of a parser hook.
6026 * @deprecated since 1.31
6027 * @param string $text
6031 public function serializeHalfParsedText( $text ) {
6032 wfDeprecated( __METHOD__
, '1.31' );
6035 'version' => self
::HALF_PARSED_VERSION
,
6036 'stripState' => $this->mStripState
->getSubState( $text ),
6037 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6043 * Load the parser state given in the $data array, which is assumed to
6044 * have been generated by serializeHalfParsedText(). The text contents is
6045 * extracted from the array, and its markers are transformed into markers
6046 * appropriate for the current Parser instance. This transformed text is
6047 * returned, and can be safely included in the return value of a parser
6050 * If the $data array has been stored persistently, the caller should first
6051 * check whether it is still valid, by calling isValidHalfParsedText().
6053 * @deprecated since 1.31
6054 * @param array $data Serialized data
6055 * @throws MWException
6058 public function unserializeHalfParsedText( $data ) {
6059 wfDeprecated( __METHOD__
, '1.31' );
6060 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6061 throw new MWException( __METHOD__
. ': invalid version' );
6064 # First, extract the strip state.
6065 $texts = [ $data['text'] ];
6066 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6068 # Now renumber links
6069 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6071 # Should be good to go.
6076 * Returns true if the given array, presumed to be generated by
6077 * serializeHalfParsedText(), is compatible with the current version of the
6080 * @deprecated since 1.31
6081 * @param array $data
6085 public function isValidHalfParsedText( $data ) {
6086 wfDeprecated( __METHOD__
, '1.31' );
6087 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6091 * Parsed a width param of imagelink like 300px or 200x300px
6093 * @param string $value
6094 * @param bool $parseHeight
6099 public static function parseWidthParam( $value, $parseHeight = true ) {
6100 $parsedWidthParam = [];
6101 if ( $value === '' ) {
6102 return $parsedWidthParam;
6105 # (T15500) In both cases (width/height and width only),
6106 # permit trailing "px" for backward compatibility.
6107 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6108 $width = intval( $m[1] );
6109 $height = intval( $m[2] );
6110 $parsedWidthParam['width'] = $width;
6111 $parsedWidthParam['height'] = $height;
6112 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6113 $width = intval( $value );
6114 $parsedWidthParam['width'] = $width;
6116 return $parsedWidthParam;
6120 * Lock the current instance of the parser.
6122 * This is meant to stop someone from calling the parser
6123 * recursively and messing up all the strip state.
6125 * @throws MWException If parser is in a parse
6126 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6128 protected function lock() {
6129 if ( $this->mInParse
) {
6130 throw new MWException( "Parser state cleared while parsing. "
6131 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6134 // Save the backtrace when locking, so that if some code tries locking again,
6135 // we can print the lock owner's backtrace for easier debugging
6137 $this->mInParse
= $e->getTraceAsString();
6139 $recursiveCheck = new ScopedCallback( function () {
6140 $this->mInParse
= false;
6143 return $recursiveCheck;
6147 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6149 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6150 * or if there is more than one <p/> tag in the input HTML.
6152 * @param string $html
6156 public static function stripOuterParagraph( $html ) {
6158 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6159 if ( strpos( $m[1], '</p>' ) === false ) {
6168 * Return this parser if it is not doing anything, otherwise
6169 * get a fresh parser. You can use this method by doing
6170 * $myParser = $wgParser->getFreshParser(), or more simply
6171 * $wgParser->getFreshParser()->parse( ... );
6172 * if you're unsure if $wgParser is safe to use.
6175 * @return Parser A parser object that is not parsing anything
6177 public function getFreshParser() {
6178 global $wgParserConf;
6179 if ( $this->mInParse
) {
6180 return new $wgParserConf['class']( $wgParserConf );
6187 * Set's up the PHP implementation of OOUI for use in this request
6188 * and instructs OutputPage to enable OOUI for itself.
6192 public function enableOOUI() {
6193 OutputPage
::setupOOUI();
6194 $this->mOutput
->setEnableOOUI( true );