3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @defgroup Parser Parser
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
37 * There are seven main entry points into the Parser class:
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
89 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
90 # uses to replace invalid HTML characters.
91 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
92 # Simplified expression to match an IPv4 or IPv6 address, or
93 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
94 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
95 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
96 // phpcs:ignore Generic.Files.LineLength
97 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
98 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
100 # Regular expression for a non-newline space
101 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
103 # Flags for preprocessToDom
104 const PTD_FOR_INCLUSION
= 1;
106 # Allowed values for $this->mOutputType
107 # Parameter to startExternalParse().
108 const OT_HTML
= 1; # like parse()
109 const OT_WIKI
= 2; # like preSaveTransform()
110 const OT_PREPROCESS
= 3; # like preprocess()
112 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 * @var string Prefix and suffix for temporary replacement strings
116 * for the multipass parser.
118 * \x7f should never appear in input as it's disallowed in XML.
119 * Using it at the front also gives us a little extra robustness
120 * since it shouldn't match when butted up against identifier-like
123 * Must not consist of all title characters, or else it will change
124 * the behavior of <nowiki> in a link.
126 * Must have a character that needs escaping in attributes, otherwise
127 * someone could put a strip marker in an attribute, to get around
128 * escaping quote marks, and break out of the attribute. Thus we add
131 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
132 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
134 # Markers used for wrapping the table of contents
135 const TOC_START
= '<mw:toc>';
136 const TOC_END
= '</mw:toc>';
138 /** @var int Assume that no output will later be saved this many seconds after parsing */
142 public $mTagHooks = [];
143 public $mTransparentTagHooks = [];
144 public $mFunctionHooks = [];
145 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
146 public $mFunctionTagHooks = [];
147 public $mStripList = [];
148 public $mDefaultStripList = [];
149 public $mVarCache = [];
150 public $mImageParams = [];
151 public $mImageParamsMagicArray = [];
152 public $mMarkerIndex = 0;
153 public $mFirstCall = true;
155 # Initialised by initialiseVariables()
158 * @var MagicWordArray
163 * @var MagicWordArray
166 # Initialised in constructor
167 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
169 # Initialized in getPreprocessor()
170 /** @var Preprocessor */
171 public $mPreprocessor;
173 # Cleared with clearState():
185 public $mIncludeCount;
187 * @var LinkHolderArray
189 public $mLinkHolders;
192 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
193 public $mDefaultSort;
194 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
195 public $mExpensiveFunctionCount; # number of expensive parser function calls
196 public $mShowToc, $mForceTocPosition;
201 public $mUser; # User object; only used when doing pre-save transform
204 # These are variables reset at least once per parse regardless of $clearState
214 public $mTitle; # Title context, used for self-link rendering and similar things
215 public $mOutputType; # Output type, one of the OT_xxx constants
216 public $ot; # Shortcut alias, see setOutputType()
217 public $mRevisionObject; # The revision object of the specified revision ID
218 public $mRevisionId; # ID to display in {{REVISIONID}} tags
219 public $mRevisionTimestamp; # The timestamp of the specified revision ID
220 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
221 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
222 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
223 public $mInputSize = false; # For {{PAGESIZE}} on current page.
226 * @var string Deprecated accessor for the strip marker prefix.
227 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
229 public $mUniqPrefix = self
::MARKER_PREFIX
;
232 * @var array Array with the language name of each language link (i.e. the
233 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
234 * duplicate language links to the ParserOutput.
236 public $mLangLinkLanguages;
239 * @var MapCacheLRU|null
242 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
244 public $currentRevisionCache;
247 * @var bool|string Recursive call protection.
248 * This variable should be treated as if it were private.
250 public $mInParse = false;
252 /** @var SectionProfiler */
253 protected $mProfiler;
258 protected $mLinkRenderer;
260 /** @var MagicWordFactory */
261 private $magicWordFactory;
265 * @param MagicWordFactory|null $magicWordFactory
267 public function __construct( $conf = [], MagicWordFactory
$magicWordFactory = null ) {
268 $this->mConf
= $conf;
269 $this->mUrlProtocols
= wfUrlProtocols();
270 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
271 self
::EXT_LINK_ADDR
.
272 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
273 if ( isset( $conf['preprocessorClass'] ) ) {
274 $this->mPreprocessorClass
= $conf['preprocessorClass'];
275 } elseif ( defined( 'HPHP_VERSION' ) ) {
276 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
277 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
278 } elseif ( extension_loaded( 'domxml' ) ) {
279 # PECL extension that conflicts with the core DOM extension (T15770)
280 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
281 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
282 } elseif ( extension_loaded( 'dom' ) ) {
283 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
285 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
287 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
289 $this->magicWordFactory
= $magicWordFactory;
290 if ( !$magicWordFactory ) {
291 $this->magicWordFactory
= MediaWikiServices
::getInstance()->getMagicWordFactory();
296 * Reduce memory usage to reduce the impact of circular references
298 public function __destruct() {
299 if ( isset( $this->mLinkHolders
) ) {
300 unset( $this->mLinkHolders
);
302 foreach ( $this as $name => $value ) {
303 unset( $this->$name );
308 * Allow extensions to clean up when the parser is cloned
310 public function __clone() {
311 $this->mInParse
= false;
313 // T58226: When you create a reference "to" an object field, that
314 // makes the object field itself be a reference too (until the other
315 // reference goes out of scope). When cloning, any field that's a
316 // reference is copied as a reference in the new object. Both of these
317 // are defined PHP5 behaviors, as inconvenient as it is for us when old
318 // hooks from PHP4 days are passing fields by reference.
319 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
320 // Make a non-reference copy of the field, then rebind the field to
321 // reference the new copy.
327 Hooks
::run( 'ParserCloned', [ $this ] );
331 * Do various kinds of initialisation on the first call of the parser
333 public function firstCallInit() {
334 if ( !$this->mFirstCall
) {
337 $this->mFirstCall
= false;
339 CoreParserFunctions
::register( $this );
340 CoreTagHooks
::register( $this );
341 $this->initialiseVariables();
343 // Avoid PHP 7.1 warning from passing $this by reference
345 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
353 public function clearState() {
354 if ( $this->mFirstCall
) {
355 $this->firstCallInit();
357 $this->mOutput
= new ParserOutput
;
358 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
359 $this->mAutonumber
= 0;
360 $this->mIncludeCount
= [];
361 $this->mLinkHolders
= new LinkHolderArray( $this );
363 $this->mRevisionObject
= $this->mRevisionTimestamp
=
364 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
365 $this->mVarCache
= [];
367 $this->mLangLinkLanguages
= [];
368 $this->currentRevisionCache
= null;
370 $this->mStripState
= new StripState( $this );
372 # Clear these on every parse, T6549
373 $this->mTplRedirCache
= $this->mTplDomCache
= [];
375 $this->mShowToc
= true;
376 $this->mForceTocPosition
= false;
377 $this->mIncludeSizes
= [
381 $this->mPPNodeCount
= 0;
382 $this->mGeneratedPPNodeCount
= 0;
383 $this->mHighestExpansionDepth
= 0;
384 $this->mDefaultSort
= false;
385 $this->mHeadings
= [];
386 $this->mDoubleUnderscores
= [];
387 $this->mExpensiveFunctionCount
= 0;
390 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
391 $this->mPreprocessor
= null;
394 $this->mProfiler
= new SectionProfiler();
396 // Avoid PHP 7.1 warning from passing $this by reference
398 Hooks
::run( 'ParserClearState', [ &$parser ] );
402 * Convert wikitext to HTML
403 * Do not call this function recursively.
405 * @param string $text Text we want to parse
406 * @param Title $title
407 * @param ParserOptions $options
408 * @param bool $linestart
409 * @param bool $clearState
410 * @param int|null $revid Number to pass in {{REVISIONID}}
411 * @return ParserOutput A ParserOutput
413 public function parse(
414 $text, Title
$title, ParserOptions
$options,
415 $linestart = true, $clearState = true, $revid = null
418 // We use U+007F DELETE to construct strip markers, so we have to make
419 // sure that this character does not occur in the input text.
420 $text = strtr( $text, "\x7f", "?" );
421 $magicScopeVariable = $this->lock();
423 // Strip U+0000 NULL (T159174)
424 $text = str_replace( "\000", '', $text );
426 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
428 $this->currentRevisionCache
= null;
429 $this->mInputSize
= strlen( $text );
430 if ( $this->mOptions
->getEnableLimitReport() ) {
431 $this->mOutput
->resetParseStartTime();
434 $oldRevisionId = $this->mRevisionId
;
435 $oldRevisionObject = $this->mRevisionObject
;
436 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
437 $oldRevisionUser = $this->mRevisionUser
;
438 $oldRevisionSize = $this->mRevisionSize
;
439 if ( $revid !== null ) {
440 $this->mRevisionId
= $revid;
441 $this->mRevisionObject
= null;
442 $this->mRevisionTimestamp
= null;
443 $this->mRevisionUser
= null;
444 $this->mRevisionSize
= null;
447 // Avoid PHP 7.1 warning from passing $this by reference
449 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
451 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
452 $text = $this->internalParse( $text );
453 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
455 $text = $this->internalParseHalfParsed( $text, true, $linestart );
458 * A converted title will be provided in the output object if title and
459 * content conversion are enabled, the article text does not contain
460 * a conversion-suppressing double-underscore tag, and no
461 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
462 * automatic link conversion.
464 if ( !( $options->getDisableTitleConversion()
465 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
466 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
467 ||
$this->mOutput
->getDisplayTitle() !== false )
469 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
470 if ( $convruletitle ) {
471 $this->mOutput
->setTitleText( $convruletitle );
473 $titleText = $this->getTargetLanguage()->convertTitle( $title );
474 $this->mOutput
->setTitleText( $titleText );
478 # Compute runtime adaptive expiry if set
479 $this->mOutput
->finalizeAdaptiveCacheExpiry();
481 # Warn if too many heavyweight parser functions were used
482 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
483 $this->limitationWarn( 'expensive-parserfunction',
484 $this->mExpensiveFunctionCount
,
485 $this->mOptions
->getExpensiveParserFunctionLimit()
489 # Information on limits, for the benefit of users who try to skirt them
490 if ( $this->mOptions
->getEnableLimitReport() ) {
491 $text .= $this->makeLimitReport();
494 # Wrap non-interface parser output in a <div> so it can be targeted
496 $class = $this->mOptions
->getWrapOutputClass();
497 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
498 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
501 $this->mOutput
->setText( $text );
503 $this->mRevisionId
= $oldRevisionId;
504 $this->mRevisionObject
= $oldRevisionObject;
505 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
506 $this->mRevisionUser
= $oldRevisionUser;
507 $this->mRevisionSize
= $oldRevisionSize;
508 $this->mInputSize
= false;
509 $this->currentRevisionCache
= null;
511 return $this->mOutput
;
515 * Set the limit report data in the current ParserOutput, and return the
516 * limit report HTML comment.
520 protected function makeLimitReport() {
521 global $wgShowHostnames;
523 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
525 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
526 if ( $cpuTime !== null ) {
527 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
528 sprintf( "%.3f", $cpuTime )
532 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
533 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
534 sprintf( "%.3f", $wallTime )
537 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
538 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
540 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
541 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
543 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
544 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
546 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
547 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
549 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
550 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
552 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
553 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
556 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
557 $this->mOutput
->setLimitReportData( $key, $value );
560 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
562 $limitReport = "NewPP limit report\n";
563 if ( $wgShowHostnames ) {
564 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
566 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
567 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
568 $limitReport .= 'Dynamic content: ' .
569 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
572 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
573 if ( Hooks
::run( 'ParserLimitReportFormat',
574 [ $key, &$value, &$limitReport, false, false ]
576 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
577 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
578 ->inLanguage( 'en' )->useDatabase( false );
579 if ( !$valueMsg->exists() ) {
580 $valueMsg = new RawMessage( '$1' );
582 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
583 $valueMsg->params( $value );
584 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
588 // Since we're not really outputting HTML, decode the entities and
589 // then re-encode the things that need hiding inside HTML comments.
590 $limitReport = htmlspecialchars_decode( $limitReport );
591 // Run deprecated hook
592 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
594 // Sanitize for comment. Note '‐' in the replacement is U+2010,
595 // which looks much like the problematic '-'.
596 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
597 $text = "\n<!-- \n$limitReport-->\n";
599 // Add on template profiling data in human/machine readable way
600 $dataByFunc = $this->mProfiler
->getFunctionStats();
601 uasort( $dataByFunc, function ( $a, $b ) {
602 return $b['real'] <=> $a['real']; // descending order
605 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
606 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
607 $item['%real'], $item['real'], $item['calls'],
608 htmlspecialchars( $item['name'] ) );
610 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
611 $text .= implode( "\n", $profileReport ) . "\n-->\n";
613 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
615 // Add other cache related metadata
616 if ( $wgShowHostnames ) {
617 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
619 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
620 $this->mOutput
->getCacheTime() );
621 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
622 $this->mOutput
->getCacheExpiry() );
623 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
624 $this->mOutput
->hasDynamicContent() );
626 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
627 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
628 $this->mTitle
->getPrefixedDBkey() );
634 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
635 * can be called from an extension tag hook.
637 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
638 * instead, which means that lists and links have not been fully parsed yet,
639 * and strip markers are still present.
641 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
643 * Use this function if you're a parser tag hook and you want to parse
644 * wikitext before or after applying additional transformations, and you
645 * intend to *return the result as hook output*, which will cause it to go
646 * through the rest of parsing process automatically.
648 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
649 * $text are not expanded
651 * @param string $text Text extension wants to have parsed
652 * @param bool|PPFrame $frame The frame to use for expanding any template variables
653 * @return string UNSAFE half-parsed HTML
655 public function recursiveTagParse( $text, $frame = false ) {
656 // Avoid PHP 7.1 warning from passing $this by reference
658 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
659 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
660 $text = $this->internalParse( $text, false, $frame );
665 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
666 * point can be called from an extension tag hook.
668 * The output of this function is fully-parsed HTML that is safe for output.
669 * If you're a parser tag hook, you might want to use recursiveTagParse()
672 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
673 * $text are not expanded
677 * @param string $text Text extension wants to have parsed
678 * @param bool|PPFrame $frame The frame to use for expanding any template variables
679 * @return string Fully parsed HTML
681 public function recursiveTagParseFully( $text, $frame = false ) {
682 $text = $this->recursiveTagParse( $text, $frame );
683 $text = $this->internalParseHalfParsed( $text, false );
688 * Expand templates and variables in the text, producing valid, static wikitext.
689 * Also removes comments.
690 * Do not call this function recursively.
691 * @param string $text
692 * @param Title|null $title
693 * @param ParserOptions $options
694 * @param int|null $revid
695 * @param bool|PPFrame $frame
696 * @return mixed|string
698 public function preprocess( $text, Title
$title = null,
699 ParserOptions
$options, $revid = null, $frame = false
701 $magicScopeVariable = $this->lock();
702 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
703 if ( $revid !== null ) {
704 $this->mRevisionId
= $revid;
706 // Avoid PHP 7.1 warning from passing $this by reference
708 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
709 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
710 $text = $this->replaceVariables( $text, $frame );
711 $text = $this->mStripState
->unstripBoth( $text );
716 * Recursive parser entry point that can be called from an extension tag
719 * @param string $text Text to be expanded
720 * @param bool|PPFrame $frame The frame to use for expanding any template variables
724 public function recursivePreprocess( $text, $frame = false ) {
725 $text = $this->replaceVariables( $text, $frame );
726 $text = $this->mStripState
->unstripBoth( $text );
731 * Process the wikitext for the "?preload=" feature. (T7210)
733 * "<noinclude>", "<includeonly>" etc. are parsed as for template
734 * transclusion, comments, templates, arguments, tags hooks and parser
735 * functions are untouched.
737 * @param string $text
738 * @param Title $title
739 * @param ParserOptions $options
740 * @param array $params
743 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
744 $msg = new RawMessage( $text );
745 $text = $msg->params( $params )->plain();
747 # Parser (re)initialisation
748 $magicScopeVariable = $this->lock();
749 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
751 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
752 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
753 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
754 $text = $this->mStripState
->unstripBoth( $text );
759 * Set the current user.
760 * Should only be used when doing pre-save transform.
762 * @param User|null $user User object or null (to reset)
764 public function setUser( $user ) {
765 $this->mUser
= $user;
769 * Set the context title
773 public function setTitle( $t ) {
775 $t = Title
::newFromText( 'NO TITLE' );
778 if ( $t->hasFragment() ) {
779 # Strip the fragment to avoid various odd effects
780 $this->mTitle
= $t->createFragmentTarget( '' );
787 * Accessor for the Title object
791 public function getTitle() {
792 return $this->mTitle
;
796 * Accessor/mutator for the Title object
798 * @param Title|null $x Title object or null to just get the current one
801 public function Title( $x = null ) {
802 return wfSetVar( $this->mTitle
, $x );
806 * Set the output type
808 * @param int $ot New value
810 public function setOutputType( $ot ) {
811 $this->mOutputType
= $ot;
814 'html' => $ot == self
::OT_HTML
,
815 'wiki' => $ot == self
::OT_WIKI
,
816 'pre' => $ot == self
::OT_PREPROCESS
,
817 'plain' => $ot == self
::OT_PLAIN
,
822 * Accessor/mutator for the output type
824 * @param int|null $x New value or null to just get the current one
827 public function OutputType( $x = null ) {
828 return wfSetVar( $this->mOutputType
, $x );
832 * Get the ParserOutput object
834 * @return ParserOutput
836 public function getOutput() {
837 return $this->mOutput
;
841 * Get the ParserOptions object
843 * @return ParserOptions
845 public function getOptions() {
846 return $this->mOptions
;
850 * Accessor/mutator for the ParserOptions object
852 * @param ParserOptions|null $x New value or null to just get the current one
853 * @return ParserOptions Current ParserOptions object
855 public function Options( $x = null ) {
856 return wfSetVar( $this->mOptions
, $x );
862 public function nextLinkID() {
863 return $this->mLinkID++
;
869 public function setLinkID( $id ) {
870 $this->mLinkID
= $id;
874 * Get a language object for use in parser functions such as {{FORMATNUM:}}
877 public function getFunctionLang() {
878 return $this->getTargetLanguage();
882 * Get the target language for the content being parsed. This is usually the
883 * language that the content is in.
887 * @throws MWException
890 public function getTargetLanguage() {
891 $target = $this->mOptions
->getTargetLanguage();
893 if ( $target !== null ) {
895 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
896 return $this->mOptions
->getUserLangObj();
897 } elseif ( is_null( $this->mTitle
) ) {
898 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
901 return $this->mTitle
->getPageLanguage();
905 * Get the language object for language conversion
906 * @deprecated since 1.32, just use getTargetLanguage()
907 * @return Language|null
909 public function getConverterLanguage() {
910 return $this->getTargetLanguage();
914 * Get a User object either from $this->mUser, if set, or from the
915 * ParserOptions object otherwise
919 public function getUser() {
920 if ( !is_null( $this->mUser
) ) {
923 return $this->mOptions
->getUser();
927 * Get a preprocessor object
929 * @return Preprocessor
931 public function getPreprocessor() {
932 if ( !isset( $this->mPreprocessor
) ) {
933 $class = $this->mPreprocessorClass
;
934 $this->mPreprocessor
= new $class( $this );
936 return $this->mPreprocessor
;
940 * Get a LinkRenderer instance to make links with
943 * @return LinkRenderer
945 public function getLinkRenderer() {
946 if ( !$this->mLinkRenderer
) {
947 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
948 ->getLinkRendererFactory()->create();
949 $this->mLinkRenderer
->setStubThreshold(
950 $this->getOptions()->getStubThreshold()
954 return $this->mLinkRenderer
;
958 * Get the MagicWordFactory that this Parser is using
961 * @return MagicWordFactory
963 public function getMagicWordFactory() {
964 return $this->magicWordFactory
;
968 * Get the content language that this Parser is using
973 public function getContentLanguage() {
974 return $this->magicWordFactory
->getContentLanguage();
978 * Replaces all occurrences of HTML-style comments and the given tags
979 * in the text with a random marker and returns the next text. The output
980 * parameter $matches will be an associative array filled with data in
987 * [ 'param' => 'x' ],
988 * '<element param="x">tag content</element>' ]
991 * @param array $elements List of element names. Comments are always extracted.
992 * @param string $text Source text string.
993 * @param array &$matches Out parameter, Array: extracted tags
994 * @return string Stripped text
996 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1001 $taglist = implode( '|', $elements );
1002 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
1004 while ( $text != '' ) {
1005 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1007 if ( count( $p ) < 5 ) {
1010 if ( count( $p ) > 5 ) {
1019 $attributes = $p[2];
1024 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1025 $stripped .= $marker;
1027 if ( $close === '/>' ) {
1028 # Empty element tag, <tag />
1033 if ( $element === '!--' ) {
1036 $end = "/(<\\/$element\\s*>)/i";
1038 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1040 if ( count( $q ) < 3 ) {
1041 # No end tag -- let it run out to the end of the text.
1050 $matches[$marker] = [ $element,
1052 Sanitizer
::decodeTagAttributes( $attributes ),
1053 "<$element$attributes$close$content$tail" ];
1059 * Get a list of strippable XML-like elements
1063 public function getStripList() {
1064 return $this->mStripList
;
1068 * Add an item to the strip state
1069 * Returns the unique tag which must be inserted into the stripped text
1070 * The tag will be replaced with the original text in unstrip()
1072 * @param string $text
1076 public function insertStripItem( $text ) {
1077 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1078 $this->mMarkerIndex++
;
1079 $this->mStripState
->addGeneral( $marker, $text );
1084 * parse the wiki syntax used to render tables
1087 * @param string $text
1090 public function doTableStuff( $text ) {
1091 $lines = StringUtils
::explode( "\n", $text );
1093 $td_history = []; # Is currently a td tag open?
1094 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1095 $tr_history = []; # Is currently a tr tag open?
1096 $tr_attributes = []; # history of tr attributes
1097 $has_opened_tr = []; # Did this table open a <tr> element?
1098 $indent_level = 0; # indent level of the table
1100 foreach ( $lines as $outLine ) {
1101 $line = trim( $outLine );
1103 if ( $line === '' ) { # empty line, go to next line
1104 $out .= $outLine . "\n";
1108 $first_character = $line[0];
1109 $first_two = substr( $line, 0, 2 );
1112 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1113 # First check if we are starting a new table
1114 $indent_level = strlen( $matches[1] );
1116 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1117 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1119 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1120 array_push( $td_history, false );
1121 array_push( $last_tag_history, '' );
1122 array_push( $tr_history, false );
1123 array_push( $tr_attributes, '' );
1124 array_push( $has_opened_tr, false );
1125 } elseif ( count( $td_history ) == 0 ) {
1126 # Don't do any of the following
1127 $out .= $outLine . "\n";
1129 } elseif ( $first_two === '|}' ) {
1130 # We are ending a table
1131 $line = '</table>' . substr( $line, 2 );
1132 $last_tag = array_pop( $last_tag_history );
1134 if ( !array_pop( $has_opened_tr ) ) {
1135 $line = "<tr><td></td></tr>{$line}";
1138 if ( array_pop( $tr_history ) ) {
1139 $line = "</tr>{$line}";
1142 if ( array_pop( $td_history ) ) {
1143 $line = "</{$last_tag}>{$line}";
1145 array_pop( $tr_attributes );
1146 if ( $indent_level > 0 ) {
1147 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1151 } elseif ( $first_two === '|-' ) {
1152 # Now we have a table row
1153 $line = preg_replace( '#^\|-+#', '', $line );
1155 # Whats after the tag is now only attributes
1156 $attributes = $this->mStripState
->unstripBoth( $line );
1157 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1158 array_pop( $tr_attributes );
1159 array_push( $tr_attributes, $attributes );
1162 $last_tag = array_pop( $last_tag_history );
1163 array_pop( $has_opened_tr );
1164 array_push( $has_opened_tr, true );
1166 if ( array_pop( $tr_history ) ) {
1170 if ( array_pop( $td_history ) ) {
1171 $line = "</{$last_tag}>{$line}";
1175 array_push( $tr_history, false );
1176 array_push( $td_history, false );
1177 array_push( $last_tag_history, '' );
1178 } elseif ( $first_character === '|'
1179 ||
$first_character === '!'
1180 ||
$first_two === '|+'
1182 # This might be cell elements, td, th or captions
1183 if ( $first_two === '|+' ) {
1184 $first_character = '+';
1185 $line = substr( $line, 2 );
1187 $line = substr( $line, 1 );
1190 // Implies both are valid for table headings.
1191 if ( $first_character === '!' ) {
1192 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1195 # Split up multiple cells on the same line.
1196 # FIXME : This can result in improper nesting of tags processed
1197 # by earlier parser steps.
1198 $cells = explode( '||', $line );
1202 # Loop through each table cell
1203 foreach ( $cells as $cell ) {
1205 if ( $first_character !== '+' ) {
1206 $tr_after = array_pop( $tr_attributes );
1207 if ( !array_pop( $tr_history ) ) {
1208 $previous = "<tr{$tr_after}>\n";
1210 array_push( $tr_history, true );
1211 array_push( $tr_attributes, '' );
1212 array_pop( $has_opened_tr );
1213 array_push( $has_opened_tr, true );
1216 $last_tag = array_pop( $last_tag_history );
1218 if ( array_pop( $td_history ) ) {
1219 $previous = "</{$last_tag}>\n{$previous}";
1222 if ( $first_character === '|' ) {
1224 } elseif ( $first_character === '!' ) {
1226 } elseif ( $first_character === '+' ) {
1227 $last_tag = 'caption';
1232 array_push( $last_tag_history, $last_tag );
1234 # A cell could contain both parameters and data
1235 $cell_data = explode( '|', $cell, 2 );
1237 # T2553: Note that a '|' inside an invalid link should not
1238 # be mistaken as delimiting cell parameters
1239 # Bug T153140: Neither should language converter markup.
1240 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1241 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1242 } elseif ( count( $cell_data ) == 1 ) {
1243 // Whitespace in cells is trimmed
1244 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1246 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1247 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1248 // Whitespace in cells is trimmed
1249 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1253 array_push( $td_history, true );
1256 $out .= $outLine . "\n";
1259 # Closing open td, tr && table
1260 while ( count( $td_history ) > 0 ) {
1261 if ( array_pop( $td_history ) ) {
1264 if ( array_pop( $tr_history ) ) {
1267 if ( !array_pop( $has_opened_tr ) ) {
1268 $out .= "<tr><td></td></tr>\n";
1271 $out .= "</table>\n";
1274 # Remove trailing line-ending (b/c)
1275 if ( substr( $out, -1 ) === "\n" ) {
1276 $out = substr( $out, 0, -1 );
1279 # special case: don't return empty table
1280 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1288 * Helper function for parse() that transforms wiki markup into half-parsed
1289 * HTML. Only called for $mOutputType == self::OT_HTML.
1293 * @param string $text The text to parse
1294 * @param bool $isMain Whether this is being called from the main parse() function
1295 * @param PPFrame|bool $frame A pre-processor frame
1299 public function internalParse( $text, $isMain = true, $frame = false ) {
1302 // Avoid PHP 7.1 warning from passing $this by reference
1305 # Hook to suspend the parser in this state
1306 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1310 # if $frame is provided, then use $frame for replacing any variables
1312 # use frame depth to infer how include/noinclude tags should be handled
1313 # depth=0 means this is the top-level document; otherwise it's an included document
1314 if ( !$frame->depth
) {
1317 $flag = self
::PTD_FOR_INCLUSION
;
1319 $dom = $this->preprocessToDom( $text, $flag );
1320 $text = $frame->expand( $dom );
1322 # if $frame is not provided, then use old-style replaceVariables
1323 $text = $this->replaceVariables( $text );
1326 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1327 $text = Sanitizer
::removeHTMLtags(
1329 [ $this, 'attributeStripCallback' ],
1331 array_keys( $this->mTransparentTagHooks
),
1333 [ $this, 'addTrackingCategory' ]
1335 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1337 # Tables need to come after variable replacement for things to work
1338 # properly; putting them before other transformations should keep
1339 # exciting things like link expansions from showing up in surprising
1341 $text = $this->doTableStuff( $text );
1343 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1345 $text = $this->doDoubleUnderscore( $text );
1347 $text = $this->doHeadings( $text );
1348 $text = $this->replaceInternalLinks( $text );
1349 $text = $this->doAllQuotes( $text );
1350 $text = $this->replaceExternalLinks( $text );
1352 # replaceInternalLinks may sometimes leave behind
1353 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1354 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1356 $text = $this->doMagicLinks( $text );
1357 $text = $this->formatHeadings( $text, $origText, $isMain );
1363 * Helper function for parse() that transforms half-parsed HTML into fully
1366 * @param string $text
1367 * @param bool $isMain
1368 * @param bool $linestart
1371 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1372 $text = $this->mStripState
->unstripGeneral( $text );
1374 // Avoid PHP 7.1 warning from passing $this by reference
1378 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1381 # Clean up special characters, only run once, next-to-last before doBlockLevels
1382 $text = Sanitizer
::armorFrenchSpaces( $text );
1384 $text = $this->doBlockLevels( $text, $linestart );
1386 $this->replaceLinkHolders( $text );
1389 * The input doesn't get language converted if
1391 * b) Content isn't converted
1392 * c) It's a conversion table
1393 * d) it is an interface message (which is in the user language)
1395 if ( !( $this->mOptions
->getDisableContentConversion()
1396 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1398 if ( !$this->mOptions
->getInterfaceMessage() ) {
1399 # The position of the convert() call should not be changed. it
1400 # assumes that the links are all replaced and the only thing left
1401 # is the <nowiki> mark.
1402 $text = $this->getTargetLanguage()->convert( $text );
1406 $text = $this->mStripState
->unstripNoWiki( $text );
1409 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1412 $text = $this->replaceTransparentTags( $text );
1413 $text = $this->mStripState
->unstripGeneral( $text );
1415 $text = Sanitizer
::normalizeCharReferences( $text );
1417 if ( MWTidy
::isEnabled() ) {
1418 if ( $this->mOptions
->getTidy() ) {
1419 $text = MWTidy
::tidy( $text );
1422 # attempt to sanitize at least some nesting problems
1423 # (T4702 and quite a few others)
1425 # ''Something [http://www.cool.com cool''] -->
1426 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1427 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1428 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1429 # fix up an anchor inside another anchor, only
1430 # at least for a single single nested link (T5695)
1431 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1432 '\\1\\2</a>\\3</a>\\1\\4</a>',
1433 # fix div inside inline elements- doBlockLevels won't wrap a line which
1434 # contains a div, so fix it up here; replace
1435 # div with escaped text
1436 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1437 '\\1\\3<div\\5>\\6</div>\\8\\9',
1438 # remove empty italic or bold tag pairs, some
1439 # introduced by rules above
1440 '/<([bi])><\/\\1>/' => '',
1443 $text = preg_replace(
1444 array_keys( $tidyregs ),
1445 array_values( $tidyregs ),
1450 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1457 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1458 * magic external links.
1463 * @param string $text
1467 public function doMagicLinks( $text ) {
1468 $prots = wfUrlProtocolsWithoutProtRel();
1469 $urlChar = self
::EXT_LINK_URL_CLASS
;
1470 $addr = self
::EXT_LINK_ADDR
;
1471 $space = self
::SPACE_NOT_NL
; # non-newline space
1472 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1473 $spaces = "$space++"; # possessive match of 1 or more spaces
1474 $text = preg_replace_callback(
1476 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1477 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1478 (\b # m[3]: Free external links
1480 ($addr$urlChar*) # m[4]: Post-protocol path
1482 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1484 \bISBN $spaces ( # m[6]: ISBN, capture number
1485 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1486 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1487 [0-9Xx] # check digit
1489 )!xu", [ $this, 'magicLinkCallback' ], $text );
1494 * @throws MWException
1496 * @return string HTML
1498 public function magicLinkCallback( $m ) {
1499 if ( isset( $m[1] ) && $m[1] !== '' ) {
1502 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1505 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1506 # Free external link
1507 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1508 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1510 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1511 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1516 $cssClass = 'mw-magiclink-rfc';
1517 $trackingCat = 'magiclink-tracking-rfc';
1519 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1520 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1524 $urlmsg = 'pubmedurl';
1525 $cssClass = 'mw-magiclink-pmid';
1526 $trackingCat = 'magiclink-tracking-pmid';
1529 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1530 substr( $m[0], 0, 20 ) . '"' );
1532 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1533 $this->addTrackingCategory( $trackingCat );
1534 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1535 } elseif ( isset( $m[6] ) && $m[6] !== ''
1536 && $this->mOptions
->getMagicISBNLinks()
1540 $space = self
::SPACE_NOT_NL
; # non-newline space
1541 $isbn = preg_replace( "/$space/", ' ', $isbn );
1542 $num = strtr( $isbn, [
1547 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1548 return $this->getLinkRenderer()->makeKnownLink(
1549 SpecialPage
::getTitleFor( 'Booksources', $num ),
1552 'class' => 'internal mw-magiclink-isbn',
1553 'title' => false // suppress title attribute
1562 * Make a free external link, given a user-supplied URL
1564 * @param string $url
1565 * @param int $numPostProto
1566 * The number of characters after the protocol.
1567 * @return string HTML
1570 public function makeFreeExternalLink( $url, $numPostProto ) {
1573 # The characters '<' and '>' (which were escaped by
1574 # removeHTMLtags()) should not be included in
1575 # URLs, per RFC 2396.
1576 # Make terminate a URL as well (bug T84937)
1579 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1584 $trail = substr( $url, $m2[0][1] ) . $trail;
1585 $url = substr( $url, 0, $m2[0][1] );
1588 # Move trailing punctuation to $trail
1590 # If there is no left bracket, then consider right brackets fair game too
1591 if ( strpos( $url, '(' ) === false ) {
1595 $urlRev = strrev( $url );
1596 $numSepChars = strspn( $urlRev, $sep );
1597 # Don't break a trailing HTML entity by moving the ; into $trail
1598 # This is in hot code, so use substr_compare to avoid having to
1599 # create a new string object for the comparison
1600 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1601 # more optimization: instead of running preg_match with a $
1602 # anchor, which can be slow, do the match on the reversed
1603 # string starting at the desired offset.
1604 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1605 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1609 if ( $numSepChars ) {
1610 $trail = substr( $url, -$numSepChars ) . $trail;
1611 $url = substr( $url, 0, -$numSepChars );
1614 # Verify that we still have a real URL after trail removal, and
1615 # not just lone protocol
1616 if ( strlen( $trail ) >= $numPostProto ) {
1617 return $url . $trail;
1620 $url = Sanitizer
::cleanUrl( $url );
1622 # Is this an external image?
1623 $text = $this->maybeMakeExternalImage( $url );
1624 if ( $text === false ) {
1625 # Not an image, make a link
1626 $text = Linker
::makeExternalLink( $url,
1627 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1629 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1630 # Register it in the output object...
1631 $this->mOutput
->addExternalLink( $url );
1633 return $text . $trail;
1637 * Parse headers and return html
1641 * @param string $text
1645 public function doHeadings( $text ) {
1646 for ( $i = 6; $i >= 1; --$i ) {
1647 $h = str_repeat( '=', $i );
1648 // Trim non-newline whitespace from headings
1649 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1650 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1656 * Replace single quotes with HTML markup
1659 * @param string $text
1661 * @return string The altered text
1663 public function doAllQuotes( $text ) {
1665 $lines = StringUtils
::explode( "\n", $text );
1666 foreach ( $lines as $line ) {
1667 $outtext .= $this->doQuotes( $line ) . "\n";
1669 $outtext = substr( $outtext, 0, -1 );
1674 * Helper function for doAllQuotes()
1676 * @param string $text
1680 public function doQuotes( $text ) {
1681 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1682 $countarr = count( $arr );
1683 if ( $countarr == 1 ) {
1687 // First, do some preliminary work. This may shift some apostrophes from
1688 // being mark-up to being text. It also counts the number of occurrences
1689 // of bold and italics mark-ups.
1692 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1693 $thislen = strlen( $arr[$i] );
1694 // If there are ever four apostrophes, assume the first is supposed to
1695 // be text, and the remaining three constitute mark-up for bold text.
1696 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1697 if ( $thislen == 4 ) {
1698 $arr[$i - 1] .= "'";
1701 } elseif ( $thislen > 5 ) {
1702 // If there are more than 5 apostrophes in a row, assume they're all
1703 // text except for the last 5.
1704 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1705 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1709 // Count the number of occurrences of bold and italics mark-ups.
1710 if ( $thislen == 2 ) {
1712 } elseif ( $thislen == 3 ) {
1714 } elseif ( $thislen == 5 ) {
1720 // If there is an odd number of both bold and italics, it is likely
1721 // that one of the bold ones was meant to be an apostrophe followed
1722 // by italics. Which one we cannot know for certain, but it is more
1723 // likely to be one that has a single-letter word before it.
1724 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1725 $firstsingleletterword = -1;
1726 $firstmultiletterword = -1;
1728 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1729 if ( strlen( $arr[$i] ) == 3 ) {
1730 $x1 = substr( $arr[$i - 1], -1 );
1731 $x2 = substr( $arr[$i - 1], -2, 1 );
1732 if ( $x1 === ' ' ) {
1733 if ( $firstspace == -1 ) {
1736 } elseif ( $x2 === ' ' ) {
1737 $firstsingleletterword = $i;
1738 // if $firstsingleletterword is set, we don't
1739 // look at the other options, so we can bail early.
1742 if ( $firstmultiletterword == -1 ) {
1743 $firstmultiletterword = $i;
1749 // If there is a single-letter word, use it!
1750 if ( $firstsingleletterword > -1 ) {
1751 $arr[$firstsingleletterword] = "''";
1752 $arr[$firstsingleletterword - 1] .= "'";
1753 } elseif ( $firstmultiletterword > -1 ) {
1754 // If not, but there's a multi-letter word, use that one.
1755 $arr[$firstmultiletterword] = "''";
1756 $arr[$firstmultiletterword - 1] .= "'";
1757 } elseif ( $firstspace > -1 ) {
1758 // ... otherwise use the first one that has neither.
1759 // (notice that it is possible for all three to be -1 if, for example,
1760 // there is only one pentuple-apostrophe in the line)
1761 $arr[$firstspace] = "''";
1762 $arr[$firstspace - 1] .= "'";
1766 // Now let's actually convert our apostrophic mush to HTML!
1771 foreach ( $arr as $r ) {
1772 if ( ( $i %
2 ) == 0 ) {
1773 if ( $state === 'both' ) {
1779 $thislen = strlen( $r );
1780 if ( $thislen == 2 ) {
1781 if ( $state === 'i' ) {
1784 } elseif ( $state === 'bi' ) {
1787 } elseif ( $state === 'ib' ) {
1788 $output .= '</b></i><b>';
1790 } elseif ( $state === 'both' ) {
1791 $output .= '<b><i>' . $buffer . '</i>';
1793 } else { // $state can be 'b' or ''
1797 } elseif ( $thislen == 3 ) {
1798 if ( $state === 'b' ) {
1801 } elseif ( $state === 'bi' ) {
1802 $output .= '</i></b><i>';
1804 } elseif ( $state === 'ib' ) {
1807 } elseif ( $state === 'both' ) {
1808 $output .= '<i><b>' . $buffer . '</b>';
1810 } else { // $state can be 'i' or ''
1814 } elseif ( $thislen == 5 ) {
1815 if ( $state === 'b' ) {
1816 $output .= '</b><i>';
1818 } elseif ( $state === 'i' ) {
1819 $output .= '</i><b>';
1821 } elseif ( $state === 'bi' ) {
1822 $output .= '</i></b>';
1824 } elseif ( $state === 'ib' ) {
1825 $output .= '</b></i>';
1827 } elseif ( $state === 'both' ) {
1828 $output .= '<i><b>' . $buffer . '</b></i>';
1830 } else { // ($state == '')
1838 // Now close all remaining tags. Notice that the order is important.
1839 if ( $state === 'b' ||
$state === 'ib' ) {
1842 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1845 if ( $state === 'bi' ) {
1848 // There might be lonely ''''', so make sure we have a buffer
1849 if ( $state === 'both' && $buffer ) {
1850 $output .= '<b><i>' . $buffer . '</i></b>';
1856 * Replace external links (REL)
1858 * Note: this is all very hackish and the order of execution matters a lot.
1859 * Make sure to run tests/parser/parserTests.php if you change this code.
1863 * @param string $text
1865 * @throws MWException
1868 public function replaceExternalLinks( $text ) {
1869 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1870 if ( $bits === false ) {
1871 throw new MWException( "PCRE needs to be compiled with "
1872 . "--enable-unicode-properties in order for MediaWiki to function" );
1874 $s = array_shift( $bits );
1877 while ( $i < count( $bits ) ) {
1880 $text = $bits[$i++
];
1881 $trail = $bits[$i++
];
1883 # The characters '<' and '>' (which were escaped by
1884 # removeHTMLtags()) should not be included in
1885 # URLs, per RFC 2396.
1887 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1888 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1889 $url = substr( $url, 0, $m2[0][1] );
1892 # If the link text is an image URL, replace it with an <img> tag
1893 # This happened by accident in the original parser, but some people used it extensively
1894 $img = $this->maybeMakeExternalImage( $text );
1895 if ( $img !== false ) {
1901 # Set linktype for CSS
1904 # No link text, e.g. [http://domain.tld/some.link]
1905 if ( $text == '' ) {
1907 $langObj = $this->getTargetLanguage();
1908 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1909 $linktype = 'autonumber';
1911 # Have link text, e.g. [http://domain.tld/some.link text]s
1913 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1916 // Excluding protocol-relative URLs may avoid many false positives.
1917 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1918 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1921 $url = Sanitizer
::cleanUrl( $url );
1923 # Use the encoded URL
1924 # This means that users can paste URLs directly into the text
1925 # Funny characters like ö aren't valid in URLs anyway
1926 # This was changed in August 2004
1927 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1928 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1930 # Register link in the output object.
1931 $this->mOutput
->addExternalLink( $url );
1938 * Get the rel attribute for a particular external link.
1941 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1942 * nofollow if appropriate
1943 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1944 * @return string|null Rel attribute for $url
1946 public static function getExternalLinkRel( $url = false, $title = null ) {
1947 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1948 $ns = $title ?
$title->getNamespace() : false;
1949 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1950 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1958 * Get an associative array of additional HTML attributes appropriate for a
1959 * particular external link. This currently may include rel => nofollow
1960 * (depending on configuration, namespace, and the URL's domain) and/or a
1961 * target attribute (depending on configuration).
1963 * @param string $url URL to extract the domain from for rel =>
1964 * nofollow if appropriate
1965 * @return array Associative array of HTML attributes
1967 public function getExternalLinkAttribs( $url ) {
1969 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1971 $target = $this->mOptions
->getExternalLinkTarget();
1973 $attribs['target'] = $target;
1974 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1975 // T133507. New windows can navigate parent cross-origin.
1976 // Including noreferrer due to lacking browser
1977 // support of noopener. Eventually noreferrer should be removed.
1978 if ( $rel !== '' ) {
1981 $rel .= 'noreferrer noopener';
1984 $attribs['rel'] = $rel;
1989 * Replace unusual escape codes in a URL with their equivalent characters
1991 * This generally follows the syntax defined in RFC 3986, with special
1992 * consideration for HTTP query strings.
1994 * @param string $url
1997 public static function normalizeLinkUrl( $url ) {
1998 # First, make sure unsafe characters are encoded
1999 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2001 return rawurlencode( $m[0] );
2007 $end = strlen( $url );
2009 # Fragment part - 'fragment'
2010 $start = strpos( $url, '#' );
2011 if ( $start !== false && $start < $end ) {
2012 $ret = self
::normalizeUrlComponent(
2013 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2017 # Query part - 'query' minus &=+;
2018 $start = strpos( $url, '?' );
2019 if ( $start !== false && $start < $end ) {
2020 $ret = self
::normalizeUrlComponent(
2021 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2025 # Scheme and path part - 'pchar'
2026 # (we assume no userinfo or encoded colons in the host)
2027 $ret = self
::normalizeUrlComponent(
2028 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2033 private static function normalizeUrlComponent( $component, $unsafe ) {
2034 $callback = function ( $matches ) use ( $unsafe ) {
2035 $char = urldecode( $matches[0] );
2036 $ord = ord( $char );
2037 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2041 # Leave it escaped, but use uppercase for a-f
2042 return strtoupper( $matches[0] );
2045 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2049 * make an image if it's allowed, either through the global
2050 * option, through the exception, or through the on-wiki whitelist
2052 * @param string $url
2056 private function maybeMakeExternalImage( $url ) {
2057 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2058 $imagesexception = !empty( $imagesfrom );
2060 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2061 if ( $imagesexception && is_array( $imagesfrom ) ) {
2062 $imagematch = false;
2063 foreach ( $imagesfrom as $match ) {
2064 if ( strpos( $url, $match ) === 0 ) {
2069 } elseif ( $imagesexception ) {
2070 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2072 $imagematch = false;
2075 if ( $this->mOptions
->getAllowExternalImages()
2076 ||
( $imagesexception && $imagematch )
2078 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2080 $text = Linker
::makeExternalImage( $url );
2083 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2084 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2086 $whitelist = explode(
2088 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2091 foreach ( $whitelist as $entry ) {
2092 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2093 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2096 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2097 # Image matches a whitelist entry
2098 $text = Linker
::makeExternalImage( $url );
2107 * Process [[ ]] wikilinks
2111 * @return string Processed text
2115 public function replaceInternalLinks( $s ) {
2116 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2121 * Process [[ ]] wikilinks (RIL)
2123 * @throws MWException
2124 * @return LinkHolderArray
2128 public function replaceInternalLinks2( &$s ) {
2129 global $wgExtraInterlanguageLinkPrefixes;
2131 static $tc = false, $e1, $e1_img;
2132 # the % is needed to support urlencoded titles as well
2134 $tc = Title
::legalChars() . '#%';
2135 # Match a link having the form [[namespace:link|alternate]]trail
2136 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2137 # Match cases where there is no "]]", which might still be images
2138 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2141 $holders = new LinkHolderArray( $this );
2143 # split the entire text string on occurrences of [[
2144 $a = StringUtils
::explode( '[[', ' ' . $s );
2145 # get the first element (all text up to first [[), and remove the space we added
2148 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2149 $s = substr( $s, 1 );
2151 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2153 if ( $useLinkPrefixExtension ) {
2154 # Match the end of a line for a word that's not followed by whitespace,
2155 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2156 $charset = $this->getContentLanguage()->linkPrefixCharset();
2157 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2160 if ( is_null( $this->mTitle
) ) {
2161 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2163 $nottalk = !$this->mTitle
->isTalkPage();
2165 if ( $useLinkPrefixExtension ) {
2167 if ( preg_match( $e2, $s, $m ) ) {
2168 $first_prefix = $m[2];
2170 $first_prefix = false;
2176 $useSubpages = $this->areSubpagesAllowed();
2178 # Loop for each link
2179 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2180 # Check for excessive memory usage
2181 if ( $holders->isBig() ) {
2183 # Do the existence check, replace the link holders and clear the array
2184 $holders->replace( $s );
2188 if ( $useLinkPrefixExtension ) {
2189 if ( preg_match( $e2, $s, $m ) ) {
2196 if ( $first_prefix ) {
2197 $prefix = $first_prefix;
2198 $first_prefix = false;
2202 $might_be_img = false;
2204 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2206 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2207 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2208 # the real problem is with the $e1 regex
2210 # Still some problems for cases where the ] is meant to be outside punctuation,
2211 # and no image is in sight. See T4095.
2213 && substr( $m[3], 0, 1 ) === ']'
2214 && strpos( $text, '[' ) !== false
2216 $text .= ']'; # so that replaceExternalLinks($text) works later
2217 $m[3] = substr( $m[3], 1 );
2219 # fix up urlencoded title texts
2220 if ( strpos( $m[1], '%' ) !== false ) {
2221 # Should anchors '#' also be rejected?
2222 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2225 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2226 # Invalid, but might be an image with a link in its caption
2227 $might_be_img = true;
2229 if ( strpos( $m[1], '%' ) !== false ) {
2230 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2233 } else { # Invalid form; output directly
2234 $s .= $prefix . '[[' . $line;
2238 $origLink = ltrim( $m[1], ' ' );
2240 # Don't allow internal links to pages containing
2241 # PROTO: where PROTO is a valid URL protocol; these
2242 # should be external links.
2243 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2244 $s .= $prefix . '[[' . $line;
2248 # Make subpage if necessary
2249 if ( $useSubpages ) {
2250 $link = $this->maybeDoSubpageLink( $origLink, $text );
2255 // \x7f isn't a default legal title char, so most likely strip
2256 // markers will force us into the "invalid form" path above. But,
2257 // just in case, let's assert that xmlish tags aren't valid in
2258 // the title position.
2259 $unstrip = $this->mStripState
->killMarkers( $link );
2260 $noMarkers = ( $unstrip === $link );
2262 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2263 if ( $nt === null ) {
2264 $s .= $prefix . '[[' . $line;
2268 $ns = $nt->getNamespace();
2269 $iw = $nt->getInterwiki();
2271 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2273 if ( $might_be_img ) { # if this is actually an invalid link
2274 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2277 # look at the next 'line' to see if we can close it there
2279 $next_line = $a->current();
2280 if ( $next_line === false ||
$next_line === null ) {
2283 $m = explode( ']]', $next_line, 3 );
2284 if ( count( $m ) == 3 ) {
2285 # the first ]] closes the inner link, the second the image
2287 $text .= "[[{$m[0]}]]{$m[1]}";
2290 } elseif ( count( $m ) == 2 ) {
2291 # if there's exactly one ]] that's fine, we'll keep looking
2292 $text .= "[[{$m[0]}]]{$m[1]}";
2294 # if $next_line is invalid too, we need look no further
2295 $text .= '[[' . $next_line;
2300 # we couldn't find the end of this imageLink, so output it raw
2301 # but don't ignore what might be perfectly normal links in the text we've examined
2302 $holders->merge( $this->replaceInternalLinks2( $text ) );
2303 $s .= "{$prefix}[[$link|$text";
2304 # note: no $trail, because without an end, there *is* no trail
2307 } else { # it's not an image, so output it raw
2308 $s .= "{$prefix}[[$link|$text";
2309 # note: no $trail, because without an end, there *is* no trail
2314 $wasblank = ( $text == '' );
2318 # Strip off leading ':'
2319 $text = substr( $text, 1 );
2322 # T6598 madness. Handle the quotes only if they come from the alternate part
2323 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2324 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2325 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2326 $text = $this->doQuotes( $text );
2329 # Link not escaped by : , create the various objects
2330 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2333 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2334 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2335 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2338 # T26502: filter duplicates
2339 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2340 $this->mLangLinkLanguages
[$iw] = true;
2341 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2345 * Strip the whitespace interwiki links produce, see T10897
2347 $s = rtrim( $s . $prefix ) . $trail; # T175416
2351 if ( $ns == NS_FILE
) {
2352 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2354 # if no parameters were passed, $text
2355 # becomes something like "File:Foo.png",
2356 # which we don't want to pass on to the
2360 # recursively parse links inside the image caption
2361 # actually, this will parse them in any other parameters, too,
2362 # but it might be hard to fix that, and it doesn't matter ATM
2363 $text = $this->replaceExternalLinks( $text );
2364 $holders->merge( $this->replaceInternalLinks2( $text ) );
2366 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2367 $s .= $prefix . $this->armorLinks(
2368 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2371 } elseif ( $ns == NS_CATEGORY
) {
2373 * Strip the whitespace Category links produce, see T2087
2375 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2378 $sortkey = $this->getDefaultSort();
2382 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2383 $sortkey = str_replace( "\n", '', $sortkey );
2384 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2385 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2391 # Self-link checking. For some languages, variants of the title are checked in
2392 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2393 # for linking to a different variant.
2394 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2395 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2399 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2400 # @todo FIXME: Should do batch file existence checks, see comment below
2401 if ( $ns == NS_MEDIA
) {
2402 # Give extensions a chance to select the file revision for us
2405 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2406 [ $this, $nt, &$options, &$descQuery ] );
2407 # Fetch and register the file (file title may be different via hooks)
2408 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2409 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2410 $s .= $prefix . $this->armorLinks(
2411 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2415 # Some titles, such as valid special pages or files in foreign repos, should
2416 # be shown as bluelinks even though they're not included in the page table
2417 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2418 # batch file existence checks for NS_FILE and NS_MEDIA
2419 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2420 $this->mOutput
->addLink( $nt );
2421 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2423 # Links will be added to the output link list after checking
2424 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2431 * Render a forced-blue link inline; protect against double expansion of
2432 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2433 * Since this little disaster has to split off the trail text to avoid
2434 * breaking URLs in the following text without breaking trails on the
2435 * wiki links, it's been made into a horrible function.
2438 * @param string $text
2439 * @param string $trail
2440 * @param string $prefix
2441 * @return string HTML-wikitext mix oh yuck
2443 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2444 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2446 if ( $text == '' ) {
2447 $text = htmlspecialchars( $nt->getPrefixedText() );
2450 $link = $this->getLinkRenderer()->makeKnownLink(
2451 $nt, new HtmlArmor( "$prefix$text$inside" )
2454 return $this->armorLinks( $link ) . $trail;
2458 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2459 * going to go through further parsing steps before inline URL expansion.
2461 * Not needed quite as much as it used to be since free links are a bit
2462 * more sensible these days. But bracketed links are still an issue.
2464 * @param string $text More-or-less HTML
2465 * @return string Less-or-more HTML with NOPARSE bits
2467 public function armorLinks( $text ) {
2468 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2469 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2473 * Return true if subpage links should be expanded on this page.
2476 public function areSubpagesAllowed() {
2477 # Some namespaces don't allow subpages
2478 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2482 * Handle link to subpage if necessary
2484 * @param string $target The source of the link
2485 * @param string &$text The link text, modified as necessary
2486 * @return string The full name of the link
2489 public function maybeDoSubpageLink( $target, &$text ) {
2490 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2494 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2496 * @param string $text
2497 * @param bool $linestart Whether or not this is at the start of a line.
2499 * @return string The lists rendered as HTML
2501 public function doBlockLevels( $text, $linestart ) {
2502 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2506 * Return value of a magic variable (like PAGENAME)
2510 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2511 * @param bool|PPFrame $frame
2513 * @throws MWException
2516 public function getVariableValue( $index, $frame = false ) {
2517 global $wgSitename, $wgServer, $wgServerName;
2518 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2520 if ( is_null( $this->mTitle
) ) {
2521 // If no title set, bad things are going to happen
2522 // later. Title should always be set since this
2523 // should only be called in the middle of a parse
2524 // operation (but the unit-tests do funky stuff)
2525 throw new MWException( __METHOD__
. ' Should only be '
2526 . ' called while parsing (no title set)' );
2529 // Avoid PHP 7.1 warning from passing $this by reference
2533 * Some of these require message or data lookups and can be
2534 * expensive to check many times.
2536 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2537 if ( isset( $this->mVarCache
[$index] ) ) {
2538 return $this->mVarCache
[$index];
2542 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2543 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2545 $pageLang = $this->getFunctionLang();
2551 case 'currentmonth':
2552 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2554 case 'currentmonth1':
2555 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2557 case 'currentmonthname':
2558 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2560 case 'currentmonthnamegen':
2561 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2563 case 'currentmonthabbrev':
2564 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2567 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2570 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2573 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2576 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2578 case 'localmonthname':
2579 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2581 case 'localmonthnamegen':
2582 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2584 case 'localmonthabbrev':
2585 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2588 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2591 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2594 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2597 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2599 case 'fullpagename':
2600 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2602 case 'fullpagenamee':
2603 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2606 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2608 case 'subpagenamee':
2609 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2611 case 'rootpagename':
2612 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2614 case 'rootpagenamee':
2615 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2618 $this->mTitle
->getRootText()
2621 case 'basepagename':
2622 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2624 case 'basepagenamee':
2625 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2628 $this->mTitle
->getBaseText()
2631 case 'talkpagename':
2632 if ( $this->mTitle
->canHaveTalkPage() ) {
2633 $talkPage = $this->mTitle
->getTalkPage();
2634 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2639 case 'talkpagenamee':
2640 if ( $this->mTitle
->canHaveTalkPage() ) {
2641 $talkPage = $this->mTitle
->getTalkPage();
2642 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2647 case 'subjectpagename':
2648 $subjPage = $this->mTitle
->getSubjectPage();
2649 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2651 case 'subjectpagenamee':
2652 $subjPage = $this->mTitle
->getSubjectPage();
2653 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2655 case 'pageid': // requested in T25427
2656 $pageid = $this->getTitle()->getArticleID();
2657 if ( $pageid == 0 ) {
2658 # 0 means the page doesn't exist in the database,
2659 # which means the user is previewing a new page.
2660 # The vary-revision flag must be set, because the magic word
2661 # will have a different value once the page is saved.
2662 $this->mOutput
->setFlag( 'vary-revision' );
2663 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2665 $value = $pageid ?
: null;
2668 # Let the edit saving system know we should parse the page
2669 # *after* a revision ID has been assigned.
2670 $this->mOutput
->setFlag( 'vary-revision-id' );
2671 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2672 $value = $this->mRevisionId
;
2673 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2674 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2675 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2679 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2681 case 'revisionday2':
2682 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2684 case 'revisionmonth':
2685 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2687 case 'revisionmonth1':
2688 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2690 case 'revisionyear':
2691 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2693 case 'revisiontimestamp':
2694 # Let the edit saving system know we should parse the page
2695 # *after* a revision ID has been assigned. This is for null edits.
2696 $this->mOutput
->setFlag( 'vary-revision' );
2697 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2698 $value = $this->getRevisionTimestamp();
2700 case 'revisionuser':
2701 # Let the edit saving system know we should parse the page
2702 # *after* a revision ID has been assigned for null edits.
2703 $this->mOutput
->setFlag( 'vary-user' );
2704 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2705 $value = $this->getRevisionUser();
2707 case 'revisionsize':
2708 $value = $this->getRevisionSize();
2711 $value = str_replace( '_', ' ',
2712 $this->getContentLanguage()->getNsText( $this->mTitle
->getNamespace() ) );
2715 $value = wfUrlencode( $this->getContentLanguage()->
2716 getNsText( $this->mTitle
->getNamespace() ) );
2718 case 'namespacenumber':
2719 $value = $this->mTitle
->getNamespace();
2722 $value = $this->mTitle
->canHaveTalkPage()
2723 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2727 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2729 case 'subjectspace':
2730 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2732 case 'subjectspacee':
2733 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2735 case 'currentdayname':
2736 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2739 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2742 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2745 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2748 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2749 # int to remove the padding
2750 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2753 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2755 case 'localdayname':
2756 $value = $pageLang->getWeekdayName(
2757 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2761 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2764 $value = $pageLang->time(
2765 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2771 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2774 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2775 # int to remove the padding
2776 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2779 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2781 case 'numberofarticles':
2782 $value = $pageLang->formatNum( SiteStats
::articles() );
2784 case 'numberoffiles':
2785 $value = $pageLang->formatNum( SiteStats
::images() );
2787 case 'numberofusers':
2788 $value = $pageLang->formatNum( SiteStats
::users() );
2790 case 'numberofactiveusers':
2791 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2793 case 'numberofpages':
2794 $value = $pageLang->formatNum( SiteStats
::pages() );
2796 case 'numberofadmins':
2797 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2799 case 'numberofedits':
2800 $value = $pageLang->formatNum( SiteStats
::edits() );
2802 case 'currenttimestamp':
2803 $value = wfTimestamp( TS_MW
, $ts );
2805 case 'localtimestamp':
2806 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2808 case 'currentversion':
2809 $value = SpecialVersion
::getVersion();
2812 return $wgArticlePath;
2818 return $wgServerName;
2820 return $wgScriptPath;
2822 return $wgStylePath;
2823 case 'directionmark':
2824 return $pageLang->getDirMark();
2825 case 'contentlanguage':
2826 global $wgLanguageCode;
2827 return $wgLanguageCode;
2828 case 'pagelanguage':
2829 $value = $pageLang->getCode();
2831 case 'cascadingsources':
2832 $value = CoreParserFunctions
::cascadingsources( $this );
2837 'ParserGetVariableValueSwitch',
2838 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2845 $this->mVarCache
[$index] = $value;
2854 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2855 * @param string $variable Parser variable name
2858 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2859 # Get the timezone-adjusted timestamp to be used for this revision
2860 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2861 # Possibly set vary-revision if there is not yet an associated revision
2862 if ( !$this->getRevisionObject() ) {
2863 # Get the timezone-adjusted timestamp $mtts seconds in the future
2865 $this->getContentLanguage()->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2870 if ( $resNow !== $resThen ) {
2871 # Let the edit saving system know we should parse the page
2872 # *after* a revision ID has been assigned. This is for null edits.
2873 $this->mOutput
->setFlag( 'vary-revision' );
2874 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2882 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2886 public function initialiseVariables() {
2887 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2888 $substIDs = $this->magicWordFactory
->getSubstIDs();
2890 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2891 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2895 * Preprocess some wikitext and return the document tree.
2896 * This is the ghost of replace_variables().
2898 * @param string $text The text to parse
2899 * @param int $flags Bitwise combination of:
2900 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2901 * included. Default is to assume a direct page view.
2903 * The generated DOM tree must depend only on the input text and the flags.
2904 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2906 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2907 * change in the DOM tree for a given text, must be passed through the section identifier
2908 * in the section edit link and thus back to extractSections().
2910 * The output of this function is currently only cached in process memory, but a persistent
2911 * cache may be implemented at a later date which takes further advantage of these strict
2912 * dependency requirements.
2916 public function preprocessToDom( $text, $flags = 0 ) {
2917 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2922 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2928 public static function splitWhitespace( $s ) {
2929 $ltrimmed = ltrim( $s );
2930 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2931 $trimmed = rtrim( $ltrimmed );
2932 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2934 $w2 = substr( $ltrimmed, -$diff );
2938 return [ $w1, $trimmed, $w2 ];
2942 * Replace magic variables, templates, and template arguments
2943 * with the appropriate text. Templates are substituted recursively,
2944 * taking care to avoid infinite loops.
2946 * Note that the substitution depends on value of $mOutputType:
2947 * self::OT_WIKI: only {{subst:}} templates
2948 * self::OT_PREPROCESS: templates but not extension tags
2949 * self::OT_HTML: all templates and extension tags
2951 * @param string $text The text to transform
2952 * @param bool|PPFrame $frame Object describing the arguments passed to the
2953 * template. Arguments may also be provided as an associative array, as
2954 * was the usual case before MW1.12. Providing arguments this way may be
2955 * useful for extensions wishing to perform variable replacement
2957 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2958 * double-brace expansion.
2961 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2962 # Is there any text? Also, Prevent too big inclusions!
2963 $textSize = strlen( $text );
2964 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2968 if ( $frame === false ) {
2969 $frame = $this->getPreprocessor()->newFrame();
2970 } elseif ( !( $frame instanceof PPFrame
) ) {
2971 wfDebug( __METHOD__
. " called using plain parameters instead of "
2972 . "a PPFrame instance. Creating custom frame.\n" );
2973 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2976 $dom = $this->preprocessToDom( $text );
2977 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2978 $text = $frame->expand( $dom, $flags );
2984 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2986 * @param array $args
2990 public static function createAssocArgs( $args ) {
2993 foreach ( $args as $arg ) {
2994 $eqpos = strpos( $arg, '=' );
2995 if ( $eqpos === false ) {
2996 $assocArgs[$index++
] = $arg;
2998 $name = trim( substr( $arg, 0, $eqpos ) );
2999 $value = trim( substr( $arg, $eqpos +
1 ) );
3000 if ( $value === false ) {
3003 if ( $name !== false ) {
3004 $assocArgs[$name] = $value;
3013 * Warn the user when a parser limitation is reached
3014 * Will warn at most once the user per limitation type
3016 * The results are shown during preview and run through the Parser (See EditPage.php)
3018 * @param string $limitationType Should be one of:
3019 * 'expensive-parserfunction' (corresponding messages:
3020 * 'expensive-parserfunction-warning',
3021 * 'expensive-parserfunction-category')
3022 * 'post-expand-template-argument' (corresponding messages:
3023 * 'post-expand-template-argument-warning',
3024 * 'post-expand-template-argument-category')
3025 * 'post-expand-template-inclusion' (corresponding messages:
3026 * 'post-expand-template-inclusion-warning',
3027 * 'post-expand-template-inclusion-category')
3028 * 'node-count-exceeded' (corresponding messages:
3029 * 'node-count-exceeded-warning',
3030 * 'node-count-exceeded-category')
3031 * 'expansion-depth-exceeded' (corresponding messages:
3032 * 'expansion-depth-exceeded-warning',
3033 * 'expansion-depth-exceeded-category')
3034 * @param string|int|null $current Current value
3035 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3036 * exceeded, provide the values (optional)
3038 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3039 # does no harm if $current and $max are present but are unnecessary for the message
3040 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3041 # only during preview, and that would split the parser cache unnecessarily.
3042 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3044 $this->mOutput
->addWarning( $warning );
3045 $this->addTrackingCategory( "$limitationType-category" );
3049 * Return the text of a template, after recursively
3050 * replacing any variables or templates within the template.
3052 * @param array $piece The parts of the template
3053 * $piece['title']: the title, i.e. the part before the |
3054 * $piece['parts']: the parameter array
3055 * $piece['lineStart']: whether the brace was at the start of a line
3056 * @param PPFrame $frame The current frame, contains template arguments
3058 * @return string The text of the template
3060 public function braceSubstitution( $piece, $frame ) {
3063 // $text has been filled
3065 // wiki markup in $text should be escaped
3067 // $text is HTML, armour it against wikitext transformation
3069 // Force interwiki transclusion to be done in raw mode not rendered
3070 $forceRawInterwiki = false;
3071 // $text is a DOM node needing expansion in a child frame
3072 $isChildObj = false;
3073 // $text is a DOM node needing expansion in the current frame
3074 $isLocalObj = false;
3076 # Title object, where $text came from
3079 # $part1 is the bit before the first |, and must contain only title characters.
3080 # Various prefixes will be stripped from it later.
3081 $titleWithSpaces = $frame->expand( $piece['title'] );
3082 $part1 = trim( $titleWithSpaces );
3085 # Original title text preserved for various purposes
3086 $originalTitle = $part1;
3088 # $args is a list of argument nodes, starting from index 0, not including $part1
3089 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3090 # below won't work b/c this $args isn't an object
3091 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3093 $profileSection = null; // profile templates
3097 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3099 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3100 # Decide whether to expand template or keep wikitext as-is.
3101 if ( $this->ot
['wiki'] ) {
3102 if ( $substMatch === false ) {
3103 $literal = true; # literal when in PST with no prefix
3105 $literal = false; # expand when in PST with subst: or safesubst:
3108 if ( $substMatch == 'subst' ) {
3109 $literal = true; # literal when not in PST with plain subst:
3111 $literal = false; # expand when not in PST with safesubst: or no prefix
3115 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3122 if ( !$found && $args->getLength() == 0 ) {
3123 $id = $this->mVariables
->matchStartToEnd( $part1 );
3124 if ( $id !== false ) {
3125 $text = $this->getVariableValue( $id, $frame );
3126 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3127 $this->mOutput
->updateCacheExpiry(
3128 $this->magicWordFactory
->getCacheTTL( $id ) );
3134 # MSG, MSGNW and RAW
3137 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3138 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3141 # Remove obsolete MSG:
3142 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3143 $mwMsg->matchStartAndRemove( $part1 );
3147 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3148 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3149 $forceRawInterwiki = true;
3155 $colonPos = strpos( $part1, ':' );
3156 if ( $colonPos !== false ) {
3157 $func = substr( $part1, 0, $colonPos );
3158 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3159 $argsLength = $args->getLength();
3160 for ( $i = 0; $i < $argsLength; $i++
) {
3161 $funcArgs[] = $args->item( $i );
3164 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3166 // Extract any forwarded flags
3167 if ( isset( $result['title'] ) ) {
3168 $title = $result['title'];
3170 if ( isset( $result['found'] ) ) {
3171 $found = $result['found'];
3173 if ( array_key_exists( 'text', $result ) ) {
3175 $text = $result['text'];
3177 if ( isset( $result['nowiki'] ) ) {
3178 $nowiki = $result['nowiki'];
3180 if ( isset( $result['isHTML'] ) ) {
3181 $isHTML = $result['isHTML'];
3183 if ( isset( $result['forceRawInterwiki'] ) ) {
3184 $forceRawInterwiki = $result['forceRawInterwiki'];
3186 if ( isset( $result['isChildObj'] ) ) {
3187 $isChildObj = $result['isChildObj'];
3189 if ( isset( $result['isLocalObj'] ) ) {
3190 $isLocalObj = $result['isLocalObj'];
3195 # Finish mangling title and then check for loops.
3196 # Set $title to a Title object and $titleText to the PDBK
3199 # Split the title into page and subpage
3201 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3202 if ( $part1 !== $relative ) {
3204 $ns = $this->mTitle
->getNamespace();
3206 $title = Title
::newFromText( $part1, $ns );
3208 $titleText = $title->getPrefixedText();
3209 # Check for language variants if the template is not found
3210 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3211 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3213 # Do recursion depth check
3214 $limit = $this->mOptions
->getMaxTemplateDepth();
3215 if ( $frame->depth
>= $limit ) {
3217 $text = '<span class="error">'
3218 . wfMessage( 'parser-template-recursion-depth-warning' )
3219 ->numParams( $limit )->inContentLanguage()->text()
3225 # Load from database
3226 if ( !$found && $title ) {
3227 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3228 if ( !$title->isExternal() ) {
3229 if ( $title->isSpecialPage()
3230 && $this->mOptions
->getAllowSpecialInclusion()
3231 && $this->ot
['html']
3233 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3234 // Pass the template arguments as URL parameters.
3235 // "uselang" will have no effect since the Language object
3236 // is forced to the one defined in ParserOptions.
3238 $argsLength = $args->getLength();
3239 for ( $i = 0; $i < $argsLength; $i++
) {
3240 $bits = $args->item( $i )->splitArg();
3241 if ( strval( $bits['index'] ) === '' ) {
3242 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3243 $value = trim( $frame->expand( $bits['value'] ) );
3244 $pageArgs[$name] = $value;
3248 // Create a new context to execute the special page
3249 $context = new RequestContext
;
3250 $context->setTitle( $title );
3251 $context->setRequest( new FauxRequest( $pageArgs ) );
3252 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3253 $context->setUser( $this->getUser() );
3255 // If this page is cached, then we better not be per user.
3256 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3258 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3259 $ret = SpecialPageFactory
::capturePath(
3260 $title, $context, $this->getLinkRenderer() );
3262 $text = $context->getOutput()->getHTML();
3263 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3266 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3267 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3268 $specialPage->maxIncludeCacheTime()
3272 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3273 $found = false; # access denied
3274 wfDebug( __METHOD__
. ": template inclusion denied for " .
3275 $title->getPrefixedDBkey() . "\n" );
3277 list( $text, $title ) = $this->getTemplateDom( $title );
3278 if ( $text !== false ) {
3284 # If the title is valid but undisplayable, make a link to it
3285 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3286 $text = "[[:$titleText]]";
3289 } elseif ( $title->isTrans() ) {
3290 # Interwiki transclusion
3291 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3292 $text = $this->interwikiTransclude( $title, 'render' );
3295 $text = $this->interwikiTransclude( $title, 'raw' );
3296 # Preprocess it like a template
3297 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3303 # Do infinite loop check
3304 # This has to be done after redirect resolution to avoid infinite loops via redirects
3305 if ( !$frame->loopCheck( $title ) ) {
3307 $text = '<span class="error">'
3308 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3310 $this->addTrackingCategory( 'template-loop-category' );
3311 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3312 wfEscapeWikiText( $titleText ) )->text() );
3313 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3317 # If we haven't found text to substitute by now, we're done
3318 # Recover the source wikitext and return it
3320 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3321 if ( $profileSection ) {
3322 $this->mProfiler
->scopedProfileOut( $profileSection );
3324 return [ 'object' => $text ];
3327 # Expand DOM-style return values in a child frame
3328 if ( $isChildObj ) {
3329 # Clean up argument array
3330 $newFrame = $frame->newChild( $args, $title );
3333 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3334 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3335 # Expansion is eligible for the empty-frame cache
3336 $text = $newFrame->cachedExpand( $titleText, $text );
3338 # Uncached expansion
3339 $text = $newFrame->expand( $text );
3342 if ( $isLocalObj && $nowiki ) {
3343 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3344 $isLocalObj = false;
3347 if ( $profileSection ) {
3348 $this->mProfiler
->scopedProfileOut( $profileSection );
3351 # Replace raw HTML by a placeholder
3353 $text = $this->insertStripItem( $text );
3354 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3355 # Escape nowiki-style return values
3356 $text = wfEscapeWikiText( $text );
3357 } elseif ( is_string( $text )
3358 && !$piece['lineStart']
3359 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3361 # T2529: if the template begins with a table or block-level
3362 # element, it should be treated as beginning a new line.
3363 # This behavior is somewhat controversial.
3364 $text = "\n" . $text;
3367 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3368 # Error, oversize inclusion
3369 if ( $titleText !== false ) {
3370 # Make a working, properly escaped link if possible (T25588)
3371 $text = "[[:$titleText]]";
3373 # This will probably not be a working link, but at least it may
3374 # provide some hint of where the problem is
3375 preg_replace( '/^:/', '', $originalTitle );
3376 $text = "[[:$originalTitle]]";
3378 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3379 . 'post-expand include size too large -->' );
3380 $this->limitationWarn( 'post-expand-template-inclusion' );
3383 if ( $isLocalObj ) {
3384 $ret = [ 'object' => $text ];
3386 $ret = [ 'text' => $text ];
3393 * Call a parser function and return an array with text and flags.
3395 * The returned array will always contain a boolean 'found', indicating
3396 * whether the parser function was found or not. It may also contain the
3398 * text: string|object, resulting wikitext or PP DOM object
3399 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3400 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3401 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3402 * nowiki: bool, wiki markup in $text should be escaped
3405 * @param PPFrame $frame The current frame, contains template arguments
3406 * @param string $function Function name
3407 * @param array $args Arguments to the function
3408 * @throws MWException
3411 public function callParserFunction( $frame, $function, array $args = [] ) {
3412 # Case sensitive functions
3413 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3414 $function = $this->mFunctionSynonyms
[1][$function];
3416 # Case insensitive functions
3417 $function = $this->getContentLanguage()->lc( $function );
3418 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3419 $function = $this->mFunctionSynonyms
[0][$function];
3421 return [ 'found' => false ];
3425 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3427 // Avoid PHP 7.1 warning from passing $this by reference
3430 $allArgs = [ &$parser ];
3431 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3432 # Convert arguments to PPNodes and collect for appending to $allArgs
3434 foreach ( $args as $k => $v ) {
3435 if ( $v instanceof PPNode ||
$k === 0 ) {
3438 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3442 # Add a frame parameter, and pass the arguments as an array
3443 $allArgs[] = $frame;
3444 $allArgs[] = $funcArgs;
3446 # Convert arguments to plain text and append to $allArgs
3447 foreach ( $args as $k => $v ) {
3448 if ( $v instanceof PPNode
) {
3449 $allArgs[] = trim( $frame->expand( $v ) );
3450 } elseif ( is_int( $k ) && $k >= 0 ) {
3451 $allArgs[] = trim( $v );
3453 $allArgs[] = trim( "$k=$v" );
3458 $result = $callback( ...$allArgs );
3460 # The interface for function hooks allows them to return a wikitext
3461 # string or an array containing the string and any flags. This mungs
3462 # things around to match what this method should return.
3463 if ( !is_array( $result ) ) {
3469 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3470 $result['text'] = $result[0];
3472 unset( $result[0] );
3479 $preprocessFlags = 0;
3480 if ( isset( $result['noparse'] ) ) {
3481 $noparse = $result['noparse'];
3483 if ( isset( $result['preprocessFlags'] ) ) {
3484 $preprocessFlags = $result['preprocessFlags'];
3488 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3489 $result['isChildObj'] = true;
3496 * Get the semi-parsed DOM representation of a template with a given title,
3497 * and its redirect destination title. Cached.
3499 * @param Title $title
3503 public function getTemplateDom( $title ) {
3504 $cacheTitle = $title;
3505 $titleText = $title->getPrefixedDBkey();
3507 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3508 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3509 $title = Title
::makeTitle( $ns, $dbk );
3510 $titleText = $title->getPrefixedDBkey();
3512 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3513 return [ $this->mTplDomCache
[$titleText], $title ];
3516 # Cache miss, go to the database
3517 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3519 if ( $text === false ) {
3520 $this->mTplDomCache
[$titleText] = false;
3521 return [ false, $title ];
3524 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3525 $this->mTplDomCache
[$titleText] = $dom;
3527 if ( !$title->equals( $cacheTitle ) ) {
3528 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3529 [ $title->getNamespace(), $title->getDBkey() ];
3532 return [ $dom, $title ];
3536 * Fetch the current revision of a given title. Note that the revision
3537 * (and even the title) may not exist in the database, so everything
3538 * contributing to the output of the parser should use this method
3539 * where possible, rather than getting the revisions themselves. This
3540 * method also caches its results, so using it benefits performance.
3543 * @param Title $title
3546 public function fetchCurrentRevisionOfTitle( $title ) {
3547 $cacheKey = $title->getPrefixedDBkey();
3548 if ( !$this->currentRevisionCache
) {
3549 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3551 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3552 $this->currentRevisionCache
->set( $cacheKey,
3553 // Defaults to Parser::statelessFetchRevision()
3554 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3557 return $this->currentRevisionCache
->get( $cacheKey );
3561 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3562 * without passing them on to it.
3565 * @param Title $title
3566 * @param Parser|bool $parser
3567 * @return Revision|bool False if missing
3569 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3570 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3576 * Fetch the unparsed text of a template and register a reference to it.
3577 * @param Title $title
3578 * @return array ( string or false, Title )
3580 public function fetchTemplateAndTitle( $title ) {
3581 // Defaults to Parser::statelessFetchTemplate()
3582 $templateCb = $this->mOptions
->getTemplateCallback();
3583 $stuff = call_user_func( $templateCb, $title, $this );
3584 // We use U+007F DELETE to distinguish strip markers from regular text.
3585 $text = $stuff['text'];
3586 if ( is_string( $stuff['text'] ) ) {
3587 $text = strtr( $text, "\x7f", "?" );
3589 $finalTitle = $stuff['finalTitle'] ??
$title;
3590 if ( isset( $stuff['deps'] ) ) {
3591 foreach ( $stuff['deps'] as $dep ) {
3592 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3593 if ( $dep['title']->equals( $this->getTitle() ) ) {
3594 // If we transclude ourselves, the final result
3595 // will change based on the new version of the page
3596 $this->mOutput
->setFlag( 'vary-revision' );
3600 return [ $text, $finalTitle ];
3604 * Fetch the unparsed text of a template and register a reference to it.
3605 * @param Title $title
3606 * @return string|bool
3608 public function fetchTemplate( $title ) {
3609 return $this->fetchTemplateAndTitle( $title )[0];
3613 * Static function to get a template
3614 * Can be overridden via ParserOptions::setTemplateCallback().
3616 * @param Title $title
3617 * @param bool|Parser $parser
3621 public static function statelessFetchTemplate( $title, $parser = false ) {
3622 $text = $skip = false;
3623 $finalTitle = $title;
3626 # Loop to fetch the article, with up to 1 redirect
3627 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3628 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3629 # Give extensions a chance to select the revision instead
3630 $id = false; # Assume current
3631 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3632 [ $parser, $title, &$skip, &$id ] );
3638 'page_id' => $title->getArticleID(),
3645 $rev = Revision
::newFromId( $id );
3646 } elseif ( $parser ) {
3647 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3649 $rev = Revision
::newFromTitle( $title );
3651 $rev_id = $rev ?
$rev->getId() : 0;
3652 # If there is no current revision, there is no page
3653 if ( $id === false && !$rev ) {
3654 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3655 $linkCache->addBadLinkObj( $title );
3660 'page_id' => $title->getArticleID(),
3661 'rev_id' => $rev_id ];
3662 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3663 # We fetched a rev from a different title; register it too...
3665 'title' => $rev->getTitle(),
3666 'page_id' => $rev->getPage(),
3667 'rev_id' => $rev_id ];
3671 $content = $rev->getContent();
3672 $text = $content ?
$content->getWikitextForTransclusion() : null;
3674 Hooks
::run( 'ParserFetchTemplate',
3675 [ $parser, $title, $rev, &$text, &$deps ] );
3677 if ( $text === false ||
$text === null ) {
3681 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3682 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3683 lcfirst( $title->getText() ) )->inContentLanguage();
3684 if ( !$message->exists() ) {
3688 $content = $message->content();
3689 $text = $message->plain();
3697 $finalTitle = $title;
3698 $title = $content->getRedirectTarget();
3702 'finalTitle' => $finalTitle,
3707 * Fetch a file and its title and register a reference to it.
3708 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3709 * @param Title $title
3710 * @param array $options Array of options to RepoGroup::findFile
3712 * @deprecated since 1.32, use fetchFileAndTitle instead
3714 public function fetchFile( $title, $options = [] ) {
3715 wfDeprecated( __METHOD__
, '1.32' );
3716 return $this->fetchFileAndTitle( $title, $options )[0];
3720 * Fetch a file and its title and register a reference to it.
3721 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3722 * @param Title $title
3723 * @param array $options Array of options to RepoGroup::findFile
3724 * @return array ( File or false, Title of file )
3726 public function fetchFileAndTitle( $title, $options = [] ) {
3727 $file = $this->fetchFileNoRegister( $title, $options );
3729 $time = $file ?
$file->getTimestamp() : false;
3730 $sha1 = $file ?
$file->getSha1() : false;
3731 # Register the file as a dependency...
3732 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3733 if ( $file && !$title->equals( $file->getTitle() ) ) {
3734 # Update fetched file title
3735 $title = $file->getTitle();
3736 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3738 return [ $file, $title ];
3742 * Helper function for fetchFileAndTitle.
3744 * Also useful if you need to fetch a file but not use it yet,
3745 * for example to get the file's handler.
3747 * @param Title $title
3748 * @param array $options Array of options to RepoGroup::findFile
3751 protected function fetchFileNoRegister( $title, $options = [] ) {
3752 if ( isset( $options['broken'] ) ) {
3753 $file = false; // broken thumbnail forced by hook
3754 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3755 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3756 } else { // get by (name,timestamp)
3757 $file = wfFindFile( $title, $options );
3763 * Transclude an interwiki link.
3765 * @param Title $title
3766 * @param string $action
3770 public function interwikiTransclude( $title, $action ) {
3771 global $wgEnableScaryTranscluding;
3773 if ( !$wgEnableScaryTranscluding ) {
3774 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3777 $url = $title->getFullURL( [ 'action' => $action ] );
3779 if ( strlen( $url ) > 255 ) {
3780 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3782 return $this->fetchScaryTemplateMaybeFromCache( $url );
3786 * @param string $url
3787 * @return mixed|string
3789 public function fetchScaryTemplateMaybeFromCache( $url ) {
3790 global $wgTranscludeCacheExpiry;
3791 $dbr = wfGetDB( DB_REPLICA
);
3792 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3793 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3794 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3796 return $obj->tc_contents
;
3799 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3800 $status = $req->execute(); // Status object
3801 if ( $status->isOK() ) {
3802 $text = $req->getContent();
3803 } elseif ( $req->getStatus() != 200 ) {
3804 // Though we failed to fetch the content, this status is useless.
3805 return wfMessage( 'scarytranscludefailed-httpstatus' )
3806 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3808 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3811 $dbw = wfGetDB( DB_MASTER
);
3812 $dbw->replace( 'transcache', [ 'tc_url' ], [
3814 'tc_time' => $dbw->timestamp( time() ),
3815 'tc_contents' => $text
3821 * Triple brace replacement -- used for template arguments
3824 * @param array $piece
3825 * @param PPFrame $frame
3829 public function argSubstitution( $piece, $frame ) {
3831 $parts = $piece['parts'];
3832 $nameWithSpaces = $frame->expand( $piece['title'] );
3833 $argName = trim( $nameWithSpaces );
3835 $text = $frame->getArgument( $argName );
3836 if ( $text === false && $parts->getLength() > 0
3837 && ( $this->ot
['html']
3839 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3842 # No match in frame, use the supplied default
3843 $object = $parts->item( 0 )->getChildren();
3845 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3846 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3847 $this->limitationWarn( 'post-expand-template-argument' );
3850 if ( $text === false && $object === false ) {
3852 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3854 if ( $error !== false ) {
3857 if ( $object !== false ) {
3858 $ret = [ 'object' => $object ];
3860 $ret = [ 'text' => $text ];
3867 * Return the text to be used for a given extension tag.
3868 * This is the ghost of strip().
3870 * @param array $params Associative array of parameters:
3871 * name PPNode for the tag name
3872 * attr PPNode for unparsed text where tag attributes are thought to be
3873 * attributes Optional associative array of parsed attributes
3874 * inner Contents of extension element
3875 * noClose Original text did not have a close tag
3876 * @param PPFrame $frame
3878 * @throws MWException
3881 public function extensionSubstitution( $params, $frame ) {
3882 static $errorStr = '<span class="error">';
3883 static $errorLen = 20;
3885 $name = $frame->expand( $params['name'] );
3886 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3887 // Probably expansion depth or node count exceeded. Just punt the
3892 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3893 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3898 // We can't safely check if the expansion for $content resulted in an
3899 // error, because the content could happen to be the error string
3901 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3903 $marker = self
::MARKER_PREFIX
. "-$name-"
3904 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3906 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3907 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3908 if ( $isFunctionTag ) {
3909 $markerType = 'none';
3911 $markerType = 'general';
3913 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3914 $name = strtolower( $name );
3915 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3916 if ( isset( $params['attributes'] ) ) {
3917 $attributes = $attributes +
$params['attributes'];
3920 if ( isset( $this->mTagHooks
[$name] ) ) {
3921 $output = call_user_func_array( $this->mTagHooks
[$name],
3922 [ $content, $attributes, $this, $frame ] );
3923 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3924 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3926 // Avoid PHP 7.1 warning from passing $this by reference
3928 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3930 $output = '<span class="error">Invalid tag extension name: ' .
3931 htmlspecialchars( $name ) . '</span>';
3934 if ( is_array( $output ) ) {
3937 $output = $flags[0];
3938 if ( isset( $flags['markerType'] ) ) {
3939 $markerType = $flags['markerType'];
3943 if ( is_null( $attrText ) ) {
3946 if ( isset( $params['attributes'] ) ) {
3947 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3948 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3949 htmlspecialchars( $attrValue ) . '"';
3952 if ( $content === null ) {
3953 $output = "<$name$attrText/>";
3955 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3956 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3960 $output = "<$name$attrText>$content$close";
3964 if ( $markerType === 'none' ) {
3966 } elseif ( $markerType === 'nowiki' ) {
3967 $this->mStripState
->addNoWiki( $marker, $output );
3968 } elseif ( $markerType === 'general' ) {
3969 $this->mStripState
->addGeneral( $marker, $output );
3971 throw new MWException( __METHOD__
. ': invalid marker type' );
3977 * Increment an include size counter
3979 * @param string $type The type of expansion
3980 * @param int $size The size of the text
3981 * @return bool False if this inclusion would take it over the maximum, true otherwise
3983 public function incrementIncludeSize( $type, $size ) {
3984 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3987 $this->mIncludeSizes
[$type] +
= $size;
3993 * Increment the expensive function count
3995 * @return bool False if the limit has been exceeded
3997 public function incrementExpensiveFunctionCount() {
3998 $this->mExpensiveFunctionCount++
;
3999 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4003 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4004 * Fills $this->mDoubleUnderscores, returns the modified text
4006 * @param string $text
4010 public function doDoubleUnderscore( $text ) {
4011 # The position of __TOC__ needs to be recorded
4012 $mw = $this->magicWordFactory
->get( 'toc' );
4013 if ( $mw->match( $text ) ) {
4014 $this->mShowToc
= true;
4015 $this->mForceTocPosition
= true;
4017 # Set a placeholder. At the end we'll fill it in with the TOC.
4018 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4020 # Only keep the first one.
4021 $text = $mw->replace( '', $text );
4024 # Now match and remove the rest of them
4025 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4026 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4028 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4029 $this->mOutput
->mNoGallery
= true;
4031 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4032 $this->mShowToc
= false;
4034 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4035 && $this->mTitle
->getNamespace() == NS_CATEGORY
4037 $this->addTrackingCategory( 'hidden-category-category' );
4039 # (T10068) Allow control over whether robots index a page.
4040 # __INDEX__ always overrides __NOINDEX__, see T16899
4041 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4042 $this->mOutput
->setIndexPolicy( 'noindex' );
4043 $this->addTrackingCategory( 'noindex-category' );
4045 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4046 $this->mOutput
->setIndexPolicy( 'index' );
4047 $this->addTrackingCategory( 'index-category' );
4050 # Cache all double underscores in the database
4051 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4052 $this->mOutput
->setProperty( $key, '' );
4059 * @see ParserOutput::addTrackingCategory()
4060 * @param string $msg Message key
4061 * @return bool Whether the addition was successful
4063 public function addTrackingCategory( $msg ) {
4064 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4068 * This function accomplishes several tasks:
4069 * 1) Auto-number headings if that option is enabled
4070 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4071 * 3) Add a Table of contents on the top for users who have enabled the option
4072 * 4) Auto-anchor headings
4074 * It loops through all headlines, collects the necessary data, then splits up the
4075 * string and re-inserts the newly formatted headlines.
4077 * @param string $text
4078 * @param string $origText Original, untouched wikitext
4079 * @param bool $isMain
4080 * @return mixed|string
4083 public function formatHeadings( $text, $origText, $isMain = true ) {
4084 global $wgMaxTocLevel;
4086 # Inhibit editsection links if requested in the page
4087 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4088 $maybeShowEditLink = false;
4090 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4093 # Get all headlines for numbering them and adding funky stuff like [edit]
4094 # links - this is for later, but we need the number of headlines right now
4095 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4096 # be trimmed here since whitespace in HTML headings is significant.
4098 $numMatches = preg_match_all(
4099 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4104 # if there are fewer than 4 headlines in the article, do not show TOC
4105 # unless it's been explicitly enabled.
4106 $enoughToc = $this->mShowToc
&&
4107 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4109 # Allow user to stipulate that a page should have a "new section"
4110 # link added via __NEWSECTIONLINK__
4111 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4112 $this->mOutput
->setNewSection( true );
4115 # Allow user to remove the "new section"
4116 # link via __NONEWSECTIONLINK__
4117 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4118 $this->mOutput
->hideNewSection( true );
4121 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4122 # override above conditions and always show TOC above first header
4123 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4124 $this->mShowToc
= true;
4132 # Ugh .. the TOC should have neat indentation levels which can be
4133 # passed to the skin functions. These are determined here
4137 $sublevelCount = [];
4143 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4144 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4145 $oldType = $this->mOutputType
;
4146 $this->setOutputType( self
::OT_WIKI
);
4147 $frame = $this->getPreprocessor()->newFrame();
4148 $root = $this->preprocessToDom( $origText );
4149 $node = $root->getFirstChild();
4154 $headlines = $numMatches !== false ?
$matches[3] : [];
4156 foreach ( $headlines as $headline ) {
4157 $isTemplate = false;
4159 $sectionIndex = false;
4161 $markerMatches = [];
4162 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4163 $serial = $markerMatches[1];
4164 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4165 $isTemplate = ( $titleText != $baseTitleText );
4166 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4170 $prevlevel = $level;
4172 $level = $matches[1][$headlineCount];
4174 if ( $level > $prevlevel ) {
4175 # Increase TOC level
4177 $sublevelCount[$toclevel] = 0;
4178 if ( $toclevel < $wgMaxTocLevel ) {
4179 $prevtoclevel = $toclevel;
4180 $toc .= Linker
::tocIndent();
4183 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4184 # Decrease TOC level, find level to jump to
4186 for ( $i = $toclevel; $i > 0; $i-- ) {
4187 if ( $levelCount[$i] == $level ) {
4188 # Found last matching level
4191 } elseif ( $levelCount[$i] < $level ) {
4192 # Found first matching level below current level
4200 if ( $toclevel < $wgMaxTocLevel ) {
4201 if ( $prevtoclevel < $wgMaxTocLevel ) {
4202 # Unindent only if the previous toc level was shown :p
4203 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4204 $prevtoclevel = $toclevel;
4206 $toc .= Linker
::tocLineEnd();
4210 # No change in level, end TOC line
4211 if ( $toclevel < $wgMaxTocLevel ) {
4212 $toc .= Linker
::tocLineEnd();
4216 $levelCount[$toclevel] = $level;
4218 # count number of headlines for each level
4219 $sublevelCount[$toclevel]++
;
4221 for ( $i = 1; $i <= $toclevel; $i++
) {
4222 if ( !empty( $sublevelCount[$i] ) ) {
4226 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4231 # The safe header is a version of the header text safe to use for links
4233 # Remove link placeholders by the link text.
4234 # <!--LINK number-->
4236 # link text with suffix
4237 # Do this before unstrip since link text can contain strip markers
4238 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4240 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4241 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4243 # Remove any <style> or <script> tags (T198618)
4244 $safeHeadline = preg_replace(
4245 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4250 # Strip out HTML (first regex removes any tag not allowed)
4252 # * <sup> and <sub> (T10393)
4256 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4257 # * <s> and <strike> (T35715)
4258 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4259 # to allow setting directionality in toc items.
4260 $tocline = preg_replace(
4262 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4263 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4269 # Strip '<span></span>', which is the result from the above if
4270 # <span id="foo"></span> is used to produce an additional anchor
4272 $tocline = str_replace( '<span></span>', '', $tocline );
4274 $tocline = trim( $tocline );
4276 # For the anchor, strip out HTML-y stuff period
4277 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4278 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4280 # Save headline for section edit hint before it's escaped
4281 $headlineHint = $safeHeadline;
4283 # Decode HTML entities
4284 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4286 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4288 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4289 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4290 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4291 if ( $fallbackHeadline === $safeHeadline ) {
4292 # No reason to have both (in fact, we can't)
4293 $fallbackHeadline = false;
4296 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4297 # @todo FIXME: We may be changing them depending on the current locale.
4298 $arrayKey = strtolower( $safeHeadline );
4299 if ( $fallbackHeadline === false ) {
4300 $fallbackArrayKey = false;
4302 $fallbackArrayKey = strtolower( $fallbackHeadline );
4305 # Create the anchor for linking from the TOC to the section
4306 $anchor = $safeHeadline;
4307 $fallbackAnchor = $fallbackHeadline;
4308 if ( isset( $refers[$arrayKey] ) ) {
4309 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4310 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4312 $linkAnchor .= "_$i";
4313 $refers["${arrayKey}_$i"] = true;
4315 $refers[$arrayKey] = true;
4317 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4318 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4319 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4320 $fallbackAnchor .= "_$i";
4321 $refers["${fallbackArrayKey}_$i"] = true;
4323 $refers[$fallbackArrayKey] = true;
4326 # Don't number the heading if it is the only one (looks silly)
4327 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4328 # the two are different if the line contains a link
4329 $headline = Html
::element(
4331 [ 'class' => 'mw-headline-number' ],
4333 ) . ' ' . $headline;
4336 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4337 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4338 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4341 # Add the section to the section tree
4342 # Find the DOM node for this header
4343 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4344 while ( $node && !$noOffset ) {
4345 if ( $node->getName() === 'h' ) {
4346 $bits = $node->splitHeading();
4347 if ( $bits['i'] == $sectionIndex ) {
4351 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4352 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4353 $node = $node->getNextSibling();
4356 'toclevel' => $toclevel,
4359 'number' => $numbering,
4360 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4361 'fromtitle' => $titleText,
4362 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4363 'anchor' => $anchor,
4366 # give headline the correct <h#> tag
4367 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4368 // Output edit section links as markers with styles that can be customized by skins
4369 if ( $isTemplate ) {
4370 # Put a T flag in the section identifier, to indicate to extractSections()
4371 # that sections inside <includeonly> should be counted.
4372 $editsectionPage = $titleText;
4373 $editsectionSection = "T-$sectionIndex";
4374 $editsectionContent = null;
4376 $editsectionPage = $this->mTitle
->getPrefixedText();
4377 $editsectionSection = $sectionIndex;
4378 $editsectionContent = $headlineHint;
4380 // We use a bit of pesudo-xml for editsection markers. The
4381 // language converter is run later on. Using a UNIQ style marker
4382 // leads to the converter screwing up the tokens when it
4383 // converts stuff. And trying to insert strip tags fails too. At
4384 // this point all real inputted tags have already been escaped,
4385 // so we don't have to worry about a user trying to input one of
4386 // these markers directly. We use a page and section attribute
4387 // to stop the language converter from converting these
4388 // important bits of data, but put the headline hint inside a
4389 // content block because the language converter is supposed to
4390 // be able to convert that piece of data.
4391 // Gets replaced with html in ParserOutput::getText
4392 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4393 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4394 if ( $editsectionContent !== null ) {
4395 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4402 $head[$headlineCount] = Linker
::makeHeadline( $level,
4403 $matches['attrib'][$headlineCount], $anchor, $headline,
4404 $editlink, $fallbackAnchor );
4409 $this->setOutputType( $oldType );
4411 # Never ever show TOC if no headers
4412 if ( $numVisible < 1 ) {
4417 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4418 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4420 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4421 $this->mOutput
->setTOCHTML( $toc );
4422 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4426 $this->mOutput
->setSections( $tocraw );
4429 # split up and insert constructed headlines
4430 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4433 // build an array of document sections
4435 foreach ( $blocks as $block ) {
4436 // $head is zero-based, sections aren't.
4437 if ( empty( $head[$i - 1] ) ) {
4438 $sections[$i] = $block;
4440 $sections[$i] = $head[$i - 1] . $block;
4444 * Send a hook, one per section.
4445 * The idea here is to be able to make section-level DIVs, but to do so in a
4446 * lower-impact, more correct way than r50769
4449 * $section : the section number
4450 * &$sectionContent : ref to the content of the section
4451 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4453 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4458 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4459 // append the TOC at the beginning
4460 // Top anchor now in skin
4461 $sections[0] = $sections[0] . $toc . "\n";
4464 $full .= implode( '', $sections );
4466 if ( $this->mForceTocPosition
) {
4467 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4474 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4475 * conversion, substituting signatures, {{subst:}} templates, etc.
4477 * @param string $text The text to transform
4478 * @param Title $title The Title object for the current article
4479 * @param User $user The User object describing the current user
4480 * @param ParserOptions $options Parsing options
4481 * @param bool $clearState Whether to clear the parser state first
4482 * @return string The altered wiki markup
4484 public function preSaveTransform( $text, Title
$title, User
$user,
4485 ParserOptions
$options, $clearState = true
4487 if ( $clearState ) {
4488 $magicScopeVariable = $this->lock();
4490 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4491 $this->setUser( $user );
4493 // Strip U+0000 NULL (T159174)
4494 $text = str_replace( "\000", '', $text );
4496 // We still normalize line endings for backwards-compatibility
4497 // with other code that just calls PST, but this should already
4498 // be handled in TextContent subclasses
4499 $text = TextContent
::normalizeLineEndings( $text );
4501 if ( $options->getPreSaveTransform() ) {
4502 $text = $this->pstPass2( $text, $user );
4504 $text = $this->mStripState
->unstripBoth( $text );
4506 $this->setUser( null ); # Reset
4512 * Pre-save transform helper function
4514 * @param string $text
4519 private function pstPass2( $text, $user ) {
4520 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4521 # $this->getContentLanguage() here in order to give everyone the same signature and use the
4522 # default one rather than the one selected in each user's preferences. (see also T14815)
4523 $ts = $this->mOptions
->getTimestamp();
4524 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4525 $ts = $timestamp->format( 'YmdHis' );
4526 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4528 $d = $this->getContentLanguage()->timeanddate( $ts, false, false ) . " ($tzMsg)";
4530 # Variable replacement
4531 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4532 $text = $this->replaceVariables( $text );
4534 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4535 # which may corrupt this parser instance via its wfMessage()->text() call-
4538 if ( strpos( $text, '~~~' ) !== false ) {
4539 $sigText = $this->getUserSig( $user );
4540 $text = strtr( $text, [
4542 '~~~~' => "$sigText $d",
4545 # The main two signature forms used above are time-sensitive
4546 $this->mOutput
->setFlag( 'user-signature' );
4549 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4550 $tc = '[' . Title
::legalChars() . ']';
4551 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4553 // [[ns:page (context)|]]
4554 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4555 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4556 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4557 // [[ns:page (context), context|]] (using either single or double-width comma)
4558 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4559 // [[|page]] (reverse pipe trick: add context from page title)
4560 $p2 = "/\[\[\\|($tc+)]]/";
4562 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4563 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4564 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4565 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4567 $t = $this->mTitle
->getText();
4569 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4570 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4571 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4572 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4574 # if there's no context, don't bother duplicating the title
4575 $text = preg_replace( $p2, '[[\\1]]', $text );
4582 * Fetch the user's signature text, if any, and normalize to
4583 * validated, ready-to-insert wikitext.
4584 * If you have pre-fetched the nickname or the fancySig option, you can
4585 * specify them here to save a database query.
4586 * Do not reuse this parser instance after calling getUserSig(),
4587 * as it may have changed if it's the $wgParser.
4589 * @param User &$user
4590 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4591 * @param bool|null $fancySig whether the nicknname is the complete signature
4592 * or null to use default value
4595 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4596 global $wgMaxSigChars;
4598 $username = $user->getName();
4600 # If not given, retrieve from the user object.
4601 if ( $nickname === false ) {
4602 $nickname = $user->getOption( 'nickname' );
4605 if ( is_null( $fancySig ) ) {
4606 $fancySig = $user->getBoolOption( 'fancysig' );
4609 $nickname = $nickname == null ?
$username : $nickname;
4611 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4612 $nickname = $username;
4613 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4614 } elseif ( $fancySig !== false ) {
4615 # Sig. might contain markup; validate this
4616 if ( $this->validateSig( $nickname ) !== false ) {
4617 # Validated; clean up (if needed) and return it
4618 return $this->cleanSig( $nickname, true );
4620 # Failed to validate; fall back to the default
4621 $nickname = $username;
4622 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4626 # Make sure nickname doesnt get a sig in a sig
4627 $nickname = self
::cleanSigInSig( $nickname );
4629 # If we're still here, make it a link to the user page
4630 $userText = wfEscapeWikiText( $username );
4631 $nickText = wfEscapeWikiText( $nickname );
4632 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4634 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4635 ->title( $this->getTitle() )->text();
4639 * Check that the user's signature contains no bad XML
4641 * @param string $text
4642 * @return string|bool An expanded string, or false if invalid.
4644 public function validateSig( $text ) {
4645 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4649 * Clean up signature text
4651 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4652 * 2) Substitute all transclusions
4654 * @param string $text
4655 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4656 * @return string Signature text
4658 public function cleanSig( $text, $parsing = false ) {
4661 $magicScopeVariable = $this->lock();
4662 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4665 # Option to disable this feature
4666 if ( !$this->mOptions
->getCleanSignatures() ) {
4670 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4671 # => Move this logic to braceSubstitution()
4672 $substWord = $this->magicWordFactory
->get( 'subst' );
4673 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4674 $substText = '{{' . $substWord->getSynonym( 0 );
4676 $text = preg_replace( $substRegex, $substText, $text );
4677 $text = self
::cleanSigInSig( $text );
4678 $dom = $this->preprocessToDom( $text );
4679 $frame = $this->getPreprocessor()->newFrame();
4680 $text = $frame->expand( $dom );
4683 $text = $this->mStripState
->unstripBoth( $text );
4690 * Strip 3, 4 or 5 tildes out of signatures.
4692 * @param string $text
4693 * @return string Signature text with /~{3,5}/ removed
4695 public static function cleanSigInSig( $text ) {
4696 $text = preg_replace( '/~{3,5}/', '', $text );
4701 * Set up some variables which are usually set up in parse()
4702 * so that an external function can call some class members with confidence
4704 * @param Title|null $title
4705 * @param ParserOptions $options
4706 * @param int $outputType
4707 * @param bool $clearState
4709 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4710 $outputType, $clearState = true
4712 $this->startParse( $title, $options, $outputType, $clearState );
4716 * @param Title|null $title
4717 * @param ParserOptions $options
4718 * @param int $outputType
4719 * @param bool $clearState
4721 private function startParse( Title
$title = null, ParserOptions
$options,
4722 $outputType, $clearState = true
4724 $this->setTitle( $title );
4725 $this->mOptions
= $options;
4726 $this->setOutputType( $outputType );
4727 if ( $clearState ) {
4728 $this->clearState();
4733 * Wrapper for preprocess()
4735 * @param string $text The text to preprocess
4736 * @param ParserOptions $options
4737 * @param Title|null $title Title object or null to use $wgTitle
4740 public function transformMsg( $text, $options, $title = null ) {
4741 static $executing = false;
4743 # Guard against infinite recursion
4754 $text = $this->preprocess( $text, $title, $options );
4761 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4762 * The callback should have the following form:
4763 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4765 * Transform and return $text. Use $parser for any required context, e.g. use
4766 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4768 * Hooks may return extended information by returning an array, of which the
4769 * first numbered element (index 0) must be the return string, and all other
4770 * entries are extracted into local variables within an internal function
4771 * in the Parser class.
4773 * This interface (introduced r61913) appears to be undocumented, but
4774 * 'markerType' is used by some core tag hooks to override which strip
4775 * array their results are placed in. **Use great caution if attempting
4776 * this interface, as it is not documented and injudicious use could smash
4777 * private variables.**
4779 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4780 * @param callable $callback The callback function (and object) to use for the tag
4781 * @throws MWException
4782 * @return callable|null The old value of the mTagHooks array associated with the hook
4784 public function setHook( $tag, callable
$callback ) {
4785 $tag = strtolower( $tag );
4786 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4787 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4789 $oldVal = $this->mTagHooks
[$tag] ??
null;
4790 $this->mTagHooks
[$tag] = $callback;
4791 if ( !in_array( $tag, $this->mStripList
) ) {
4792 $this->mStripList
[] = $tag;
4799 * As setHook(), but letting the contents be parsed.
4801 * Transparent tag hooks are like regular XML-style tag hooks, except they
4802 * operate late in the transformation sequence, on HTML instead of wikitext.
4804 * This is probably obsoleted by things dealing with parser frames?
4805 * The only extension currently using it is geoserver.
4808 * @todo better document or deprecate this
4810 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4811 * @param callable $callback The callback function (and object) to use for the tag
4812 * @throws MWException
4813 * @return callable|null The old value of the mTagHooks array associated with the hook
4815 public function setTransparentTagHook( $tag, callable
$callback ) {
4816 $tag = strtolower( $tag );
4817 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4818 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4820 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4821 $this->mTransparentTagHooks
[$tag] = $callback;
4827 * Remove all tag hooks
4829 public function clearTagHooks() {
4830 $this->mTagHooks
= [];
4831 $this->mFunctionTagHooks
= [];
4832 $this->mStripList
= $this->mDefaultStripList
;
4836 * Create a function, e.g. {{sum:1|2|3}}
4837 * The callback function should have the form:
4838 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4840 * Or with Parser::SFH_OBJECT_ARGS:
4841 * function myParserFunction( $parser, $frame, $args ) { ... }
4843 * The callback may either return the text result of the function, or an array with the text
4844 * in element 0, and a number of flags in the other elements. The names of the flags are
4845 * specified in the keys. Valid flags are:
4846 * found The text returned is valid, stop processing the template. This
4848 * nowiki Wiki markup in the return value should be escaped
4849 * isHTML The returned text is HTML, armour it against wikitext transformation
4851 * @param string $id The magic word ID
4852 * @param callable $callback The callback function (and object) to use
4853 * @param int $flags A combination of the following flags:
4854 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4856 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4857 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4858 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4859 * the arguments, and to control the way they are expanded.
4861 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4862 * arguments, for instance:
4863 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4865 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4866 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4867 * working if/when this is changed.
4869 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4872 * Please read the documentation in includes/parser/Preprocessor.php for more information
4873 * about the methods available in PPFrame and PPNode.
4875 * @throws MWException
4876 * @return string|callable The old callback function for this name, if any
4878 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4879 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4880 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4882 # Add to function cache
4883 $mw = $this->magicWordFactory
->get( $id );
4885 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4888 $synonyms = $mw->getSynonyms();
4889 $sensitive = intval( $mw->isCaseSensitive() );
4891 foreach ( $synonyms as $syn ) {
4893 if ( !$sensitive ) {
4894 $syn = $this->getContentLanguage()->lc( $syn );
4897 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4900 # Remove trailing colon
4901 if ( substr( $syn, -1, 1 ) === ':' ) {
4902 $syn = substr( $syn, 0, -1 );
4904 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4910 * Get all registered function hook identifiers
4914 public function getFunctionHooks() {
4915 return array_keys( $this->mFunctionHooks
);
4919 * Create a tag function, e.g. "<test>some stuff</test>".
4920 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4921 * Unlike parser functions, their content is not preprocessed.
4922 * @param string $tag
4923 * @param callable $callback
4925 * @throws MWException
4928 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4929 $tag = strtolower( $tag );
4930 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4931 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4933 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4934 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4936 if ( !in_array( $tag, $this->mStripList
) ) {
4937 $this->mStripList
[] = $tag;
4944 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4945 * Placeholders created in Linker::link()
4947 * @param string &$text
4948 * @param int $options
4950 public function replaceLinkHolders( &$text, $options = 0 ) {
4951 $this->mLinkHolders
->replace( $text );
4955 * Replace "<!--LINK-->" link placeholders with plain text of links
4956 * (not HTML-formatted).
4958 * @param string $text
4961 public function replaceLinkHoldersText( $text ) {
4962 return $this->mLinkHolders
->replaceText( $text );
4966 * Renders an image gallery from a text with one line per image.
4967 * text labels may be given by using |-style alternative text. E.g.
4968 * Image:one.jpg|The number "1"
4969 * Image:tree.jpg|A tree
4970 * given as text will return the HTML of a gallery with two images,
4971 * labeled 'The number "1"' and
4974 * @param string $text
4975 * @param array $params
4976 * @return string HTML
4978 public function renderImageGallery( $text, $params ) {
4980 if ( isset( $params['mode'] ) ) {
4981 $mode = $params['mode'];
4985 $ig = ImageGalleryBase
::factory( $mode );
4986 } catch ( Exception
$e ) {
4987 // If invalid type set, fallback to default.
4988 $ig = ImageGalleryBase
::factory( false );
4991 $ig->setContextTitle( $this->mTitle
);
4992 $ig->setShowBytes( false );
4993 $ig->setShowDimensions( false );
4994 $ig->setShowFilename( false );
4995 $ig->setParser( $this );
4996 $ig->setHideBadImages();
4997 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
4999 if ( isset( $params['showfilename'] ) ) {
5000 $ig->setShowFilename( true );
5002 $ig->setShowFilename( false );
5004 if ( isset( $params['caption'] ) ) {
5005 $caption = $params['caption'];
5006 $caption = htmlspecialchars( $caption );
5007 $caption = $this->replaceInternalLinks( $caption );
5008 $ig->setCaptionHtml( $caption );
5010 if ( isset( $params['perrow'] ) ) {
5011 $ig->setPerRow( $params['perrow'] );
5013 if ( isset( $params['widths'] ) ) {
5014 $ig->setWidths( $params['widths'] );
5016 if ( isset( $params['heights'] ) ) {
5017 $ig->setHeights( $params['heights'] );
5019 $ig->setAdditionalOptions( $params );
5021 // Avoid PHP 7.1 warning from passing $this by reference
5023 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5025 $lines = StringUtils
::explode( "\n", $text );
5026 foreach ( $lines as $line ) {
5027 # match lines like these:
5028 # Image:someimage.jpg|This is some image
5030 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5032 if ( count( $matches ) == 0 ) {
5036 if ( strpos( $matches[0], '%' ) !== false ) {
5037 $matches[1] = rawurldecode( $matches[1] );
5039 $title = Title
::newFromText( $matches[1], NS_FILE
);
5040 if ( is_null( $title ) ) {
5041 # Bogus title. Ignore these so we don't bomb out later.
5045 # We need to get what handler the file uses, to figure out parameters.
5046 # Note, a hook can overide the file name, and chose an entirely different
5047 # file (which potentially could be of a different type and have different handler).
5050 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5051 [ $this, $title, &$options, &$descQuery ] );
5052 # Don't register it now, as TraditionalImageGallery does that later.
5053 $file = $this->fetchFileNoRegister( $title, $options );
5054 $handler = $file ?
$file->getHandler() : false;
5057 'img_alt' => 'gallery-internal-alt',
5058 'img_link' => 'gallery-internal-link',
5061 $paramMap = $paramMap +
$handler->getParamMap();
5062 // We don't want people to specify per-image widths.
5063 // Additionally the width parameter would need special casing anyhow.
5064 unset( $paramMap['img_width'] );
5067 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5072 $handlerOptions = [];
5073 if ( isset( $matches[3] ) ) {
5074 // look for an |alt= definition while trying not to break existing
5075 // captions with multiple pipes (|) in it, until a more sensible grammar
5076 // is defined for images in galleries
5078 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5079 // splitting on '|' is a bit odd, and different from makeImage.
5080 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5081 // Protect LanguageConverter markup
5082 $parameterMatches = StringUtils
::delimiterExplode(
5083 '-{', '}-', '|', $matches[3], true /* nested */
5086 foreach ( $parameterMatches as $parameterMatch ) {
5087 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5089 $paramName = $paramMap[$magicName];
5091 switch ( $paramName ) {
5092 case 'gallery-internal-alt':
5093 $alt = $this->stripAltText( $match, false );
5095 case 'gallery-internal-link':
5096 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5097 $chars = self
::EXT_LINK_URL_CLASS
;
5098 $addr = self
::EXT_LINK_ADDR
;
5099 $prots = $this->mUrlProtocols
;
5100 // check to see if link matches an absolute url, if not then it must be a wiki link.
5101 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5102 // Result of LanguageConverter::markNoConversion
5103 // invoked on an external link.
5104 $linkValue = substr( $linkValue, 4, -2 );
5106 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5108 $this->mOutput
->addExternalLink( $link );
5110 $localLinkTitle = Title
::newFromText( $linkValue );
5111 if ( $localLinkTitle !== null ) {
5112 $this->mOutput
->addLink( $localLinkTitle );
5113 $link = $localLinkTitle->getLinkURL();
5118 // Must be a handler specific parameter.
5119 if ( $handler->validateParam( $paramName, $match ) ) {
5120 $handlerOptions[$paramName] = $match;
5122 // Guess not, consider it as caption.
5123 wfDebug( "$parameterMatch failed parameter validation\n" );
5124 $label = $parameterMatch;
5130 $label = $parameterMatch;
5135 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5137 $html = $ig->toHTML();
5138 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5143 * @param MediaHandler $handler
5146 public function getImageParams( $handler ) {
5148 $handlerClass = get_class( $handler );
5152 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5153 # Initialise static lists
5154 static $internalParamNames = [
5155 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5156 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5157 'bottom', 'text-bottom' ],
5158 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5159 'upright', 'border', 'link', 'alt', 'class' ],
5161 static $internalParamMap;
5162 if ( !$internalParamMap ) {
5163 $internalParamMap = [];
5164 foreach ( $internalParamNames as $type => $names ) {
5165 foreach ( $names as $name ) {
5166 // For grep: img_left, img_right, img_center, img_none,
5167 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5168 // img_bottom, img_text_bottom,
5169 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5170 // img_border, img_link, img_alt, img_class
5171 $magicName = str_replace( '-', '_', "img_$name" );
5172 $internalParamMap[$magicName] = [ $type, $name ];
5177 # Add handler params
5178 $paramMap = $internalParamMap;
5180 $handlerParamMap = $handler->getParamMap();
5181 foreach ( $handlerParamMap as $magic => $paramName ) {
5182 $paramMap[$magic] = [ 'handler', $paramName ];
5185 $this->mImageParams
[$handlerClass] = $paramMap;
5186 $this->mImageParamsMagicArray
[$handlerClass] =
5187 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5189 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5193 * Parse image options text and use it to make an image
5195 * @param Title $title
5196 * @param string $options
5197 * @param LinkHolderArray|bool $holders
5198 * @return string HTML
5200 public function makeImage( $title, $options, $holders = false ) {
5201 # Check if the options text is of the form "options|alt text"
5203 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5204 # * left no resizing, just left align. label is used for alt= only
5205 # * right same, but right aligned
5206 # * none same, but not aligned
5207 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5208 # * center center the image
5209 # * frame Keep original image size, no magnify-button.
5210 # * framed Same as "frame"
5211 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5212 # * upright reduce width for upright images, rounded to full __0 px
5213 # * border draw a 1px border around the image
5214 # * alt Text for HTML alt attribute (defaults to empty)
5215 # * class Set a class for img node
5216 # * link Set the target of the image link. Can be external, interwiki, or local
5217 # vertical-align values (no % or length right now):
5227 # Protect LanguageConverter markup when splitting into parts
5228 $parts = StringUtils
::delimiterExplode(
5229 '-{', '}-', '|', $options, true /* allow nesting */
5232 # Give extensions a chance to select the file revision for us
5235 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5236 [ $this, $title, &$options, &$descQuery ] );
5237 # Fetch and register the file (file title may be different via hooks)
5238 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5241 $handler = $file ?
$file->getHandler() : false;
5243 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5246 $this->addTrackingCategory( 'broken-file-category' );
5249 # Process the input parameters
5251 $params = [ 'frame' => [], 'handler' => [],
5252 'horizAlign' => [], 'vertAlign' => [] ];
5253 $seenformat = false;
5254 foreach ( $parts as $part ) {
5255 $part = trim( $part );
5256 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5258 if ( isset( $paramMap[$magicName] ) ) {
5259 list( $type, $paramName ) = $paramMap[$magicName];
5261 # Special case; width and height come in one variable together
5262 if ( $type === 'handler' && $paramName === 'width' ) {
5263 $parsedWidthParam = self
::parseWidthParam( $value );
5264 if ( isset( $parsedWidthParam['width'] ) ) {
5265 $width = $parsedWidthParam['width'];
5266 if ( $handler->validateParam( 'width', $width ) ) {
5267 $params[$type]['width'] = $width;
5271 if ( isset( $parsedWidthParam['height'] ) ) {
5272 $height = $parsedWidthParam['height'];
5273 if ( $handler->validateParam( 'height', $height ) ) {
5274 $params[$type]['height'] = $height;
5278 # else no validation -- T15436
5280 if ( $type === 'handler' ) {
5281 # Validate handler parameter
5282 $validated = $handler->validateParam( $paramName, $value );
5284 # Validate internal parameters
5285 switch ( $paramName ) {
5289 # @todo FIXME: Possibly check validity here for
5290 # manualthumb? downstream behavior seems odd with
5291 # missing manual thumbs.
5293 $value = $this->stripAltText( $value, $holders );
5296 $chars = self
::EXT_LINK_URL_CLASS
;
5297 $addr = self
::EXT_LINK_ADDR
;
5298 $prots = $this->mUrlProtocols
;
5299 if ( $value === '' ) {
5300 $paramName = 'no-link';
5303 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5304 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5305 $paramName = 'link-url';
5306 $this->mOutput
->addExternalLink( $value );
5307 if ( $this->mOptions
->getExternalLinkTarget() ) {
5308 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5313 $linkTitle = Title
::newFromText( $value );
5315 $paramName = 'link-title';
5316 $value = $linkTitle;
5317 $this->mOutput
->addLink( $linkTitle );
5325 // use first appearing option, discard others.
5326 $validated = !$seenformat;
5330 # Most other things appear to be empty or numeric...
5331 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5336 $params[$type][$paramName] = $value;
5340 if ( !$validated ) {
5345 # Process alignment parameters
5346 if ( $params['horizAlign'] ) {
5347 $params['frame']['align'] = key( $params['horizAlign'] );
5349 if ( $params['vertAlign'] ) {
5350 $params['frame']['valign'] = key( $params['vertAlign'] );
5353 $params['frame']['caption'] = $caption;
5355 # Will the image be presented in a frame, with the caption below?
5356 $imageIsFramed = isset( $params['frame']['frame'] )
5357 ||
isset( $params['frame']['framed'] )
5358 ||
isset( $params['frame']['thumbnail'] )
5359 ||
isset( $params['frame']['manualthumb'] );
5361 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5362 # came to also set the caption, ordinary text after the image -- which
5363 # makes no sense, because that just repeats the text multiple times in
5364 # screen readers. It *also* came to set the title attribute.
5365 # Now that we have an alt attribute, we should not set the alt text to
5366 # equal the caption: that's worse than useless, it just repeats the
5367 # text. This is the framed/thumbnail case. If there's no caption, we
5368 # use the unnamed parameter for alt text as well, just for the time be-
5369 # ing, if the unnamed param is set and the alt param is not.
5370 # For the future, we need to figure out if we want to tweak this more,
5371 # e.g., introducing a title= parameter for the title; ignoring the un-
5372 # named parameter entirely for images without a caption; adding an ex-
5373 # plicit caption= parameter and preserving the old magic unnamed para-
5375 if ( $imageIsFramed ) { # Framed image
5376 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5377 # No caption or alt text, add the filename as the alt text so
5378 # that screen readers at least get some description of the image
5379 $params['frame']['alt'] = $title->getText();
5381 # Do not set $params['frame']['title'] because tooltips don't make sense
5383 } else { # Inline image
5384 if ( !isset( $params['frame']['alt'] ) ) {
5385 # No alt text, use the "caption" for the alt text
5386 if ( $caption !== '' ) {
5387 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5389 # No caption, fall back to using the filename for the
5391 $params['frame']['alt'] = $title->getText();
5394 # Use the "caption" for the tooltip text
5395 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5398 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5400 # Linker does the rest
5401 $time = $options['time'] ??
false;
5402 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5403 $time, $descQuery, $this->mOptions
->getThumbSize() );
5405 # Give the handler a chance to modify the parser object
5407 $handler->parserTransformHook( $this, $file );
5414 * @param string $caption
5415 * @param LinkHolderArray|bool $holders
5416 * @return mixed|string
5418 protected function stripAltText( $caption, $holders ) {
5419 # Strip bad stuff out of the title (tooltip). We can't just use
5420 # replaceLinkHoldersText() here, because if this function is called
5421 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5423 $tooltip = $holders->replaceText( $caption );
5425 $tooltip = $this->replaceLinkHoldersText( $caption );
5428 # make sure there are no placeholders in thumbnail attributes
5429 # that are later expanded to html- so expand them now and
5431 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5432 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5438 * Set a flag in the output object indicating that the content is dynamic and
5439 * shouldn't be cached.
5440 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5442 public function disableCache() {
5443 wfDebug( "Parser output marked as uncacheable.\n" );
5444 if ( !$this->mOutput
) {
5445 throw new MWException( __METHOD__
.
5446 " can only be called when actually parsing something" );
5448 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5452 * Callback from the Sanitizer for expanding items found in HTML attribute
5453 * values, so they can be safely tested and escaped.
5455 * @param string &$text
5456 * @param bool|PPFrame $frame
5459 public function attributeStripCallback( &$text, $frame = false ) {
5460 $text = $this->replaceVariables( $text, $frame );
5461 $text = $this->mStripState
->unstripBoth( $text );
5470 public function getTags() {
5472 array_keys( $this->mTransparentTagHooks
),
5473 array_keys( $this->mTagHooks
),
5474 array_keys( $this->mFunctionTagHooks
)
5479 * Replace transparent tags in $text with the values given by the callbacks.
5481 * Transparent tag hooks are like regular XML-style tag hooks, except they
5482 * operate late in the transformation sequence, on HTML instead of wikitext.
5484 * @param string $text
5488 public function replaceTransparentTags( $text ) {
5490 $elements = array_keys( $this->mTransparentTagHooks
);
5491 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5494 foreach ( $matches as $marker => $data ) {
5495 list( $element, $content, $params, $tag ) = $data;
5496 $tagName = strtolower( $element );
5497 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5498 $output = call_user_func_array(
5499 $this->mTransparentTagHooks
[$tagName],
5500 [ $content, $params, $this ]
5505 $replacements[$marker] = $output;
5507 return strtr( $text, $replacements );
5511 * Break wikitext input into sections, and either pull or replace
5512 * some particular section's text.
5514 * External callers should use the getSection and replaceSection methods.
5516 * @param string $text Page wikitext
5517 * @param string|int $sectionId A section identifier string of the form:
5518 * "<flag1> - <flag2> - ... - <section number>"
5520 * Currently the only recognised flag is "T", which means the target section number
5521 * was derived during a template inclusion parse, in other words this is a template
5522 * section edit link. If no flags are given, it was an ordinary section edit link.
5523 * This flag is required to avoid a section numbering mismatch when a section is
5524 * enclosed by "<includeonly>" (T8563).
5526 * The section number 0 pulls the text before the first heading; other numbers will
5527 * pull the given section along with its lower-level subsections. If the section is
5528 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5530 * Section 0 is always considered to exist, even if it only contains the empty
5531 * string. If $text is the empty string and section 0 is replaced, $newText is
5534 * @param string $mode One of "get" or "replace"
5535 * @param string $newText Replacement text for section data.
5536 * @return string For "get", the extracted section text.
5537 * for "replace", the whole page with the section replaced.
5539 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5540 global $wgTitle; # not generally used but removes an ugly failure mode
5542 $magicScopeVariable = $this->lock();
5543 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5545 $frame = $this->getPreprocessor()->newFrame();
5547 # Process section extraction flags
5549 $sectionParts = explode( '-', $sectionId );
5550 $sectionIndex = array_pop( $sectionParts );
5551 foreach ( $sectionParts as $part ) {
5552 if ( $part === 'T' ) {
5553 $flags |
= self
::PTD_FOR_INCLUSION
;
5557 # Check for empty input
5558 if ( strval( $text ) === '' ) {
5559 # Only sections 0 and T-0 exist in an empty document
5560 if ( $sectionIndex == 0 ) {
5561 if ( $mode === 'get' ) {
5567 if ( $mode === 'get' ) {
5575 # Preprocess the text
5576 $root = $this->preprocessToDom( $text, $flags );
5578 # <h> nodes indicate section breaks
5579 # They can only occur at the top level, so we can find them by iterating the root's children
5580 $node = $root->getFirstChild();
5582 # Find the target section
5583 if ( $sectionIndex == 0 ) {
5584 # Section zero doesn't nest, level=big
5585 $targetLevel = 1000;
5588 if ( $node->getName() === 'h' ) {
5589 $bits = $node->splitHeading();
5590 if ( $bits['i'] == $sectionIndex ) {
5591 $targetLevel = $bits['level'];
5595 if ( $mode === 'replace' ) {
5596 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5598 $node = $node->getNextSibling();
5604 if ( $mode === 'get' ) {
5611 # Find the end of the section, including nested sections
5613 if ( $node->getName() === 'h' ) {
5614 $bits = $node->splitHeading();
5615 $curLevel = $bits['level'];
5616 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5620 if ( $mode === 'get' ) {
5621 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5623 $node = $node->getNextSibling();
5626 # Write out the remainder (in replace mode only)
5627 if ( $mode === 'replace' ) {
5628 # Output the replacement text
5629 # Add two newlines on -- trailing whitespace in $newText is conventionally
5630 # stripped by the editor, so we need both newlines to restore the paragraph gap
5631 # Only add trailing whitespace if there is newText
5632 if ( $newText != "" ) {
5633 $outText .= $newText . "\n\n";
5637 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5638 $node = $node->getNextSibling();
5642 if ( is_string( $outText ) ) {
5643 # Re-insert stripped tags
5644 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5651 * This function returns the text of a section, specified by a number ($section).
5652 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5653 * the first section before any such heading (section 0).
5655 * If a section contains subsections, these are also returned.
5657 * @param string $text Text to look in
5658 * @param string|int $sectionId Section identifier as a number or string
5659 * (e.g. 0, 1 or 'T-1').
5660 * @param string $defaultText Default to return if section is not found
5662 * @return string Text of the requested section
5664 public function getSection( $text, $sectionId, $defaultText = '' ) {
5665 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5669 * This function returns $oldtext after the content of the section
5670 * specified by $section has been replaced with $text. If the target
5671 * section does not exist, $oldtext is returned unchanged.
5673 * @param string $oldText Former text of the article
5674 * @param string|int $sectionId Section identifier as a number or string
5675 * (e.g. 0, 1 or 'T-1').
5676 * @param string $newText Replacing text
5678 * @return string Modified text
5680 public function replaceSection( $oldText, $sectionId, $newText ) {
5681 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5685 * Get the ID of the revision we are parsing
5689 public function getRevisionId() {
5690 return $this->mRevisionId
;
5694 * Get the revision object for $this->mRevisionId
5696 * @return Revision|null Either a Revision object or null
5697 * @since 1.23 (public since 1.23)
5699 public function getRevisionObject() {
5700 if ( !is_null( $this->mRevisionObject
) ) {
5701 return $this->mRevisionObject
;
5703 if ( is_null( $this->mRevisionId
) ) {
5707 $rev = call_user_func(
5708 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5711 # If the parse is for a new revision, then the callback should have
5712 # already been set to force the object and should match mRevisionId.
5713 # If not, try to fetch by mRevisionId for sanity.
5714 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5715 $rev = Revision
::newFromId( $this->mRevisionId
);
5718 $this->mRevisionObject
= $rev;
5720 return $this->mRevisionObject
;
5724 * Get the timestamp associated with the current revision, adjusted for
5725 * the default server-local timestamp
5728 public function getRevisionTimestamp() {
5729 if ( is_null( $this->mRevisionTimestamp
) ) {
5730 $revObject = $this->getRevisionObject();
5731 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5733 # The cryptic '' timezone parameter tells to use the site-default
5734 # timezone offset instead of the user settings.
5735 # Since this value will be saved into the parser cache, served
5736 # to other users, and potentially even used inside links and such,
5737 # it needs to be consistent for all visitors.
5738 $this->mRevisionTimestamp
= $this->getContentLanguage()->userAdjust( $timestamp, '' );
5741 return $this->mRevisionTimestamp
;
5745 * Get the name of the user that edited the last revision
5747 * @return string User name
5749 public function getRevisionUser() {
5750 if ( is_null( $this->mRevisionUser
) ) {
5751 $revObject = $this->getRevisionObject();
5753 # if this template is subst: the revision id will be blank,
5754 # so just use the current user's name
5756 $this->mRevisionUser
= $revObject->getUserText();
5757 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5758 $this->mRevisionUser
= $this->getUser()->getName();
5761 return $this->mRevisionUser
;
5765 * Get the size of the revision
5767 * @return int|null Revision size
5769 public function getRevisionSize() {
5770 if ( is_null( $this->mRevisionSize
) ) {
5771 $revObject = $this->getRevisionObject();
5773 # if this variable is subst: the revision id will be blank,
5774 # so just use the parser input size, because the own substituation
5775 # will change the size.
5777 $this->mRevisionSize
= $revObject->getSize();
5779 $this->mRevisionSize
= $this->mInputSize
;
5782 return $this->mRevisionSize
;
5786 * Mutator for $mDefaultSort
5788 * @param string $sort New value
5790 public function setDefaultSort( $sort ) {
5791 $this->mDefaultSort
= $sort;
5792 $this->mOutput
->setProperty( 'defaultsort', $sort );
5796 * Accessor for $mDefaultSort
5797 * Will use the empty string if none is set.
5799 * This value is treated as a prefix, so the
5800 * empty string is equivalent to sorting by
5805 public function getDefaultSort() {
5806 if ( $this->mDefaultSort
!== false ) {
5807 return $this->mDefaultSort
;
5814 * Accessor for $mDefaultSort
5815 * Unlike getDefaultSort(), will return false if none is set
5817 * @return string|bool
5819 public function getCustomDefaultSort() {
5820 return $this->mDefaultSort
;
5823 private static function getSectionNameFromStrippedText( $text ) {
5824 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5825 $text = Sanitizer
::decodeCharReferences( $text );
5826 $text = self
::normalizeSectionName( $text );
5830 private static function makeAnchor( $sectionName ) {
5831 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5834 private static function makeLegacyAnchor( $sectionName ) {
5835 global $wgFragmentMode;
5836 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5837 // ForAttribute() and ForLink() are the same for legacy encoding
5838 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5840 $id = Sanitizer
::escapeIdForLink( $sectionName );
5847 * Try to guess the section anchor name based on a wikitext fragment
5848 * presumably extracted from a heading, for example "Header" from
5851 * @param string $text
5852 * @return string Anchor (starting with '#')
5854 public function guessSectionNameFromWikiText( $text ) {
5855 # Strip out wikitext links(they break the anchor)
5856 $text = $this->stripSectionName( $text );
5857 $sectionName = self
::getSectionNameFromStrippedText( $text );
5858 return self
::makeAnchor( $sectionName );
5862 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5863 * instead, if possible. For use in redirects, since various versions
5864 * of Microsoft browsers interpret Location: headers as something other
5865 * than UTF-8, resulting in breakage.
5867 * @param string $text The section name
5868 * @return string Anchor (starting with '#')
5870 public function guessLegacySectionNameFromWikiText( $text ) {
5871 # Strip out wikitext links(they break the anchor)
5872 $text = $this->stripSectionName( $text );
5873 $sectionName = self
::getSectionNameFromStrippedText( $text );
5874 return self
::makeLegacyAnchor( $sectionName );
5878 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5879 * @param string $text Section name (plain text)
5880 * @return string Anchor (starting with '#')
5882 public static function guessSectionNameFromStrippedText( $text ) {
5883 $sectionName = self
::getSectionNameFromStrippedText( $text );
5884 return self
::makeAnchor( $sectionName );
5888 * Apply the same normalization as code making links to this section would
5890 * @param string $text
5893 private static function normalizeSectionName( $text ) {
5894 # T90902: ensure the same normalization is applied for IDs as to links
5895 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5898 $parts = $titleParser->splitTitleString( "#$text" );
5899 } catch ( MalformedTitleException
$ex ) {
5902 return $parts['fragment'];
5906 * Strips a text string of wikitext for use in a section anchor
5908 * Accepts a text string and then removes all wikitext from the
5909 * string and leaves only the resultant text (i.e. the result of
5910 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5911 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5912 * to create valid section anchors by mimicing the output of the
5913 * parser when headings are parsed.
5915 * @param string $text Text string to be stripped of wikitext
5916 * for use in a Section anchor
5917 * @return string Filtered text string
5919 public function stripSectionName( $text ) {
5920 # Strip internal link markup
5921 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5922 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5924 # Strip external link markup
5925 # @todo FIXME: Not tolerant to blank link text
5926 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5927 # on how many empty links there are on the page - need to figure that out.
5928 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5930 # Parse wikitext quotes (italics & bold)
5931 $text = $this->doQuotes( $text );
5934 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5939 * strip/replaceVariables/unstrip for preprocessor regression testing
5941 * @param string $text
5942 * @param Title $title
5943 * @param ParserOptions $options
5944 * @param int $outputType
5948 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5949 $outputType = self
::OT_HTML
5951 $magicScopeVariable = $this->lock();
5952 $this->startParse( $title, $options, $outputType, true );
5954 $text = $this->replaceVariables( $text );
5955 $text = $this->mStripState
->unstripBoth( $text );
5956 $text = Sanitizer
::removeHTMLtags( $text );
5961 * @param string $text
5962 * @param Title $title
5963 * @param ParserOptions $options
5966 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5967 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5971 * @param string $text
5972 * @param Title $title
5973 * @param ParserOptions $options
5976 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5977 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5981 * Call a callback function on all regions of the given text that are not
5982 * inside strip markers, and replace those regions with the return value
5983 * of the callback. For example, with input:
5987 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5988 * two strings will be replaced with the value returned by the callback in
5992 * @param callable $callback
5996 public function markerSkipCallback( $s, $callback ) {
5999 while ( $i < strlen( $s ) ) {
6000 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6001 if ( $markerStart === false ) {
6002 $out .= call_user_func( $callback, substr( $s, $i ) );
6005 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6006 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6007 if ( $markerEnd === false ) {
6008 $out .= substr( $s, $markerStart );
6011 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6012 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6021 * Remove any strip markers found in the given text.
6023 * @param string $text
6026 public function killMarkers( $text ) {
6027 return $this->mStripState
->killMarkers( $text );
6031 * Save the parser state required to convert the given half-parsed text to
6032 * HTML. "Half-parsed" in this context means the output of
6033 * recursiveTagParse() or internalParse(). This output has strip markers
6034 * from replaceVariables (extensionSubstitution() etc.), and link
6035 * placeholders from replaceLinkHolders().
6037 * Returns an array which can be serialized and stored persistently. This
6038 * array can later be loaded into another parser instance with
6039 * unserializeHalfParsedText(). The text can then be safely incorporated into
6040 * the return value of a parser hook.
6042 * @deprecated since 1.31
6043 * @param string $text
6047 public function serializeHalfParsedText( $text ) {
6048 wfDeprecated( __METHOD__
, '1.31' );
6051 'version' => self
::HALF_PARSED_VERSION
,
6052 'stripState' => $this->mStripState
->getSubState( $text ),
6053 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6059 * Load the parser state given in the $data array, which is assumed to
6060 * have been generated by serializeHalfParsedText(). The text contents is
6061 * extracted from the array, and its markers are transformed into markers
6062 * appropriate for the current Parser instance. This transformed text is
6063 * returned, and can be safely included in the return value of a parser
6066 * If the $data array has been stored persistently, the caller should first
6067 * check whether it is still valid, by calling isValidHalfParsedText().
6069 * @deprecated since 1.31
6070 * @param array $data Serialized data
6071 * @throws MWException
6074 public function unserializeHalfParsedText( $data ) {
6075 wfDeprecated( __METHOD__
, '1.31' );
6076 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6077 throw new MWException( __METHOD__
. ': invalid version' );
6080 # First, extract the strip state.
6081 $texts = [ $data['text'] ];
6082 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6084 # Now renumber links
6085 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6087 # Should be good to go.
6092 * Returns true if the given array, presumed to be generated by
6093 * serializeHalfParsedText(), is compatible with the current version of the
6096 * @deprecated since 1.31
6097 * @param array $data
6101 public function isValidHalfParsedText( $data ) {
6102 wfDeprecated( __METHOD__
, '1.31' );
6103 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6107 * Parsed a width param of imagelink like 300px or 200x300px
6109 * @param string $value
6110 * @param bool $parseHeight
6115 public static function parseWidthParam( $value, $parseHeight = true ) {
6116 $parsedWidthParam = [];
6117 if ( $value === '' ) {
6118 return $parsedWidthParam;
6121 # (T15500) In both cases (width/height and width only),
6122 # permit trailing "px" for backward compatibility.
6123 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6124 $width = intval( $m[1] );
6125 $height = intval( $m[2] );
6126 $parsedWidthParam['width'] = $width;
6127 $parsedWidthParam['height'] = $height;
6128 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6129 $width = intval( $value );
6130 $parsedWidthParam['width'] = $width;
6132 return $parsedWidthParam;
6136 * Lock the current instance of the parser.
6138 * This is meant to stop someone from calling the parser
6139 * recursively and messing up all the strip state.
6141 * @throws MWException If parser is in a parse
6142 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6144 protected function lock() {
6145 if ( $this->mInParse
) {
6146 throw new MWException( "Parser state cleared while parsing. "
6147 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6150 // Save the backtrace when locking, so that if some code tries locking again,
6151 // we can print the lock owner's backtrace for easier debugging
6153 $this->mInParse
= $e->getTraceAsString();
6155 $recursiveCheck = new ScopedCallback( function () {
6156 $this->mInParse
= false;
6159 return $recursiveCheck;
6163 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6165 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6166 * or if there is more than one <p/> tag in the input HTML.
6168 * @param string $html
6172 public static function stripOuterParagraph( $html ) {
6174 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6175 if ( strpos( $m[1], '</p>' ) === false ) {
6184 * Return this parser if it is not doing anything, otherwise
6185 * get a fresh parser. You can use this method by doing
6186 * $myParser = $wgParser->getFreshParser(), or more simply
6187 * $wgParser->getFreshParser()->parse( ... );
6188 * if you're unsure if $wgParser is safe to use.
6191 * @return Parser A parser object that is not parsing anything
6193 public function getFreshParser() {
6194 global $wgParserConf;
6195 if ( $this->mInParse
) {
6196 return new $wgParserConf['class']( $wgParserConf );
6203 * Set's up the PHP implementation of OOUI for use in this request
6204 * and instructs OutputPage to enable OOUI for itself.
6208 public function enableOOUI() {
6209 OutputPage
::setupOOUI();
6210 $this->mOutput
->setEnableOOUI( true );