3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @defgroup Parser Parser
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
37 * There are seven main entry points into the Parser class:
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
57 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
60 * $wgNamespacesWithSubpages
62 * @par Settings only within ParserOptions:
63 * $wgAllowExternalImages
64 * $wgAllowSpecialInclusion
72 * Update this version number when the ParserOutput format
73 * changes in an incompatible way, so the parser cache
74 * can automatically discard old data.
76 const VERSION
= '1.6.4';
79 * Update this version number when the output of serialiseHalfParsedText()
80 * changes in an incompatible way
82 const HALF_PARSED_VERSION
= 2;
84 # Flags for Parser::setFunctionHook
85 const SFH_NO_HASH
= 1;
86 const SFH_OBJECT_ARGS
= 2;
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
92 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
93 # uses to replace invalid HTML characters.
94 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
95 # Simplified expression to match an IPv4 or IPv6 address, or
96 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
97 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
98 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
99 // phpcs:ignore Generic.Files.LineLength
100 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
101 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
103 # Regular expression for a non-newline space
104 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
118 * @var string Prefix and suffix for temporary replacement strings
119 * for the multipass parser.
121 * \x7f should never appear in input as it's disallowed in XML.
122 * Using it at the front also gives us a little extra robustness
123 * since it shouldn't match when butted up against identifier-like
126 * Must not consist of all title characters, or else it will change
127 * the behavior of <nowiki> in a link.
129 * Must have a character that needs escaping in attributes, otherwise
130 * someone could put a strip marker in an attribute, to get around
131 * escaping quote marks, and break out of the attribute. Thus we add
134 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
135 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
137 # Markers used for wrapping the table of contents
138 const TOC_START
= '<mw:toc>';
139 const TOC_END
= '</mw:toc>';
141 /** @var int Assume that no output will later be saved this many seconds after parsing */
145 public $mTagHooks = [];
146 public $mTransparentTagHooks = [];
147 public $mFunctionHooks = [];
148 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
149 public $mFunctionTagHooks = [];
150 public $mStripList = [];
151 public $mDefaultStripList = [];
152 public $mVarCache = [];
153 public $mImageParams = [];
154 public $mImageParamsMagicArray = [];
155 public $mMarkerIndex = 0;
157 * @var bool Whether firstCallInit still needs to be called
159 public $mFirstCall = true;
161 # Initialised by initialiseVariables()
164 * @var MagicWordArray
169 * @var MagicWordArray
172 # Initialised in constructor
173 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
175 # Initialized in getPreprocessor()
176 /** @var Preprocessor */
177 public $mPreprocessor;
179 # Cleared with clearState():
191 public $mIncludeCount;
193 * @var LinkHolderArray
195 public $mLinkHolders;
198 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
199 public $mDefaultSort;
200 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
201 public $mExpensiveFunctionCount; # number of expensive parser function calls
202 public $mShowToc, $mForceTocPosition;
207 public $mUser; # User object; only used when doing pre-save transform
210 # These are variables reset at least once per parse regardless of $clearState
220 public $mTitle; # Title context, used for self-link rendering and similar things
221 public $mOutputType; # Output type, one of the OT_xxx constants
222 public $ot; # Shortcut alias, see setOutputType()
223 public $mRevisionObject; # The revision object of the specified revision ID
224 public $mRevisionId; # ID to display in {{REVISIONID}} tags
225 public $mRevisionTimestamp; # The timestamp of the specified revision ID
226 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
227 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
228 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
229 public $mInputSize = false; # For {{PAGESIZE}} on current page.
232 * @var string Deprecated accessor for the strip marker prefix.
233 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
235 public $mUniqPrefix = self
::MARKER_PREFIX
;
238 * @var array Array with the language name of each language link (i.e. the
239 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
240 * duplicate language links to the ParserOutput.
242 public $mLangLinkLanguages;
245 * @var MapCacheLRU|null
248 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
250 public $currentRevisionCache;
253 * @var bool|string Recursive call protection.
254 * This variable should be treated as if it were private.
256 public $mInParse = false;
258 /** @var SectionProfiler */
259 protected $mProfiler;
264 protected $mLinkRenderer;
266 /** @var MagicWordFactory */
267 private $magicWordFactory;
271 * @param MagicWordFactory|null $magicWordFactory
273 public function __construct( $conf = [], MagicWordFactory
$magicWordFactory = null ) {
274 $this->mConf
= $conf;
275 $this->mUrlProtocols
= wfUrlProtocols();
276 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
277 self
::EXT_LINK_ADDR
.
278 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
279 if ( isset( $conf['preprocessorClass'] ) ) {
280 $this->mPreprocessorClass
= $conf['preprocessorClass'];
281 } elseif ( defined( 'HPHP_VERSION' ) ) {
282 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
283 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
284 } elseif ( extension_loaded( 'domxml' ) ) {
285 # PECL extension that conflicts with the core DOM extension (T15770)
286 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
287 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
288 } elseif ( extension_loaded( 'dom' ) ) {
289 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
291 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
293 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
295 $this->magicWordFactory
= $magicWordFactory;
296 if ( !$magicWordFactory ) {
297 $this->magicWordFactory
= MediaWikiServices
::getInstance()->getMagicWordFactory();
302 * Reduce memory usage to reduce the impact of circular references
304 public function __destruct() {
305 if ( isset( $this->mLinkHolders
) ) {
306 unset( $this->mLinkHolders
);
308 foreach ( $this as $name => $value ) {
309 unset( $this->$name );
314 * Allow extensions to clean up when the parser is cloned
316 public function __clone() {
317 $this->mInParse
= false;
319 // T58226: When you create a reference "to" an object field, that
320 // makes the object field itself be a reference too (until the other
321 // reference goes out of scope). When cloning, any field that's a
322 // reference is copied as a reference in the new object. Both of these
323 // are defined PHP5 behaviors, as inconvenient as it is for us when old
324 // hooks from PHP4 days are passing fields by reference.
325 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
326 // Make a non-reference copy of the field, then rebind the field to
327 // reference the new copy.
333 Hooks
::run( 'ParserCloned', [ $this ] );
337 * Do various kinds of initialisation on the first call of the parser
339 public function firstCallInit() {
340 if ( !$this->mFirstCall
) {
343 $this->mFirstCall
= false;
345 CoreParserFunctions
::register( $this );
346 CoreTagHooks
::register( $this );
347 $this->initialiseVariables();
349 // Avoid PHP 7.1 warning from passing $this by reference
351 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
359 public function clearState() {
360 $this->firstCallInit();
361 $this->mOutput
= new ParserOutput
;
362 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
363 $this->mAutonumber
= 0;
364 $this->mIncludeCount
= [];
365 $this->mLinkHolders
= new LinkHolderArray( $this );
367 $this->mRevisionObject
= $this->mRevisionTimestamp
=
368 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
369 $this->mVarCache
= [];
371 $this->mLangLinkLanguages
= [];
372 $this->currentRevisionCache
= null;
374 $this->mStripState
= new StripState( $this );
376 # Clear these on every parse, T6549
377 $this->mTplRedirCache
= $this->mTplDomCache
= [];
379 $this->mShowToc
= true;
380 $this->mForceTocPosition
= false;
381 $this->mIncludeSizes
= [
385 $this->mPPNodeCount
= 0;
386 $this->mGeneratedPPNodeCount
= 0;
387 $this->mHighestExpansionDepth
= 0;
388 $this->mDefaultSort
= false;
389 $this->mHeadings
= [];
390 $this->mDoubleUnderscores
= [];
391 $this->mExpensiveFunctionCount
= 0;
394 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
395 $this->mPreprocessor
= null;
398 $this->mProfiler
= new SectionProfiler();
400 // Avoid PHP 7.1 warning from passing $this by reference
402 Hooks
::run( 'ParserClearState', [ &$parser ] );
406 * Convert wikitext to HTML
407 * Do not call this function recursively.
409 * @param string $text Text we want to parse
410 * @param Title $title
411 * @param ParserOptions $options
412 * @param bool $linestart
413 * @param bool $clearState
414 * @param int|null $revid Number to pass in {{REVISIONID}}
415 * @return ParserOutput A ParserOutput
417 public function parse(
418 $text, Title
$title, ParserOptions
$options,
419 $linestart = true, $clearState = true, $revid = null
422 // We use U+007F DELETE to construct strip markers, so we have to make
423 // sure that this character does not occur in the input text.
424 $text = strtr( $text, "\x7f", "?" );
425 $magicScopeVariable = $this->lock();
427 // Strip U+0000 NULL (T159174)
428 $text = str_replace( "\000", '', $text );
430 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
432 $this->currentRevisionCache
= null;
433 $this->mInputSize
= strlen( $text );
434 if ( $this->mOptions
->getEnableLimitReport() ) {
435 $this->mOutput
->resetParseStartTime();
438 $oldRevisionId = $this->mRevisionId
;
439 $oldRevisionObject = $this->mRevisionObject
;
440 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
441 $oldRevisionUser = $this->mRevisionUser
;
442 $oldRevisionSize = $this->mRevisionSize
;
443 if ( $revid !== null ) {
444 $this->mRevisionId
= $revid;
445 $this->mRevisionObject
= null;
446 $this->mRevisionTimestamp
= null;
447 $this->mRevisionUser
= null;
448 $this->mRevisionSize
= null;
451 // Avoid PHP 7.1 warning from passing $this by reference
453 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
455 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
456 $text = $this->internalParse( $text );
457 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
459 $text = $this->internalParseHalfParsed( $text, true, $linestart );
462 * A converted title will be provided in the output object if title and
463 * content conversion are enabled, the article text does not contain
464 * a conversion-suppressing double-underscore tag, and no
465 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
466 * automatic link conversion.
468 if ( !( $options->getDisableTitleConversion()
469 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
470 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
471 ||
$this->mOutput
->getDisplayTitle() !== false )
473 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
474 if ( $convruletitle ) {
475 $this->mOutput
->setTitleText( $convruletitle );
477 $titleText = $this->getTargetLanguage()->convertTitle( $title );
478 $this->mOutput
->setTitleText( $titleText );
482 # Compute runtime adaptive expiry if set
483 $this->mOutput
->finalizeAdaptiveCacheExpiry();
485 # Warn if too many heavyweight parser functions were used
486 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
487 $this->limitationWarn( 'expensive-parserfunction',
488 $this->mExpensiveFunctionCount
,
489 $this->mOptions
->getExpensiveParserFunctionLimit()
493 # Information on limits, for the benefit of users who try to skirt them
494 if ( $this->mOptions
->getEnableLimitReport() ) {
495 $text .= $this->makeLimitReport();
498 # Wrap non-interface parser output in a <div> so it can be targeted
500 $class = $this->mOptions
->getWrapOutputClass();
501 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
502 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
505 $this->mOutput
->setText( $text );
507 $this->mRevisionId
= $oldRevisionId;
508 $this->mRevisionObject
= $oldRevisionObject;
509 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
510 $this->mRevisionUser
= $oldRevisionUser;
511 $this->mRevisionSize
= $oldRevisionSize;
512 $this->mInputSize
= false;
513 $this->currentRevisionCache
= null;
515 return $this->mOutput
;
519 * Set the limit report data in the current ParserOutput, and return the
520 * limit report HTML comment.
524 protected function makeLimitReport() {
525 global $wgShowHostnames;
527 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
529 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
530 if ( $cpuTime !== null ) {
531 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
532 sprintf( "%.3f", $cpuTime )
536 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
537 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
538 sprintf( "%.3f", $wallTime )
541 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
542 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
544 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
545 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
547 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
548 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
550 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
551 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
553 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
554 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
556 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
557 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
560 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
561 $this->mOutput
->setLimitReportData( $key, $value );
564 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
566 $limitReport = "NewPP limit report\n";
567 if ( $wgShowHostnames ) {
568 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
570 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
571 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
572 $limitReport .= 'Dynamic content: ' .
573 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
576 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
577 if ( Hooks
::run( 'ParserLimitReportFormat',
578 [ $key, &$value, &$limitReport, false, false ]
580 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
581 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
582 ->inLanguage( 'en' )->useDatabase( false );
583 if ( !$valueMsg->exists() ) {
584 $valueMsg = new RawMessage( '$1' );
586 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
587 $valueMsg->params( $value );
588 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
592 // Since we're not really outputting HTML, decode the entities and
593 // then re-encode the things that need hiding inside HTML comments.
594 $limitReport = htmlspecialchars_decode( $limitReport );
595 // Run deprecated hook
596 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
598 // Sanitize for comment. Note '‐' in the replacement is U+2010,
599 // which looks much like the problematic '-'.
600 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
601 $text = "\n<!-- \n$limitReport-->\n";
603 // Add on template profiling data in human/machine readable way
604 $dataByFunc = $this->mProfiler
->getFunctionStats();
605 uasort( $dataByFunc, function ( $a, $b ) {
606 return $b['real'] <=> $a['real']; // descending order
609 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
610 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
611 $item['%real'], $item['real'], $item['calls'],
612 htmlspecialchars( $item['name'] ) );
614 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
615 $text .= implode( "\n", $profileReport ) . "\n-->\n";
617 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
619 // Add other cache related metadata
620 if ( $wgShowHostnames ) {
621 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
623 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
624 $this->mOutput
->getCacheTime() );
625 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
626 $this->mOutput
->getCacheExpiry() );
627 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
628 $this->mOutput
->hasDynamicContent() );
630 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
631 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
632 $this->mTitle
->getPrefixedDBkey() );
638 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
639 * can be called from an extension tag hook.
641 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
642 * instead, which means that lists and links have not been fully parsed yet,
643 * and strip markers are still present.
645 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
647 * Use this function if you're a parser tag hook and you want to parse
648 * wikitext before or after applying additional transformations, and you
649 * intend to *return the result as hook output*, which will cause it to go
650 * through the rest of parsing process automatically.
652 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
653 * $text are not expanded
655 * @param string $text Text extension wants to have parsed
656 * @param bool|PPFrame $frame The frame to use for expanding any template variables
657 * @return string UNSAFE half-parsed HTML
659 public function recursiveTagParse( $text, $frame = false ) {
660 // Avoid PHP 7.1 warning from passing $this by reference
662 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
663 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
664 $text = $this->internalParse( $text, false, $frame );
669 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
670 * point can be called from an extension tag hook.
672 * The output of this function is fully-parsed HTML that is safe for output.
673 * If you're a parser tag hook, you might want to use recursiveTagParse()
676 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
677 * $text are not expanded
681 * @param string $text Text extension wants to have parsed
682 * @param bool|PPFrame $frame The frame to use for expanding any template variables
683 * @return string Fully parsed HTML
685 public function recursiveTagParseFully( $text, $frame = false ) {
686 $text = $this->recursiveTagParse( $text, $frame );
687 $text = $this->internalParseHalfParsed( $text, false );
692 * Expand templates and variables in the text, producing valid, static wikitext.
693 * Also removes comments.
694 * Do not call this function recursively.
695 * @param string $text
696 * @param Title|null $title
697 * @param ParserOptions $options
698 * @param int|null $revid
699 * @param bool|PPFrame $frame
700 * @return mixed|string
702 public function preprocess( $text, Title
$title = null,
703 ParserOptions
$options, $revid = null, $frame = false
705 $magicScopeVariable = $this->lock();
706 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
707 if ( $revid !== null ) {
708 $this->mRevisionId
= $revid;
710 // Avoid PHP 7.1 warning from passing $this by reference
712 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
713 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
714 $text = $this->replaceVariables( $text, $frame );
715 $text = $this->mStripState
->unstripBoth( $text );
720 * Recursive parser entry point that can be called from an extension tag
723 * @param string $text Text to be expanded
724 * @param bool|PPFrame $frame The frame to use for expanding any template variables
728 public function recursivePreprocess( $text, $frame = false ) {
729 $text = $this->replaceVariables( $text, $frame );
730 $text = $this->mStripState
->unstripBoth( $text );
735 * Process the wikitext for the "?preload=" feature. (T7210)
737 * "<noinclude>", "<includeonly>" etc. are parsed as for template
738 * transclusion, comments, templates, arguments, tags hooks and parser
739 * functions are untouched.
741 * @param string $text
742 * @param Title $title
743 * @param ParserOptions $options
744 * @param array $params
747 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
748 $msg = new RawMessage( $text );
749 $text = $msg->params( $params )->plain();
751 # Parser (re)initialisation
752 $magicScopeVariable = $this->lock();
753 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
755 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
756 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
757 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
758 $text = $this->mStripState
->unstripBoth( $text );
763 * Set the current user.
764 * Should only be used when doing pre-save transform.
766 * @param User|null $user User object or null (to reset)
768 public function setUser( $user ) {
769 $this->mUser
= $user;
773 * Set the context title
777 public function setTitle( $t ) {
779 $t = Title
::newFromText( 'NO TITLE' );
782 if ( $t->hasFragment() ) {
783 # Strip the fragment to avoid various odd effects
784 $this->mTitle
= $t->createFragmentTarget( '' );
791 * Accessor for the Title object
795 public function getTitle() {
796 return $this->mTitle
;
800 * Accessor/mutator for the Title object
802 * @param Title|null $x Title object or null to just get the current one
805 public function Title( $x = null ) {
806 return wfSetVar( $this->mTitle
, $x );
810 * Set the output type
812 * @param int $ot New value
814 public function setOutputType( $ot ) {
815 $this->mOutputType
= $ot;
818 'html' => $ot == self
::OT_HTML
,
819 'wiki' => $ot == self
::OT_WIKI
,
820 'pre' => $ot == self
::OT_PREPROCESS
,
821 'plain' => $ot == self
::OT_PLAIN
,
826 * Accessor/mutator for the output type
828 * @param int|null $x New value or null to just get the current one
831 public function OutputType( $x = null ) {
832 return wfSetVar( $this->mOutputType
, $x );
836 * Get the ParserOutput object
838 * @return ParserOutput
840 public function getOutput() {
841 return $this->mOutput
;
845 * Get the ParserOptions object
847 * @return ParserOptions
849 public function getOptions() {
850 return $this->mOptions
;
854 * Accessor/mutator for the ParserOptions object
856 * @param ParserOptions|null $x New value or null to just get the current one
857 * @return ParserOptions Current ParserOptions object
859 public function Options( $x = null ) {
860 return wfSetVar( $this->mOptions
, $x );
866 public function nextLinkID() {
867 return $this->mLinkID++
;
873 public function setLinkID( $id ) {
874 $this->mLinkID
= $id;
878 * Get a language object for use in parser functions such as {{FORMATNUM:}}
881 public function getFunctionLang() {
882 return $this->getTargetLanguage();
886 * Get the target language for the content being parsed. This is usually the
887 * language that the content is in.
891 * @throws MWException
894 public function getTargetLanguage() {
895 $target = $this->mOptions
->getTargetLanguage();
897 if ( $target !== null ) {
899 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
900 return $this->mOptions
->getUserLangObj();
901 } elseif ( is_null( $this->mTitle
) ) {
902 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
905 return $this->mTitle
->getPageLanguage();
909 * Get the language object for language conversion
910 * @deprecated since 1.32, just use getTargetLanguage()
911 * @return Language|null
913 public function getConverterLanguage() {
914 return $this->getTargetLanguage();
918 * Get a User object either from $this->mUser, if set, or from the
919 * ParserOptions object otherwise
923 public function getUser() {
924 if ( !is_null( $this->mUser
) ) {
927 return $this->mOptions
->getUser();
931 * Get a preprocessor object
933 * @return Preprocessor
935 public function getPreprocessor() {
936 if ( !isset( $this->mPreprocessor
) ) {
937 $class = $this->mPreprocessorClass
;
938 $this->mPreprocessor
= new $class( $this );
940 return $this->mPreprocessor
;
944 * Get a LinkRenderer instance to make links with
947 * @return LinkRenderer
949 public function getLinkRenderer() {
950 if ( !$this->mLinkRenderer
) {
951 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
952 ->getLinkRendererFactory()->create();
953 $this->mLinkRenderer
->setStubThreshold(
954 $this->getOptions()->getStubThreshold()
958 return $this->mLinkRenderer
;
962 * Get the MagicWordFactory that this Parser is using
965 * @return MagicWordFactory
967 public function getMagicWordFactory() {
968 return $this->magicWordFactory
;
972 * Replaces all occurrences of HTML-style comments and the given tags
973 * in the text with a random marker and returns the next text. The output
974 * parameter $matches will be an associative array filled with data in
981 * [ 'param' => 'x' ],
982 * '<element param="x">tag content</element>' ]
985 * @param array $elements List of element names. Comments are always extracted.
986 * @param string $text Source text string.
987 * @param array &$matches Out parameter, Array: extracted tags
988 * @return string Stripped text
990 public static function extractTagsAndParams( $elements, $text, &$matches ) {
995 $taglist = implode( '|', $elements );
996 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
998 while ( $text != '' ) {
999 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1001 if ( count( $p ) < 5 ) {
1004 if ( count( $p ) > 5 ) {
1013 $attributes = $p[2];
1018 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1019 $stripped .= $marker;
1021 if ( $close === '/>' ) {
1022 # Empty element tag, <tag />
1027 if ( $element === '!--' ) {
1030 $end = "/(<\\/$element\\s*>)/i";
1032 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1034 if ( count( $q ) < 3 ) {
1035 # No end tag -- let it run out to the end of the text.
1044 $matches[$marker] = [ $element,
1046 Sanitizer
::decodeTagAttributes( $attributes ),
1047 "<$element$attributes$close$content$tail" ];
1053 * Get a list of strippable XML-like elements
1057 public function getStripList() {
1058 return $this->mStripList
;
1062 * Add an item to the strip state
1063 * Returns the unique tag which must be inserted into the stripped text
1064 * The tag will be replaced with the original text in unstrip()
1066 * @param string $text
1070 public function insertStripItem( $text ) {
1071 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1072 $this->mMarkerIndex++
;
1073 $this->mStripState
->addGeneral( $marker, $text );
1078 * parse the wiki syntax used to render tables
1081 * @param string $text
1084 public function doTableStuff( $text ) {
1085 $lines = StringUtils
::explode( "\n", $text );
1087 $td_history = []; # Is currently a td tag open?
1088 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1089 $tr_history = []; # Is currently a tr tag open?
1090 $tr_attributes = []; # history of tr attributes
1091 $has_opened_tr = []; # Did this table open a <tr> element?
1092 $indent_level = 0; # indent level of the table
1094 foreach ( $lines as $outLine ) {
1095 $line = trim( $outLine );
1097 if ( $line === '' ) { # empty line, go to next line
1098 $out .= $outLine . "\n";
1102 $first_character = $line[0];
1103 $first_two = substr( $line, 0, 2 );
1106 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1107 # First check if we are starting a new table
1108 $indent_level = strlen( $matches[1] );
1110 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1111 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1113 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1114 array_push( $td_history, false );
1115 array_push( $last_tag_history, '' );
1116 array_push( $tr_history, false );
1117 array_push( $tr_attributes, '' );
1118 array_push( $has_opened_tr, false );
1119 } elseif ( count( $td_history ) == 0 ) {
1120 # Don't do any of the following
1121 $out .= $outLine . "\n";
1123 } elseif ( $first_two === '|}' ) {
1124 # We are ending a table
1125 $line = '</table>' . substr( $line, 2 );
1126 $last_tag = array_pop( $last_tag_history );
1128 if ( !array_pop( $has_opened_tr ) ) {
1129 $line = "<tr><td></td></tr>{$line}";
1132 if ( array_pop( $tr_history ) ) {
1133 $line = "</tr>{$line}";
1136 if ( array_pop( $td_history ) ) {
1137 $line = "</{$last_tag}>{$line}";
1139 array_pop( $tr_attributes );
1140 if ( $indent_level > 0 ) {
1141 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1145 } elseif ( $first_two === '|-' ) {
1146 # Now we have a table row
1147 $line = preg_replace( '#^\|-+#', '', $line );
1149 # Whats after the tag is now only attributes
1150 $attributes = $this->mStripState
->unstripBoth( $line );
1151 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1152 array_pop( $tr_attributes );
1153 array_push( $tr_attributes, $attributes );
1156 $last_tag = array_pop( $last_tag_history );
1157 array_pop( $has_opened_tr );
1158 array_push( $has_opened_tr, true );
1160 if ( array_pop( $tr_history ) ) {
1164 if ( array_pop( $td_history ) ) {
1165 $line = "</{$last_tag}>{$line}";
1169 array_push( $tr_history, false );
1170 array_push( $td_history, false );
1171 array_push( $last_tag_history, '' );
1172 } elseif ( $first_character === '|'
1173 ||
$first_character === '!'
1174 ||
$first_two === '|+'
1176 # This might be cell elements, td, th or captions
1177 if ( $first_two === '|+' ) {
1178 $first_character = '+';
1179 $line = substr( $line, 2 );
1181 $line = substr( $line, 1 );
1184 // Implies both are valid for table headings.
1185 if ( $first_character === '!' ) {
1186 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1189 # Split up multiple cells on the same line.
1190 # FIXME : This can result in improper nesting of tags processed
1191 # by earlier parser steps.
1192 $cells = explode( '||', $line );
1196 # Loop through each table cell
1197 foreach ( $cells as $cell ) {
1199 if ( $first_character !== '+' ) {
1200 $tr_after = array_pop( $tr_attributes );
1201 if ( !array_pop( $tr_history ) ) {
1202 $previous = "<tr{$tr_after}>\n";
1204 array_push( $tr_history, true );
1205 array_push( $tr_attributes, '' );
1206 array_pop( $has_opened_tr );
1207 array_push( $has_opened_tr, true );
1210 $last_tag = array_pop( $last_tag_history );
1212 if ( array_pop( $td_history ) ) {
1213 $previous = "</{$last_tag}>\n{$previous}";
1216 if ( $first_character === '|' ) {
1218 } elseif ( $first_character === '!' ) {
1220 } elseif ( $first_character === '+' ) {
1221 $last_tag = 'caption';
1226 array_push( $last_tag_history, $last_tag );
1228 # A cell could contain both parameters and data
1229 $cell_data = explode( '|', $cell, 2 );
1231 # T2553: Note that a '|' inside an invalid link should not
1232 # be mistaken as delimiting cell parameters
1233 # Bug T153140: Neither should language converter markup.
1234 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1235 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1236 } elseif ( count( $cell_data ) == 1 ) {
1237 // Whitespace in cells is trimmed
1238 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1240 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1241 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1242 // Whitespace in cells is trimmed
1243 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1247 array_push( $td_history, true );
1250 $out .= $outLine . "\n";
1253 # Closing open td, tr && table
1254 while ( count( $td_history ) > 0 ) {
1255 if ( array_pop( $td_history ) ) {
1258 if ( array_pop( $tr_history ) ) {
1261 if ( !array_pop( $has_opened_tr ) ) {
1262 $out .= "<tr><td></td></tr>\n";
1265 $out .= "</table>\n";
1268 # Remove trailing line-ending (b/c)
1269 if ( substr( $out, -1 ) === "\n" ) {
1270 $out = substr( $out, 0, -1 );
1273 # special case: don't return empty table
1274 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1282 * Helper function for parse() that transforms wiki markup into half-parsed
1283 * HTML. Only called for $mOutputType == self::OT_HTML.
1287 * @param string $text The text to parse
1288 * @param bool $isMain Whether this is being called from the main parse() function
1289 * @param PPFrame|bool $frame A pre-processor frame
1293 public function internalParse( $text, $isMain = true, $frame = false ) {
1296 // Avoid PHP 7.1 warning from passing $this by reference
1299 # Hook to suspend the parser in this state
1300 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1304 # if $frame is provided, then use $frame for replacing any variables
1306 # use frame depth to infer how include/noinclude tags should be handled
1307 # depth=0 means this is the top-level document; otherwise it's an included document
1308 if ( !$frame->depth
) {
1311 $flag = self
::PTD_FOR_INCLUSION
;
1313 $dom = $this->preprocessToDom( $text, $flag );
1314 $text = $frame->expand( $dom );
1316 # if $frame is not provided, then use old-style replaceVariables
1317 $text = $this->replaceVariables( $text );
1320 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1321 $text = Sanitizer
::removeHTMLtags(
1323 [ $this, 'attributeStripCallback' ],
1325 array_keys( $this->mTransparentTagHooks
),
1327 [ $this, 'addTrackingCategory' ]
1329 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1331 # Tables need to come after variable replacement for things to work
1332 # properly; putting them before other transformations should keep
1333 # exciting things like link expansions from showing up in surprising
1335 $text = $this->doTableStuff( $text );
1337 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1339 $text = $this->doDoubleUnderscore( $text );
1341 $text = $this->doHeadings( $text );
1342 $text = $this->replaceInternalLinks( $text );
1343 $text = $this->doAllQuotes( $text );
1344 $text = $this->replaceExternalLinks( $text );
1346 # replaceInternalLinks may sometimes leave behind
1347 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1348 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1350 $text = $this->doMagicLinks( $text );
1351 $text = $this->formatHeadings( $text, $origText, $isMain );
1357 * Helper function for parse() that transforms half-parsed HTML into fully
1360 * @param string $text
1361 * @param bool $isMain
1362 * @param bool $linestart
1365 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1366 $text = $this->mStripState
->unstripGeneral( $text );
1368 // Avoid PHP 7.1 warning from passing $this by reference
1372 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1375 # Clean up special characters, only run once, next-to-last before doBlockLevels
1376 $text = Sanitizer
::armorFrenchSpaces( $text );
1378 $text = $this->doBlockLevels( $text, $linestart );
1380 $this->replaceLinkHolders( $text );
1383 * The input doesn't get language converted if
1385 * b) Content isn't converted
1386 * c) It's a conversion table
1387 * d) it is an interface message (which is in the user language)
1389 if ( !( $this->mOptions
->getDisableContentConversion()
1390 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1392 if ( !$this->mOptions
->getInterfaceMessage() ) {
1393 # The position of the convert() call should not be changed. it
1394 # assumes that the links are all replaced and the only thing left
1395 # is the <nowiki> mark.
1396 $text = $this->getTargetLanguage()->convert( $text );
1400 $text = $this->mStripState
->unstripNoWiki( $text );
1403 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1406 $text = $this->replaceTransparentTags( $text );
1407 $text = $this->mStripState
->unstripGeneral( $text );
1409 $text = Sanitizer
::normalizeCharReferences( $text );
1411 if ( MWTidy
::isEnabled() ) {
1412 if ( $this->mOptions
->getTidy() ) {
1413 $text = MWTidy
::tidy( $text );
1416 # attempt to sanitize at least some nesting problems
1417 # (T4702 and quite a few others)
1419 # ''Something [http://www.cool.com cool''] -->
1420 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1421 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1422 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1423 # fix up an anchor inside another anchor, only
1424 # at least for a single single nested link (T5695)
1425 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1426 '\\1\\2</a>\\3</a>\\1\\4</a>',
1427 # fix div inside inline elements- doBlockLevels won't wrap a line which
1428 # contains a div, so fix it up here; replace
1429 # div with escaped text
1430 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1431 '\\1\\3<div\\5>\\6</div>\\8\\9',
1432 # remove empty italic or bold tag pairs, some
1433 # introduced by rules above
1434 '/<([bi])><\/\\1>/' => '',
1437 $text = preg_replace(
1438 array_keys( $tidyregs ),
1439 array_values( $tidyregs ),
1444 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1451 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1452 * magic external links.
1457 * @param string $text
1461 public function doMagicLinks( $text ) {
1462 $prots = wfUrlProtocolsWithoutProtRel();
1463 $urlChar = self
::EXT_LINK_URL_CLASS
;
1464 $addr = self
::EXT_LINK_ADDR
;
1465 $space = self
::SPACE_NOT_NL
; # non-newline space
1466 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1467 $spaces = "$space++"; # possessive match of 1 or more spaces
1468 $text = preg_replace_callback(
1470 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1471 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1472 (\b # m[3]: Free external links
1474 ($addr$urlChar*) # m[4]: Post-protocol path
1476 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1478 \bISBN $spaces ( # m[6]: ISBN, capture number
1479 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1480 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1481 [0-9Xx] # check digit
1483 )!xu", [ $this, 'magicLinkCallback' ], $text );
1488 * @throws MWException
1490 * @return string HTML
1492 public function magicLinkCallback( $m ) {
1493 if ( isset( $m[1] ) && $m[1] !== '' ) {
1496 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1499 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1500 # Free external link
1501 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1502 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1504 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1505 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1510 $cssClass = 'mw-magiclink-rfc';
1511 $trackingCat = 'magiclink-tracking-rfc';
1513 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1514 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1518 $urlmsg = 'pubmedurl';
1519 $cssClass = 'mw-magiclink-pmid';
1520 $trackingCat = 'magiclink-tracking-pmid';
1523 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1524 substr( $m[0], 0, 20 ) . '"' );
1526 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1527 $this->addTrackingCategory( $trackingCat );
1528 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1529 } elseif ( isset( $m[6] ) && $m[6] !== ''
1530 && $this->mOptions
->getMagicISBNLinks()
1534 $space = self
::SPACE_NOT_NL
; # non-newline space
1535 $isbn = preg_replace( "/$space/", ' ', $isbn );
1536 $num = strtr( $isbn, [
1541 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1542 return $this->getLinkRenderer()->makeKnownLink(
1543 SpecialPage
::getTitleFor( 'Booksources', $num ),
1546 'class' => 'internal mw-magiclink-isbn',
1547 'title' => false // suppress title attribute
1556 * Make a free external link, given a user-supplied URL
1558 * @param string $url
1559 * @param int $numPostProto
1560 * The number of characters after the protocol.
1561 * @return string HTML
1564 public function makeFreeExternalLink( $url, $numPostProto ) {
1567 # The characters '<' and '>' (which were escaped by
1568 # removeHTMLtags()) should not be included in
1569 # URLs, per RFC 2396.
1570 # Make terminate a URL as well (bug T84937)
1573 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1578 $trail = substr( $url, $m2[0][1] ) . $trail;
1579 $url = substr( $url, 0, $m2[0][1] );
1582 # Move trailing punctuation to $trail
1584 # If there is no left bracket, then consider right brackets fair game too
1585 if ( strpos( $url, '(' ) === false ) {
1589 $urlRev = strrev( $url );
1590 $numSepChars = strspn( $urlRev, $sep );
1591 # Don't break a trailing HTML entity by moving the ; into $trail
1592 # This is in hot code, so use substr_compare to avoid having to
1593 # create a new string object for the comparison
1594 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1595 # more optimization: instead of running preg_match with a $
1596 # anchor, which can be slow, do the match on the reversed
1597 # string starting at the desired offset.
1598 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1599 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1603 if ( $numSepChars ) {
1604 $trail = substr( $url, -$numSepChars ) . $trail;
1605 $url = substr( $url, 0, -$numSepChars );
1608 # Verify that we still have a real URL after trail removal, and
1609 # not just lone protocol
1610 if ( strlen( $trail ) >= $numPostProto ) {
1611 return $url . $trail;
1614 $url = Sanitizer
::cleanUrl( $url );
1616 # Is this an external image?
1617 $text = $this->maybeMakeExternalImage( $url );
1618 if ( $text === false ) {
1619 # Not an image, make a link
1620 $text = Linker
::makeExternalLink( $url,
1621 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1623 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1624 # Register it in the output object...
1625 $this->mOutput
->addExternalLink( $url );
1627 return $text . $trail;
1631 * Parse headers and return html
1635 * @param string $text
1639 public function doHeadings( $text ) {
1640 for ( $i = 6; $i >= 1; --$i ) {
1641 $h = str_repeat( '=', $i );
1642 // Trim non-newline whitespace from headings
1643 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1644 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1650 * Replace single quotes with HTML markup
1653 * @param string $text
1655 * @return string The altered text
1657 public function doAllQuotes( $text ) {
1659 $lines = StringUtils
::explode( "\n", $text );
1660 foreach ( $lines as $line ) {
1661 $outtext .= $this->doQuotes( $line ) . "\n";
1663 $outtext = substr( $outtext, 0, -1 );
1668 * Helper function for doAllQuotes()
1670 * @param string $text
1674 public function doQuotes( $text ) {
1675 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1676 $countarr = count( $arr );
1677 if ( $countarr == 1 ) {
1681 // First, do some preliminary work. This may shift some apostrophes from
1682 // being mark-up to being text. It also counts the number of occurrences
1683 // of bold and italics mark-ups.
1686 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1687 $thislen = strlen( $arr[$i] );
1688 // If there are ever four apostrophes, assume the first is supposed to
1689 // be text, and the remaining three constitute mark-up for bold text.
1690 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1691 if ( $thislen == 4 ) {
1692 $arr[$i - 1] .= "'";
1695 } elseif ( $thislen > 5 ) {
1696 // If there are more than 5 apostrophes in a row, assume they're all
1697 // text except for the last 5.
1698 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1699 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1703 // Count the number of occurrences of bold and italics mark-ups.
1704 if ( $thislen == 2 ) {
1706 } elseif ( $thislen == 3 ) {
1708 } elseif ( $thislen == 5 ) {
1714 // If there is an odd number of both bold and italics, it is likely
1715 // that one of the bold ones was meant to be an apostrophe followed
1716 // by italics. Which one we cannot know for certain, but it is more
1717 // likely to be one that has a single-letter word before it.
1718 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1719 $firstsingleletterword = -1;
1720 $firstmultiletterword = -1;
1722 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1723 if ( strlen( $arr[$i] ) == 3 ) {
1724 $x1 = substr( $arr[$i - 1], -1 );
1725 $x2 = substr( $arr[$i - 1], -2, 1 );
1726 if ( $x1 === ' ' ) {
1727 if ( $firstspace == -1 ) {
1730 } elseif ( $x2 === ' ' ) {
1731 $firstsingleletterword = $i;
1732 // if $firstsingleletterword is set, we don't
1733 // look at the other options, so we can bail early.
1736 if ( $firstmultiletterword == -1 ) {
1737 $firstmultiletterword = $i;
1743 // If there is a single-letter word, use it!
1744 if ( $firstsingleletterword > -1 ) {
1745 $arr[$firstsingleletterword] = "''";
1746 $arr[$firstsingleletterword - 1] .= "'";
1747 } elseif ( $firstmultiletterword > -1 ) {
1748 // If not, but there's a multi-letter word, use that one.
1749 $arr[$firstmultiletterword] = "''";
1750 $arr[$firstmultiletterword - 1] .= "'";
1751 } elseif ( $firstspace > -1 ) {
1752 // ... otherwise use the first one that has neither.
1753 // (notice that it is possible for all three to be -1 if, for example,
1754 // there is only one pentuple-apostrophe in the line)
1755 $arr[$firstspace] = "''";
1756 $arr[$firstspace - 1] .= "'";
1760 // Now let's actually convert our apostrophic mush to HTML!
1765 foreach ( $arr as $r ) {
1766 if ( ( $i %
2 ) == 0 ) {
1767 if ( $state === 'both' ) {
1773 $thislen = strlen( $r );
1774 if ( $thislen == 2 ) {
1775 if ( $state === 'i' ) {
1778 } elseif ( $state === 'bi' ) {
1781 } elseif ( $state === 'ib' ) {
1782 $output .= '</b></i><b>';
1784 } elseif ( $state === 'both' ) {
1785 $output .= '<b><i>' . $buffer . '</i>';
1787 } else { // $state can be 'b' or ''
1791 } elseif ( $thislen == 3 ) {
1792 if ( $state === 'b' ) {
1795 } elseif ( $state === 'bi' ) {
1796 $output .= '</i></b><i>';
1798 } elseif ( $state === 'ib' ) {
1801 } elseif ( $state === 'both' ) {
1802 $output .= '<i><b>' . $buffer . '</b>';
1804 } else { // $state can be 'i' or ''
1808 } elseif ( $thislen == 5 ) {
1809 if ( $state === 'b' ) {
1810 $output .= '</b><i>';
1812 } elseif ( $state === 'i' ) {
1813 $output .= '</i><b>';
1815 } elseif ( $state === 'bi' ) {
1816 $output .= '</i></b>';
1818 } elseif ( $state === 'ib' ) {
1819 $output .= '</b></i>';
1821 } elseif ( $state === 'both' ) {
1822 $output .= '<i><b>' . $buffer . '</b></i>';
1824 } else { // ($state == '')
1832 // Now close all remaining tags. Notice that the order is important.
1833 if ( $state === 'b' ||
$state === 'ib' ) {
1836 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1839 if ( $state === 'bi' ) {
1842 // There might be lonely ''''', so make sure we have a buffer
1843 if ( $state === 'both' && $buffer ) {
1844 $output .= '<b><i>' . $buffer . '</i></b>';
1850 * Replace external links (REL)
1852 * Note: this is all very hackish and the order of execution matters a lot.
1853 * Make sure to run tests/parser/parserTests.php if you change this code.
1857 * @param string $text
1859 * @throws MWException
1862 public function replaceExternalLinks( $text ) {
1863 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1864 if ( $bits === false ) {
1865 throw new MWException( "PCRE needs to be compiled with "
1866 . "--enable-unicode-properties in order for MediaWiki to function" );
1868 $s = array_shift( $bits );
1871 while ( $i < count( $bits ) ) {
1874 $text = $bits[$i++
];
1875 $trail = $bits[$i++
];
1877 # The characters '<' and '>' (which were escaped by
1878 # removeHTMLtags()) should not be included in
1879 # URLs, per RFC 2396.
1881 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1882 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1883 $url = substr( $url, 0, $m2[0][1] );
1886 # If the link text is an image URL, replace it with an <img> tag
1887 # This happened by accident in the original parser, but some people used it extensively
1888 $img = $this->maybeMakeExternalImage( $text );
1889 if ( $img !== false ) {
1895 # Set linktype for CSS
1898 # No link text, e.g. [http://domain.tld/some.link]
1899 if ( $text == '' ) {
1901 $langObj = $this->getTargetLanguage();
1902 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1903 $linktype = 'autonumber';
1905 # Have link text, e.g. [http://domain.tld/some.link text]s
1907 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1910 // Excluding protocol-relative URLs may avoid many false positives.
1911 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1912 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1915 $url = Sanitizer
::cleanUrl( $url );
1917 # Use the encoded URL
1918 # This means that users can paste URLs directly into the text
1919 # Funny characters like ö aren't valid in URLs anyway
1920 # This was changed in August 2004
1921 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1922 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1924 # Register link in the output object.
1925 $this->mOutput
->addExternalLink( $url );
1932 * Get the rel attribute for a particular external link.
1935 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1936 * nofollow if appropriate
1937 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1938 * @return string|null Rel attribute for $url
1940 public static function getExternalLinkRel( $url = false, $title = null ) {
1941 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1942 $ns = $title ?
$title->getNamespace() : false;
1943 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1944 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1952 * Get an associative array of additional HTML attributes appropriate for a
1953 * particular external link. This currently may include rel => nofollow
1954 * (depending on configuration, namespace, and the URL's domain) and/or a
1955 * target attribute (depending on configuration).
1957 * @param string $url URL to extract the domain from for rel =>
1958 * nofollow if appropriate
1959 * @return array Associative array of HTML attributes
1961 public function getExternalLinkAttribs( $url ) {
1963 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1965 $target = $this->mOptions
->getExternalLinkTarget();
1967 $attribs['target'] = $target;
1968 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1969 // T133507. New windows can navigate parent cross-origin.
1970 // Including noreferrer due to lacking browser
1971 // support of noopener. Eventually noreferrer should be removed.
1972 if ( $rel !== '' ) {
1975 $rel .= 'noreferrer noopener';
1978 $attribs['rel'] = $rel;
1983 * Replace unusual escape codes in a URL with their equivalent characters
1985 * This generally follows the syntax defined in RFC 3986, with special
1986 * consideration for HTTP query strings.
1988 * @param string $url
1991 public static function normalizeLinkUrl( $url ) {
1992 # First, make sure unsafe characters are encoded
1993 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1995 return rawurlencode( $m[0] );
2001 $end = strlen( $url );
2003 # Fragment part - 'fragment'
2004 $start = strpos( $url, '#' );
2005 if ( $start !== false && $start < $end ) {
2006 $ret = self
::normalizeUrlComponent(
2007 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2011 # Query part - 'query' minus &=+;
2012 $start = strpos( $url, '?' );
2013 if ( $start !== false && $start < $end ) {
2014 $ret = self
::normalizeUrlComponent(
2015 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2019 # Scheme and path part - 'pchar'
2020 # (we assume no userinfo or encoded colons in the host)
2021 $ret = self
::normalizeUrlComponent(
2022 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2027 private static function normalizeUrlComponent( $component, $unsafe ) {
2028 $callback = function ( $matches ) use ( $unsafe ) {
2029 $char = urldecode( $matches[0] );
2030 $ord = ord( $char );
2031 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2035 # Leave it escaped, but use uppercase for a-f
2036 return strtoupper( $matches[0] );
2039 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2043 * make an image if it's allowed, either through the global
2044 * option, through the exception, or through the on-wiki whitelist
2046 * @param string $url
2050 private function maybeMakeExternalImage( $url ) {
2051 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2052 $imagesexception = !empty( $imagesfrom );
2054 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2055 if ( $imagesexception && is_array( $imagesfrom ) ) {
2056 $imagematch = false;
2057 foreach ( $imagesfrom as $match ) {
2058 if ( strpos( $url, $match ) === 0 ) {
2063 } elseif ( $imagesexception ) {
2064 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2066 $imagematch = false;
2069 if ( $this->mOptions
->getAllowExternalImages()
2070 ||
( $imagesexception && $imagematch )
2072 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2074 $text = Linker
::makeExternalImage( $url );
2077 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2078 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2080 $whitelist = explode(
2082 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2085 foreach ( $whitelist as $entry ) {
2086 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2087 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2090 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2091 # Image matches a whitelist entry
2092 $text = Linker
::makeExternalImage( $url );
2101 * Process [[ ]] wikilinks
2105 * @return string Processed text
2109 public function replaceInternalLinks( $s ) {
2110 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2115 * Process [[ ]] wikilinks (RIL)
2117 * @throws MWException
2118 * @return LinkHolderArray
2122 public function replaceInternalLinks2( &$s ) {
2123 global $wgExtraInterlanguageLinkPrefixes;
2125 static $tc = false, $e1, $e1_img;
2126 # the % is needed to support urlencoded titles as well
2128 $tc = Title
::legalChars() . '#%';
2129 # Match a link having the form [[namespace:link|alternate]]trail
2130 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2131 # Match cases where there is no "]]", which might still be images
2132 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2135 $holders = new LinkHolderArray( $this );
2137 # split the entire text string on occurrences of [[
2138 $a = StringUtils
::explode( '[[', ' ' . $s );
2139 # get the first element (all text up to first [[), and remove the space we added
2142 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2143 $s = substr( $s, 1 );
2145 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2147 if ( $useLinkPrefixExtension ) {
2148 # Match the end of a line for a word that's not followed by whitespace,
2149 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2151 $charset = $wgContLang->linkPrefixCharset();
2152 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2155 if ( is_null( $this->mTitle
) ) {
2156 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2158 $nottalk = !$this->mTitle
->isTalkPage();
2160 if ( $useLinkPrefixExtension ) {
2162 if ( preg_match( $e2, $s, $m ) ) {
2163 $first_prefix = $m[2];
2165 $first_prefix = false;
2171 $useSubpages = $this->areSubpagesAllowed();
2173 # Loop for each link
2174 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2175 # Check for excessive memory usage
2176 if ( $holders->isBig() ) {
2178 # Do the existence check, replace the link holders and clear the array
2179 $holders->replace( $s );
2183 if ( $useLinkPrefixExtension ) {
2184 if ( preg_match( $e2, $s, $m ) ) {
2191 if ( $first_prefix ) {
2192 $prefix = $first_prefix;
2193 $first_prefix = false;
2197 $might_be_img = false;
2199 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2201 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2202 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2203 # the real problem is with the $e1 regex
2205 # Still some problems for cases where the ] is meant to be outside punctuation,
2206 # and no image is in sight. See T4095.
2208 && substr( $m[3], 0, 1 ) === ']'
2209 && strpos( $text, '[' ) !== false
2211 $text .= ']'; # so that replaceExternalLinks($text) works later
2212 $m[3] = substr( $m[3], 1 );
2214 # fix up urlencoded title texts
2215 if ( strpos( $m[1], '%' ) !== false ) {
2216 # Should anchors '#' also be rejected?
2217 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2220 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2221 # Invalid, but might be an image with a link in its caption
2222 $might_be_img = true;
2224 if ( strpos( $m[1], '%' ) !== false ) {
2225 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2228 } else { # Invalid form; output directly
2229 $s .= $prefix . '[[' . $line;
2233 $origLink = ltrim( $m[1], ' ' );
2235 # Don't allow internal links to pages containing
2236 # PROTO: where PROTO is a valid URL protocol; these
2237 # should be external links.
2238 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2239 $s .= $prefix . '[[' . $line;
2243 # Make subpage if necessary
2244 if ( $useSubpages ) {
2245 $link = $this->maybeDoSubpageLink( $origLink, $text );
2250 // \x7f isn't a default legal title char, so most likely strip
2251 // markers will force us into the "invalid form" path above. But,
2252 // just in case, let's assert that xmlish tags aren't valid in
2253 // the title position.
2254 $unstrip = $this->mStripState
->killMarkers( $link );
2255 $noMarkers = ( $unstrip === $link );
2257 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2258 if ( $nt === null ) {
2259 $s .= $prefix . '[[' . $line;
2263 $ns = $nt->getNamespace();
2264 $iw = $nt->getInterwiki();
2266 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2268 if ( $might_be_img ) { # if this is actually an invalid link
2269 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2272 # look at the next 'line' to see if we can close it there
2274 $next_line = $a->current();
2275 if ( $next_line === false ||
$next_line === null ) {
2278 $m = explode( ']]', $next_line, 3 );
2279 if ( count( $m ) == 3 ) {
2280 # the first ]] closes the inner link, the second the image
2282 $text .= "[[{$m[0]}]]{$m[1]}";
2285 } elseif ( count( $m ) == 2 ) {
2286 # if there's exactly one ]] that's fine, we'll keep looking
2287 $text .= "[[{$m[0]}]]{$m[1]}";
2289 # if $next_line is invalid too, we need look no further
2290 $text .= '[[' . $next_line;
2295 # we couldn't find the end of this imageLink, so output it raw
2296 # but don't ignore what might be perfectly normal links in the text we've examined
2297 $holders->merge( $this->replaceInternalLinks2( $text ) );
2298 $s .= "{$prefix}[[$link|$text";
2299 # note: no $trail, because without an end, there *is* no trail
2302 } else { # it's not an image, so output it raw
2303 $s .= "{$prefix}[[$link|$text";
2304 # note: no $trail, because without an end, there *is* no trail
2309 $wasblank = ( $text == '' );
2313 # Strip off leading ':'
2314 $text = substr( $text, 1 );
2317 # T6598 madness. Handle the quotes only if they come from the alternate part
2318 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2319 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2320 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2321 $text = $this->doQuotes( $text );
2324 # Link not escaped by : , create the various objects
2325 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2328 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2329 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2330 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2333 # T26502: filter duplicates
2334 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2335 $this->mLangLinkLanguages
[$iw] = true;
2336 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2340 * Strip the whitespace interwiki links produce, see T10897
2342 $s = rtrim( $s . $prefix ) . $trail; # T175416
2346 if ( $ns == NS_FILE
) {
2347 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2349 # if no parameters were passed, $text
2350 # becomes something like "File:Foo.png",
2351 # which we don't want to pass on to the
2355 # recursively parse links inside the image caption
2356 # actually, this will parse them in any other parameters, too,
2357 # but it might be hard to fix that, and it doesn't matter ATM
2358 $text = $this->replaceExternalLinks( $text );
2359 $holders->merge( $this->replaceInternalLinks2( $text ) );
2361 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2362 $s .= $prefix . $this->armorLinks(
2363 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2366 } elseif ( $ns == NS_CATEGORY
) {
2368 * Strip the whitespace Category links produce, see T2087
2370 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2373 $sortkey = $this->getDefaultSort();
2377 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2378 $sortkey = str_replace( "\n", '', $sortkey );
2379 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2380 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2386 # Self-link checking. For some languages, variants of the title are checked in
2387 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2388 # for linking to a different variant.
2389 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2390 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2394 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2395 # @todo FIXME: Should do batch file existence checks, see comment below
2396 if ( $ns == NS_MEDIA
) {
2397 # Give extensions a chance to select the file revision for us
2400 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2401 [ $this, $nt, &$options, &$descQuery ] );
2402 # Fetch and register the file (file title may be different via hooks)
2403 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2404 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2405 $s .= $prefix . $this->armorLinks(
2406 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2410 # Some titles, such as valid special pages or files in foreign repos, should
2411 # be shown as bluelinks even though they're not included in the page table
2412 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2413 # batch file existence checks for NS_FILE and NS_MEDIA
2414 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2415 $this->mOutput
->addLink( $nt );
2416 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2418 # Links will be added to the output link list after checking
2419 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2426 * Render a forced-blue link inline; protect against double expansion of
2427 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2428 * Since this little disaster has to split off the trail text to avoid
2429 * breaking URLs in the following text without breaking trails on the
2430 * wiki links, it's been made into a horrible function.
2433 * @param string $text
2434 * @param string $trail
2435 * @param string $prefix
2436 * @return string HTML-wikitext mix oh yuck
2438 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2439 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2441 if ( $text == '' ) {
2442 $text = htmlspecialchars( $nt->getPrefixedText() );
2445 $link = $this->getLinkRenderer()->makeKnownLink(
2446 $nt, new HtmlArmor( "$prefix$text$inside" )
2449 return $this->armorLinks( $link ) . $trail;
2453 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2454 * going to go through further parsing steps before inline URL expansion.
2456 * Not needed quite as much as it used to be since free links are a bit
2457 * more sensible these days. But bracketed links are still an issue.
2459 * @param string $text More-or-less HTML
2460 * @return string Less-or-more HTML with NOPARSE bits
2462 public function armorLinks( $text ) {
2463 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2464 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2468 * Return true if subpage links should be expanded on this page.
2471 public function areSubpagesAllowed() {
2472 # Some namespaces don't allow subpages
2473 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2477 * Handle link to subpage if necessary
2479 * @param string $target The source of the link
2480 * @param string &$text The link text, modified as necessary
2481 * @return string The full name of the link
2484 public function maybeDoSubpageLink( $target, &$text ) {
2485 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2489 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2491 * @param string $text
2492 * @param bool $linestart Whether or not this is at the start of a line.
2494 * @return string The lists rendered as HTML
2496 public function doBlockLevels( $text, $linestart ) {
2497 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2501 * Return value of a magic variable (like PAGENAME)
2505 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2506 * @param bool|PPFrame $frame
2508 * @throws MWException
2511 public function getVariableValue( $index, $frame = false ) {
2512 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2513 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2515 if ( is_null( $this->mTitle
) ) {
2516 // If no title set, bad things are going to happen
2517 // later. Title should always be set since this
2518 // should only be called in the middle of a parse
2519 // operation (but the unit-tests do funky stuff)
2520 throw new MWException( __METHOD__
. ' Should only be '
2521 . ' called while parsing (no title set)' );
2524 // Avoid PHP 7.1 warning from passing $this by reference
2528 * Some of these require message or data lookups and can be
2529 * expensive to check many times.
2531 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2532 if ( isset( $this->mVarCache
[$index] ) ) {
2533 return $this->mVarCache
[$index];
2537 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2538 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2540 $pageLang = $this->getFunctionLang();
2546 case 'currentmonth':
2547 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2549 case 'currentmonth1':
2550 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2552 case 'currentmonthname':
2553 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2555 case 'currentmonthnamegen':
2556 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2558 case 'currentmonthabbrev':
2559 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2562 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2565 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2568 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2571 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2573 case 'localmonthname':
2574 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2576 case 'localmonthnamegen':
2577 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2579 case 'localmonthabbrev':
2580 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2583 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2586 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2589 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2592 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2594 case 'fullpagename':
2595 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2597 case 'fullpagenamee':
2598 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2601 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2603 case 'subpagenamee':
2604 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2606 case 'rootpagename':
2607 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2609 case 'rootpagenamee':
2610 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2613 $this->mTitle
->getRootText()
2616 case 'basepagename':
2617 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2619 case 'basepagenamee':
2620 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2623 $this->mTitle
->getBaseText()
2626 case 'talkpagename':
2627 if ( $this->mTitle
->canHaveTalkPage() ) {
2628 $talkPage = $this->mTitle
->getTalkPage();
2629 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2634 case 'talkpagenamee':
2635 if ( $this->mTitle
->canHaveTalkPage() ) {
2636 $talkPage = $this->mTitle
->getTalkPage();
2637 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2642 case 'subjectpagename':
2643 $subjPage = $this->mTitle
->getSubjectPage();
2644 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2646 case 'subjectpagenamee':
2647 $subjPage = $this->mTitle
->getSubjectPage();
2648 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2650 case 'pageid': // requested in T25427
2651 $pageid = $this->getTitle()->getArticleID();
2652 if ( $pageid == 0 ) {
2653 # 0 means the page doesn't exist in the database,
2654 # which means the user is previewing a new page.
2655 # The vary-revision flag must be set, because the magic word
2656 # will have a different value once the page is saved.
2657 $this->mOutput
->setFlag( 'vary-revision' );
2658 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2660 $value = $pageid ?
: null;
2663 # Let the edit saving system know we should parse the page
2664 # *after* a revision ID has been assigned.
2665 $this->mOutput
->setFlag( 'vary-revision-id' );
2666 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2667 $value = $this->mRevisionId
;
2668 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2669 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2670 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2674 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2676 case 'revisionday2':
2677 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2679 case 'revisionmonth':
2680 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2682 case 'revisionmonth1':
2683 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2685 case 'revisionyear':
2686 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2688 case 'revisiontimestamp':
2689 # Let the edit saving system know we should parse the page
2690 # *after* a revision ID has been assigned. This is for null edits.
2691 $this->mOutput
->setFlag( 'vary-revision' );
2692 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2693 $value = $this->getRevisionTimestamp();
2695 case 'revisionuser':
2696 # Let the edit saving system know we should parse the page
2697 # *after* a revision ID has been assigned for null edits.
2698 $this->mOutput
->setFlag( 'vary-user' );
2699 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2700 $value = $this->getRevisionUser();
2702 case 'revisionsize':
2703 $value = $this->getRevisionSize();
2706 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2709 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2711 case 'namespacenumber':
2712 $value = $this->mTitle
->getNamespace();
2715 $value = $this->mTitle
->canHaveTalkPage()
2716 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2720 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2722 case 'subjectspace':
2723 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2725 case 'subjectspacee':
2726 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2728 case 'currentdayname':
2729 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2732 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2735 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2738 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2741 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2742 # int to remove the padding
2743 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2746 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2748 case 'localdayname':
2749 $value = $pageLang->getWeekdayName(
2750 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2754 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2757 $value = $pageLang->time(
2758 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2764 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2767 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2768 # int to remove the padding
2769 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2772 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2774 case 'numberofarticles':
2775 $value = $pageLang->formatNum( SiteStats
::articles() );
2777 case 'numberoffiles':
2778 $value = $pageLang->formatNum( SiteStats
::images() );
2780 case 'numberofusers':
2781 $value = $pageLang->formatNum( SiteStats
::users() );
2783 case 'numberofactiveusers':
2784 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2786 case 'numberofpages':
2787 $value = $pageLang->formatNum( SiteStats
::pages() );
2789 case 'numberofadmins':
2790 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2792 case 'numberofedits':
2793 $value = $pageLang->formatNum( SiteStats
::edits() );
2795 case 'currenttimestamp':
2796 $value = wfTimestamp( TS_MW
, $ts );
2798 case 'localtimestamp':
2799 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2801 case 'currentversion':
2802 $value = SpecialVersion
::getVersion();
2805 return $wgArticlePath;
2811 return $wgServerName;
2813 return $wgScriptPath;
2815 return $wgStylePath;
2816 case 'directionmark':
2817 return $pageLang->getDirMark();
2818 case 'contentlanguage':
2819 global $wgLanguageCode;
2820 return $wgLanguageCode;
2821 case 'pagelanguage':
2822 $value = $pageLang->getCode();
2824 case 'cascadingsources':
2825 $value = CoreParserFunctions
::cascadingsources( $this );
2830 'ParserGetVariableValueSwitch',
2831 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2838 $this->mVarCache
[$index] = $value;
2847 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2848 * @param string $variable Parser variable name
2851 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2854 # Get the timezone-adjusted timestamp to be used for this revision
2855 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2856 # Possibly set vary-revision if there is not yet an associated revision
2857 if ( !$this->getRevisionObject() ) {
2858 # Get the timezone-adjusted timestamp $mtts seconds in the future
2860 $wgContLang->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2865 if ( $resNow !== $resThen ) {
2866 # Let the edit saving system know we should parse the page
2867 # *after* a revision ID has been assigned. This is for null edits.
2868 $this->mOutput
->setFlag( 'vary-revision' );
2869 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2877 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2881 public function initialiseVariables() {
2882 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2883 $substIDs = $this->magicWordFactory
->getSubstIDs();
2885 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2886 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2890 * Preprocess some wikitext and return the document tree.
2891 * This is the ghost of replace_variables().
2893 * @param string $text The text to parse
2894 * @param int $flags Bitwise combination of:
2895 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2896 * included. Default is to assume a direct page view.
2898 * The generated DOM tree must depend only on the input text and the flags.
2899 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2901 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2902 * change in the DOM tree for a given text, must be passed through the section identifier
2903 * in the section edit link and thus back to extractSections().
2905 * The output of this function is currently only cached in process memory, but a persistent
2906 * cache may be implemented at a later date which takes further advantage of these strict
2907 * dependency requirements.
2911 public function preprocessToDom( $text, $flags = 0 ) {
2912 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2917 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2923 public static function splitWhitespace( $s ) {
2924 $ltrimmed = ltrim( $s );
2925 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2926 $trimmed = rtrim( $ltrimmed );
2927 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2929 $w2 = substr( $ltrimmed, -$diff );
2933 return [ $w1, $trimmed, $w2 ];
2937 * Replace magic variables, templates, and template arguments
2938 * with the appropriate text. Templates are substituted recursively,
2939 * taking care to avoid infinite loops.
2941 * Note that the substitution depends on value of $mOutputType:
2942 * self::OT_WIKI: only {{subst:}} templates
2943 * self::OT_PREPROCESS: templates but not extension tags
2944 * self::OT_HTML: all templates and extension tags
2946 * @param string $text The text to transform
2947 * @param bool|PPFrame $frame Object describing the arguments passed to the
2948 * template. Arguments may also be provided as an associative array, as
2949 * was the usual case before MW1.12. Providing arguments this way may be
2950 * useful for extensions wishing to perform variable replacement
2952 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2953 * double-brace expansion.
2956 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2957 # Is there any text? Also, Prevent too big inclusions!
2958 $textSize = strlen( $text );
2959 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2963 if ( $frame === false ) {
2964 $frame = $this->getPreprocessor()->newFrame();
2965 } elseif ( !( $frame instanceof PPFrame
) ) {
2966 wfDebug( __METHOD__
. " called using plain parameters instead of "
2967 . "a PPFrame instance. Creating custom frame.\n" );
2968 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2971 $dom = $this->preprocessToDom( $text );
2972 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2973 $text = $frame->expand( $dom, $flags );
2979 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2981 * @param array $args
2985 public static function createAssocArgs( $args ) {
2988 foreach ( $args as $arg ) {
2989 $eqpos = strpos( $arg, '=' );
2990 if ( $eqpos === false ) {
2991 $assocArgs[$index++
] = $arg;
2993 $name = trim( substr( $arg, 0, $eqpos ) );
2994 $value = trim( substr( $arg, $eqpos +
1 ) );
2995 if ( $value === false ) {
2998 if ( $name !== false ) {
2999 $assocArgs[$name] = $value;
3008 * Warn the user when a parser limitation is reached
3009 * Will warn at most once the user per limitation type
3011 * The results are shown during preview and run through the Parser (See EditPage.php)
3013 * @param string $limitationType Should be one of:
3014 * 'expensive-parserfunction' (corresponding messages:
3015 * 'expensive-parserfunction-warning',
3016 * 'expensive-parserfunction-category')
3017 * 'post-expand-template-argument' (corresponding messages:
3018 * 'post-expand-template-argument-warning',
3019 * 'post-expand-template-argument-category')
3020 * 'post-expand-template-inclusion' (corresponding messages:
3021 * 'post-expand-template-inclusion-warning',
3022 * 'post-expand-template-inclusion-category')
3023 * 'node-count-exceeded' (corresponding messages:
3024 * 'node-count-exceeded-warning',
3025 * 'node-count-exceeded-category')
3026 * 'expansion-depth-exceeded' (corresponding messages:
3027 * 'expansion-depth-exceeded-warning',
3028 * 'expansion-depth-exceeded-category')
3029 * @param string|int|null $current Current value
3030 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3031 * exceeded, provide the values (optional)
3033 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3034 # does no harm if $current and $max are present but are unnecessary for the message
3035 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3036 # only during preview, and that would split the parser cache unnecessarily.
3037 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3039 $this->mOutput
->addWarning( $warning );
3040 $this->addTrackingCategory( "$limitationType-category" );
3044 * Return the text of a template, after recursively
3045 * replacing any variables or templates within the template.
3047 * @param array $piece The parts of the template
3048 * $piece['title']: the title, i.e. the part before the |
3049 * $piece['parts']: the parameter array
3050 * $piece['lineStart']: whether the brace was at the start of a line
3051 * @param PPFrame $frame The current frame, contains template arguments
3053 * @return string The text of the template
3055 public function braceSubstitution( $piece, $frame ) {
3058 // $text has been filled
3060 // wiki markup in $text should be escaped
3062 // $text is HTML, armour it against wikitext transformation
3064 // Force interwiki transclusion to be done in raw mode not rendered
3065 $forceRawInterwiki = false;
3066 // $text is a DOM node needing expansion in a child frame
3067 $isChildObj = false;
3068 // $text is a DOM node needing expansion in the current frame
3069 $isLocalObj = false;
3071 # Title object, where $text came from
3074 # $part1 is the bit before the first |, and must contain only title characters.
3075 # Various prefixes will be stripped from it later.
3076 $titleWithSpaces = $frame->expand( $piece['title'] );
3077 $part1 = trim( $titleWithSpaces );
3080 # Original title text preserved for various purposes
3081 $originalTitle = $part1;
3083 # $args is a list of argument nodes, starting from index 0, not including $part1
3084 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3085 # below won't work b/c this $args isn't an object
3086 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3088 $profileSection = null; // profile templates
3092 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3094 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3095 # Decide whether to expand template or keep wikitext as-is.
3096 if ( $this->ot
['wiki'] ) {
3097 if ( $substMatch === false ) {
3098 $literal = true; # literal when in PST with no prefix
3100 $literal = false; # expand when in PST with subst: or safesubst:
3103 if ( $substMatch == 'subst' ) {
3104 $literal = true; # literal when not in PST with plain subst:
3106 $literal = false; # expand when not in PST with safesubst: or no prefix
3110 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3117 if ( !$found && $args->getLength() == 0 ) {
3118 $id = $this->mVariables
->matchStartToEnd( $part1 );
3119 if ( $id !== false ) {
3120 $text = $this->getVariableValue( $id, $frame );
3121 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3122 $this->mOutput
->updateCacheExpiry(
3123 $this->magicWordFactory
->getCacheTTL( $id ) );
3129 # MSG, MSGNW and RAW
3132 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3133 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3136 # Remove obsolete MSG:
3137 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3138 $mwMsg->matchStartAndRemove( $part1 );
3142 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3143 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3144 $forceRawInterwiki = true;
3150 $colonPos = strpos( $part1, ':' );
3151 if ( $colonPos !== false ) {
3152 $func = substr( $part1, 0, $colonPos );
3153 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3154 $argsLength = $args->getLength();
3155 for ( $i = 0; $i < $argsLength; $i++
) {
3156 $funcArgs[] = $args->item( $i );
3159 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3161 // Extract any forwarded flags
3162 if ( isset( $result['title'] ) ) {
3163 $title = $result['title'];
3165 if ( isset( $result['found'] ) ) {
3166 $found = $result['found'];
3168 if ( array_key_exists( 'text', $result ) ) {
3170 $text = $result['text'];
3172 if ( isset( $result['nowiki'] ) ) {
3173 $nowiki = $result['nowiki'];
3175 if ( isset( $result['isHTML'] ) ) {
3176 $isHTML = $result['isHTML'];
3178 if ( isset( $result['forceRawInterwiki'] ) ) {
3179 $forceRawInterwiki = $result['forceRawInterwiki'];
3181 if ( isset( $result['isChildObj'] ) ) {
3182 $isChildObj = $result['isChildObj'];
3184 if ( isset( $result['isLocalObj'] ) ) {
3185 $isLocalObj = $result['isLocalObj'];
3190 # Finish mangling title and then check for loops.
3191 # Set $title to a Title object and $titleText to the PDBK
3194 # Split the title into page and subpage
3196 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3197 if ( $part1 !== $relative ) {
3199 $ns = $this->mTitle
->getNamespace();
3201 $title = Title
::newFromText( $part1, $ns );
3203 $titleText = $title->getPrefixedText();
3204 # Check for language variants if the template is not found
3205 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3206 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3208 # Do recursion depth check
3209 $limit = $this->mOptions
->getMaxTemplateDepth();
3210 if ( $frame->depth
>= $limit ) {
3212 $text = '<span class="error">'
3213 . wfMessage( 'parser-template-recursion-depth-warning' )
3214 ->numParams( $limit )->inContentLanguage()->text()
3220 # Load from database
3221 if ( !$found && $title ) {
3222 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3223 if ( !$title->isExternal() ) {
3224 if ( $title->isSpecialPage()
3225 && $this->mOptions
->getAllowSpecialInclusion()
3226 && $this->ot
['html']
3228 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3229 // Pass the template arguments as URL parameters.
3230 // "uselang" will have no effect since the Language object
3231 // is forced to the one defined in ParserOptions.
3233 $argsLength = $args->getLength();
3234 for ( $i = 0; $i < $argsLength; $i++
) {
3235 $bits = $args->item( $i )->splitArg();
3236 if ( strval( $bits['index'] ) === '' ) {
3237 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3238 $value = trim( $frame->expand( $bits['value'] ) );
3239 $pageArgs[$name] = $value;
3243 // Create a new context to execute the special page
3244 $context = new RequestContext
;
3245 $context->setTitle( $title );
3246 $context->setRequest( new FauxRequest( $pageArgs ) );
3247 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3248 $context->setUser( $this->getUser() );
3250 // If this page is cached, then we better not be per user.
3251 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3253 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3254 $ret = SpecialPageFactory
::capturePath(
3255 $title, $context, $this->getLinkRenderer() );
3257 $text = $context->getOutput()->getHTML();
3258 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3261 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3262 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3263 $specialPage->maxIncludeCacheTime()
3267 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3268 $found = false; # access denied
3269 wfDebug( __METHOD__
. ": template inclusion denied for " .
3270 $title->getPrefixedDBkey() . "\n" );
3272 list( $text, $title ) = $this->getTemplateDom( $title );
3273 if ( $text !== false ) {
3279 # If the title is valid but undisplayable, make a link to it
3280 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3281 $text = "[[:$titleText]]";
3284 } elseif ( $title->isTrans() ) {
3285 # Interwiki transclusion
3286 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3287 $text = $this->interwikiTransclude( $title, 'render' );
3290 $text = $this->interwikiTransclude( $title, 'raw' );
3291 # Preprocess it like a template
3292 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3298 # Do infinite loop check
3299 # This has to be done after redirect resolution to avoid infinite loops via redirects
3300 if ( !$frame->loopCheck( $title ) ) {
3302 $text = '<span class="error">'
3303 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3305 $this->addTrackingCategory( 'template-loop-category' );
3306 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3307 wfEscapeWikiText( $titleText ) )->text() );
3308 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3312 # If we haven't found text to substitute by now, we're done
3313 # Recover the source wikitext and return it
3315 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3316 if ( $profileSection ) {
3317 $this->mProfiler
->scopedProfileOut( $profileSection );
3319 return [ 'object' => $text ];
3322 # Expand DOM-style return values in a child frame
3323 if ( $isChildObj ) {
3324 # Clean up argument array
3325 $newFrame = $frame->newChild( $args, $title );
3328 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3329 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3330 # Expansion is eligible for the empty-frame cache
3331 $text = $newFrame->cachedExpand( $titleText, $text );
3333 # Uncached expansion
3334 $text = $newFrame->expand( $text );
3337 if ( $isLocalObj && $nowiki ) {
3338 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3339 $isLocalObj = false;
3342 if ( $profileSection ) {
3343 $this->mProfiler
->scopedProfileOut( $profileSection );
3346 # Replace raw HTML by a placeholder
3348 $text = $this->insertStripItem( $text );
3349 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3350 # Escape nowiki-style return values
3351 $text = wfEscapeWikiText( $text );
3352 } elseif ( is_string( $text )
3353 && !$piece['lineStart']
3354 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3356 # T2529: if the template begins with a table or block-level
3357 # element, it should be treated as beginning a new line.
3358 # This behavior is somewhat controversial.
3359 $text = "\n" . $text;
3362 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3363 # Error, oversize inclusion
3364 if ( $titleText !== false ) {
3365 # Make a working, properly escaped link if possible (T25588)
3366 $text = "[[:$titleText]]";
3368 # This will probably not be a working link, but at least it may
3369 # provide some hint of where the problem is
3370 preg_replace( '/^:/', '', $originalTitle );
3371 $text = "[[:$originalTitle]]";
3373 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3374 . 'post-expand include size too large -->' );
3375 $this->limitationWarn( 'post-expand-template-inclusion' );
3378 if ( $isLocalObj ) {
3379 $ret = [ 'object' => $text ];
3381 $ret = [ 'text' => $text ];
3388 * Call a parser function and return an array with text and flags.
3390 * The returned array will always contain a boolean 'found', indicating
3391 * whether the parser function was found or not. It may also contain the
3393 * text: string|object, resulting wikitext or PP DOM object
3394 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3395 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3396 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3397 * nowiki: bool, wiki markup in $text should be escaped
3400 * @param PPFrame $frame The current frame, contains template arguments
3401 * @param string $function Function name
3402 * @param array $args Arguments to the function
3403 * @throws MWException
3406 public function callParserFunction( $frame, $function, array $args = [] ) {
3409 # Case sensitive functions
3410 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3411 $function = $this->mFunctionSynonyms
[1][$function];
3413 # Case insensitive functions
3414 $function = $wgContLang->lc( $function );
3415 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3416 $function = $this->mFunctionSynonyms
[0][$function];
3418 return [ 'found' => false ];
3422 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3424 // Avoid PHP 7.1 warning from passing $this by reference
3427 $allArgs = [ &$parser ];
3428 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3429 # Convert arguments to PPNodes and collect for appending to $allArgs
3431 foreach ( $args as $k => $v ) {
3432 if ( $v instanceof PPNode ||
$k === 0 ) {
3435 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3439 # Add a frame parameter, and pass the arguments as an array
3440 $allArgs[] = $frame;
3441 $allArgs[] = $funcArgs;
3443 # Convert arguments to plain text and append to $allArgs
3444 foreach ( $args as $k => $v ) {
3445 if ( $v instanceof PPNode
) {
3446 $allArgs[] = trim( $frame->expand( $v ) );
3447 } elseif ( is_int( $k ) && $k >= 0 ) {
3448 $allArgs[] = trim( $v );
3450 $allArgs[] = trim( "$k=$v" );
3455 $result = $callback( ...$allArgs );
3457 # The interface for function hooks allows them to return a wikitext
3458 # string or an array containing the string and any flags. This mungs
3459 # things around to match what this method should return.
3460 if ( !is_array( $result ) ) {
3466 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3467 $result['text'] = $result[0];
3469 unset( $result[0] );
3476 $preprocessFlags = 0;
3477 if ( isset( $result['noparse'] ) ) {
3478 $noparse = $result['noparse'];
3480 if ( isset( $result['preprocessFlags'] ) ) {
3481 $preprocessFlags = $result['preprocessFlags'];
3485 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3486 $result['isChildObj'] = true;
3493 * Get the semi-parsed DOM representation of a template with a given title,
3494 * and its redirect destination title. Cached.
3496 * @param Title $title
3500 public function getTemplateDom( $title ) {
3501 $cacheTitle = $title;
3502 $titleText = $title->getPrefixedDBkey();
3504 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3505 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3506 $title = Title
::makeTitle( $ns, $dbk );
3507 $titleText = $title->getPrefixedDBkey();
3509 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3510 return [ $this->mTplDomCache
[$titleText], $title ];
3513 # Cache miss, go to the database
3514 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3516 if ( $text === false ) {
3517 $this->mTplDomCache
[$titleText] = false;
3518 return [ false, $title ];
3521 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3522 $this->mTplDomCache
[$titleText] = $dom;
3524 if ( !$title->equals( $cacheTitle ) ) {
3525 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3526 [ $title->getNamespace(), $title->getDBkey() ];
3529 return [ $dom, $title ];
3533 * Fetch the current revision of a given title. Note that the revision
3534 * (and even the title) may not exist in the database, so everything
3535 * contributing to the output of the parser should use this method
3536 * where possible, rather than getting the revisions themselves. This
3537 * method also caches its results, so using it benefits performance.
3540 * @param Title $title
3543 public function fetchCurrentRevisionOfTitle( $title ) {
3544 $cacheKey = $title->getPrefixedDBkey();
3545 if ( !$this->currentRevisionCache
) {
3546 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3548 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3549 $this->currentRevisionCache
->set( $cacheKey,
3550 // Defaults to Parser::statelessFetchRevision()
3551 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3554 return $this->currentRevisionCache
->get( $cacheKey );
3558 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3559 * without passing them on to it.
3562 * @param Title $title
3563 * @param Parser|bool $parser
3564 * @return Revision|bool False if missing
3566 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3567 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3573 * Fetch the unparsed text of a template and register a reference to it.
3574 * @param Title $title
3575 * @return array ( string or false, Title )
3577 public function fetchTemplateAndTitle( $title ) {
3578 // Defaults to Parser::statelessFetchTemplate()
3579 $templateCb = $this->mOptions
->getTemplateCallback();
3580 $stuff = call_user_func( $templateCb, $title, $this );
3581 // We use U+007F DELETE to distinguish strip markers from regular text.
3582 $text = $stuff['text'];
3583 if ( is_string( $stuff['text'] ) ) {
3584 $text = strtr( $text, "\x7f", "?" );
3586 $finalTitle = $stuff['finalTitle'] ??
$title;
3587 if ( isset( $stuff['deps'] ) ) {
3588 foreach ( $stuff['deps'] as $dep ) {
3589 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3590 if ( $dep['title']->equals( $this->getTitle() ) ) {
3591 // If we transclude ourselves, the final result
3592 // will change based on the new version of the page
3593 $this->mOutput
->setFlag( 'vary-revision' );
3597 return [ $text, $finalTitle ];
3601 * Fetch the unparsed text of a template and register a reference to it.
3602 * @param Title $title
3603 * @return string|bool
3605 public function fetchTemplate( $title ) {
3606 return $this->fetchTemplateAndTitle( $title )[0];
3610 * Static function to get a template
3611 * Can be overridden via ParserOptions::setTemplateCallback().
3613 * @param Title $title
3614 * @param bool|Parser $parser
3618 public static function statelessFetchTemplate( $title, $parser = false ) {
3619 $text = $skip = false;
3620 $finalTitle = $title;
3623 # Loop to fetch the article, with up to 1 redirect
3624 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3625 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3626 # Give extensions a chance to select the revision instead
3627 $id = false; # Assume current
3628 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3629 [ $parser, $title, &$skip, &$id ] );
3635 'page_id' => $title->getArticleID(),
3642 $rev = Revision
::newFromId( $id );
3643 } elseif ( $parser ) {
3644 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3646 $rev = Revision
::newFromTitle( $title );
3648 $rev_id = $rev ?
$rev->getId() : 0;
3649 # If there is no current revision, there is no page
3650 if ( $id === false && !$rev ) {
3651 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3652 $linkCache->addBadLinkObj( $title );
3657 'page_id' => $title->getArticleID(),
3658 'rev_id' => $rev_id ];
3659 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3660 # We fetched a rev from a different title; register it too...
3662 'title' => $rev->getTitle(),
3663 'page_id' => $rev->getPage(),
3664 'rev_id' => $rev_id ];
3668 $content = $rev->getContent();
3669 $text = $content ?
$content->getWikitextForTransclusion() : null;
3671 Hooks
::run( 'ParserFetchTemplate',
3672 [ $parser, $title, $rev, &$text, &$deps ] );
3674 if ( $text === false ||
$text === null ) {
3678 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3680 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3681 if ( !$message->exists() ) {
3685 $content = $message->content();
3686 $text = $message->plain();
3694 $finalTitle = $title;
3695 $title = $content->getRedirectTarget();
3699 'finalTitle' => $finalTitle,
3704 * Fetch a file and its title and register a reference to it.
3705 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3706 * @param Title $title
3707 * @param array $options Array of options to RepoGroup::findFile
3709 * @deprecated since 1.32, use fetchFileAndTitle instead
3711 public function fetchFile( $title, $options = [] ) {
3712 wfDeprecated( __METHOD__
, '1.32' );
3713 return $this->fetchFileAndTitle( $title, $options )[0];
3717 * Fetch a file and its title and register a reference to it.
3718 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3719 * @param Title $title
3720 * @param array $options Array of options to RepoGroup::findFile
3721 * @return array ( File or false, Title of file )
3723 public function fetchFileAndTitle( $title, $options = [] ) {
3724 $file = $this->fetchFileNoRegister( $title, $options );
3726 $time = $file ?
$file->getTimestamp() : false;
3727 $sha1 = $file ?
$file->getSha1() : false;
3728 # Register the file as a dependency...
3729 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3730 if ( $file && !$title->equals( $file->getTitle() ) ) {
3731 # Update fetched file title
3732 $title = $file->getTitle();
3733 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3735 return [ $file, $title ];
3739 * Helper function for fetchFileAndTitle.
3741 * Also useful if you need to fetch a file but not use it yet,
3742 * for example to get the file's handler.
3744 * @param Title $title
3745 * @param array $options Array of options to RepoGroup::findFile
3748 protected function fetchFileNoRegister( $title, $options = [] ) {
3749 if ( isset( $options['broken'] ) ) {
3750 $file = false; // broken thumbnail forced by hook
3751 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3752 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3753 } else { // get by (name,timestamp)
3754 $file = wfFindFile( $title, $options );
3760 * Transclude an interwiki link.
3762 * @param Title $title
3763 * @param string $action
3767 public function interwikiTransclude( $title, $action ) {
3768 global $wgEnableScaryTranscluding;
3770 if ( !$wgEnableScaryTranscluding ) {
3771 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3774 $url = $title->getFullURL( [ 'action' => $action ] );
3776 if ( strlen( $url ) > 255 ) {
3777 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3779 return $this->fetchScaryTemplateMaybeFromCache( $url );
3783 * @param string $url
3784 * @return mixed|string
3786 public function fetchScaryTemplateMaybeFromCache( $url ) {
3787 global $wgTranscludeCacheExpiry;
3788 $dbr = wfGetDB( DB_REPLICA
);
3789 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3790 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3791 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3793 return $obj->tc_contents
;
3796 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3797 $status = $req->execute(); // Status object
3798 if ( $status->isOK() ) {
3799 $text = $req->getContent();
3800 } elseif ( $req->getStatus() != 200 ) {
3801 // Though we failed to fetch the content, this status is useless.
3802 return wfMessage( 'scarytranscludefailed-httpstatus' )
3803 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3805 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3808 $dbw = wfGetDB( DB_MASTER
);
3809 $dbw->replace( 'transcache', [ 'tc_url' ], [
3811 'tc_time' => $dbw->timestamp( time() ),
3812 'tc_contents' => $text
3818 * Triple brace replacement -- used for template arguments
3821 * @param array $piece
3822 * @param PPFrame $frame
3826 public function argSubstitution( $piece, $frame ) {
3828 $parts = $piece['parts'];
3829 $nameWithSpaces = $frame->expand( $piece['title'] );
3830 $argName = trim( $nameWithSpaces );
3832 $text = $frame->getArgument( $argName );
3833 if ( $text === false && $parts->getLength() > 0
3834 && ( $this->ot
['html']
3836 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3839 # No match in frame, use the supplied default
3840 $object = $parts->item( 0 )->getChildren();
3842 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3843 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3844 $this->limitationWarn( 'post-expand-template-argument' );
3847 if ( $text === false && $object === false ) {
3849 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3851 if ( $error !== false ) {
3854 if ( $object !== false ) {
3855 $ret = [ 'object' => $object ];
3857 $ret = [ 'text' => $text ];
3864 * Return the text to be used for a given extension tag.
3865 * This is the ghost of strip().
3867 * @param array $params Associative array of parameters:
3868 * name PPNode for the tag name
3869 * attr PPNode for unparsed text where tag attributes are thought to be
3870 * attributes Optional associative array of parsed attributes
3871 * inner Contents of extension element
3872 * noClose Original text did not have a close tag
3873 * @param PPFrame $frame
3875 * @throws MWException
3878 public function extensionSubstitution( $params, $frame ) {
3879 static $errorStr = '<span class="error">';
3880 static $errorLen = 20;
3882 $name = $frame->expand( $params['name'] );
3883 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3884 // Probably expansion depth or node count exceeded. Just punt the
3889 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3890 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3895 // We can't safely check if the expansion for $content resulted in an
3896 // error, because the content could happen to be the error string
3898 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3900 $marker = self
::MARKER_PREFIX
. "-$name-"
3901 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3903 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3904 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3905 if ( $isFunctionTag ) {
3906 $markerType = 'none';
3908 $markerType = 'general';
3910 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3911 $name = strtolower( $name );
3912 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3913 if ( isset( $params['attributes'] ) ) {
3914 $attributes = $attributes +
$params['attributes'];
3917 if ( isset( $this->mTagHooks
[$name] ) ) {
3918 $output = call_user_func_array( $this->mTagHooks
[$name],
3919 [ $content, $attributes, $this, $frame ] );
3920 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3921 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3923 // Avoid PHP 7.1 warning from passing $this by reference
3925 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3927 $output = '<span class="error">Invalid tag extension name: ' .
3928 htmlspecialchars( $name ) . '</span>';
3931 if ( is_array( $output ) ) {
3934 $output = $flags[0];
3935 if ( isset( $flags['markerType'] ) ) {
3936 $markerType = $flags['markerType'];
3940 if ( is_null( $attrText ) ) {
3943 if ( isset( $params['attributes'] ) ) {
3944 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3945 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3946 htmlspecialchars( $attrValue ) . '"';
3949 if ( $content === null ) {
3950 $output = "<$name$attrText/>";
3952 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3953 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3957 $output = "<$name$attrText>$content$close";
3961 if ( $markerType === 'none' ) {
3963 } elseif ( $markerType === 'nowiki' ) {
3964 $this->mStripState
->addNoWiki( $marker, $output );
3965 } elseif ( $markerType === 'general' ) {
3966 $this->mStripState
->addGeneral( $marker, $output );
3968 throw new MWException( __METHOD__
. ': invalid marker type' );
3974 * Increment an include size counter
3976 * @param string $type The type of expansion
3977 * @param int $size The size of the text
3978 * @return bool False if this inclusion would take it over the maximum, true otherwise
3980 public function incrementIncludeSize( $type, $size ) {
3981 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3984 $this->mIncludeSizes
[$type] +
= $size;
3990 * Increment the expensive function count
3992 * @return bool False if the limit has been exceeded
3994 public function incrementExpensiveFunctionCount() {
3995 $this->mExpensiveFunctionCount++
;
3996 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4000 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4001 * Fills $this->mDoubleUnderscores, returns the modified text
4003 * @param string $text
4007 public function doDoubleUnderscore( $text ) {
4008 # The position of __TOC__ needs to be recorded
4009 $mw = $this->magicWordFactory
->get( 'toc' );
4010 if ( $mw->match( $text ) ) {
4011 $this->mShowToc
= true;
4012 $this->mForceTocPosition
= true;
4014 # Set a placeholder. At the end we'll fill it in with the TOC.
4015 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4017 # Only keep the first one.
4018 $text = $mw->replace( '', $text );
4021 # Now match and remove the rest of them
4022 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4023 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4025 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4026 $this->mOutput
->mNoGallery
= true;
4028 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4029 $this->mShowToc
= false;
4031 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4032 && $this->mTitle
->getNamespace() == NS_CATEGORY
4034 $this->addTrackingCategory( 'hidden-category-category' );
4036 # (T10068) Allow control over whether robots index a page.
4037 # __INDEX__ always overrides __NOINDEX__, see T16899
4038 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4039 $this->mOutput
->setIndexPolicy( 'noindex' );
4040 $this->addTrackingCategory( 'noindex-category' );
4042 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4043 $this->mOutput
->setIndexPolicy( 'index' );
4044 $this->addTrackingCategory( 'index-category' );
4047 # Cache all double underscores in the database
4048 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4049 $this->mOutput
->setProperty( $key, '' );
4056 * @see ParserOutput::addTrackingCategory()
4057 * @param string $msg Message key
4058 * @return bool Whether the addition was successful
4060 public function addTrackingCategory( $msg ) {
4061 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4065 * This function accomplishes several tasks:
4066 * 1) Auto-number headings if that option is enabled
4067 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4068 * 3) Add a Table of contents on the top for users who have enabled the option
4069 * 4) Auto-anchor headings
4071 * It loops through all headlines, collects the necessary data, then splits up the
4072 * string and re-inserts the newly formatted headlines.
4074 * @param string $text
4075 * @param string $origText Original, untouched wikitext
4076 * @param bool $isMain
4077 * @return mixed|string
4080 public function formatHeadings( $text, $origText, $isMain = true ) {
4081 global $wgMaxTocLevel;
4083 # Inhibit editsection links if requested in the page
4084 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4085 $maybeShowEditLink = false;
4087 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4090 # Get all headlines for numbering them and adding funky stuff like [edit]
4091 # links - this is for later, but we need the number of headlines right now
4092 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4093 # be trimmed here since whitespace in HTML headings is significant.
4095 $numMatches = preg_match_all(
4096 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4101 # if there are fewer than 4 headlines in the article, do not show TOC
4102 # unless it's been explicitly enabled.
4103 $enoughToc = $this->mShowToc
&&
4104 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4106 # Allow user to stipulate that a page should have a "new section"
4107 # link added via __NEWSECTIONLINK__
4108 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4109 $this->mOutput
->setNewSection( true );
4112 # Allow user to remove the "new section"
4113 # link via __NONEWSECTIONLINK__
4114 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4115 $this->mOutput
->hideNewSection( true );
4118 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4119 # override above conditions and always show TOC above first header
4120 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4121 $this->mShowToc
= true;
4129 # Ugh .. the TOC should have neat indentation levels which can be
4130 # passed to the skin functions. These are determined here
4134 $sublevelCount = [];
4140 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4141 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4142 $oldType = $this->mOutputType
;
4143 $this->setOutputType( self
::OT_WIKI
);
4144 $frame = $this->getPreprocessor()->newFrame();
4145 $root = $this->preprocessToDom( $origText );
4146 $node = $root->getFirstChild();
4151 $headlines = $numMatches !== false ?
$matches[3] : [];
4153 foreach ( $headlines as $headline ) {
4154 $isTemplate = false;
4156 $sectionIndex = false;
4158 $markerMatches = [];
4159 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4160 $serial = $markerMatches[1];
4161 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4162 $isTemplate = ( $titleText != $baseTitleText );
4163 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4167 $prevlevel = $level;
4169 $level = $matches[1][$headlineCount];
4171 if ( $level > $prevlevel ) {
4172 # Increase TOC level
4174 $sublevelCount[$toclevel] = 0;
4175 if ( $toclevel < $wgMaxTocLevel ) {
4176 $prevtoclevel = $toclevel;
4177 $toc .= Linker
::tocIndent();
4180 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4181 # Decrease TOC level, find level to jump to
4183 for ( $i = $toclevel; $i > 0; $i-- ) {
4184 if ( $levelCount[$i] == $level ) {
4185 # Found last matching level
4188 } elseif ( $levelCount[$i] < $level ) {
4189 # Found first matching level below current level
4197 if ( $toclevel < $wgMaxTocLevel ) {
4198 if ( $prevtoclevel < $wgMaxTocLevel ) {
4199 # Unindent only if the previous toc level was shown :p
4200 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4201 $prevtoclevel = $toclevel;
4203 $toc .= Linker
::tocLineEnd();
4207 # No change in level, end TOC line
4208 if ( $toclevel < $wgMaxTocLevel ) {
4209 $toc .= Linker
::tocLineEnd();
4213 $levelCount[$toclevel] = $level;
4215 # count number of headlines for each level
4216 $sublevelCount[$toclevel]++
;
4218 for ( $i = 1; $i <= $toclevel; $i++
) {
4219 if ( !empty( $sublevelCount[$i] ) ) {
4223 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4228 # The safe header is a version of the header text safe to use for links
4230 # Remove link placeholders by the link text.
4231 # <!--LINK number-->
4233 # link text with suffix
4234 # Do this before unstrip since link text can contain strip markers
4235 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4237 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4238 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4240 # Remove any <style> or <script> tags (T198618)
4241 $safeHeadline = preg_replace(
4242 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4247 # Strip out HTML (first regex removes any tag not allowed)
4249 # * <sup> and <sub> (T10393)
4253 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4254 # * <s> and <strike> (T35715)
4255 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4256 # to allow setting directionality in toc items.
4257 $tocline = preg_replace(
4259 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4260 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4266 # Strip '<span></span>', which is the result from the above if
4267 # <span id="foo"></span> is used to produce an additional anchor
4269 $tocline = str_replace( '<span></span>', '', $tocline );
4271 $tocline = trim( $tocline );
4273 # For the anchor, strip out HTML-y stuff period
4274 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4275 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4277 # Save headline for section edit hint before it's escaped
4278 $headlineHint = $safeHeadline;
4280 # Decode HTML entities
4281 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4283 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4285 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4286 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4287 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4288 if ( $fallbackHeadline === $safeHeadline ) {
4289 # No reason to have both (in fact, we can't)
4290 $fallbackHeadline = false;
4293 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4294 # @todo FIXME: We may be changing them depending on the current locale.
4295 $arrayKey = strtolower( $safeHeadline );
4296 if ( $fallbackHeadline === false ) {
4297 $fallbackArrayKey = false;
4299 $fallbackArrayKey = strtolower( $fallbackHeadline );
4302 # Create the anchor for linking from the TOC to the section
4303 $anchor = $safeHeadline;
4304 $fallbackAnchor = $fallbackHeadline;
4305 if ( isset( $refers[$arrayKey] ) ) {
4306 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4307 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4309 $linkAnchor .= "_$i";
4310 $refers["${arrayKey}_$i"] = true;
4312 $refers[$arrayKey] = true;
4314 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4315 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4316 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4317 $fallbackAnchor .= "_$i";
4318 $refers["${fallbackArrayKey}_$i"] = true;
4320 $refers[$fallbackArrayKey] = true;
4323 # Don't number the heading if it is the only one (looks silly)
4324 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4325 # the two are different if the line contains a link
4326 $headline = Html
::element(
4328 [ 'class' => 'mw-headline-number' ],
4330 ) . ' ' . $headline;
4333 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4334 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4335 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4338 # Add the section to the section tree
4339 # Find the DOM node for this header
4340 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4341 while ( $node && !$noOffset ) {
4342 if ( $node->getName() === 'h' ) {
4343 $bits = $node->splitHeading();
4344 if ( $bits['i'] == $sectionIndex ) {
4348 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4349 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4350 $node = $node->getNextSibling();
4353 'toclevel' => $toclevel,
4356 'number' => $numbering,
4357 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4358 'fromtitle' => $titleText,
4359 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4360 'anchor' => $anchor,
4363 # give headline the correct <h#> tag
4364 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4365 // Output edit section links as markers with styles that can be customized by skins
4366 if ( $isTemplate ) {
4367 # Put a T flag in the section identifier, to indicate to extractSections()
4368 # that sections inside <includeonly> should be counted.
4369 $editsectionPage = $titleText;
4370 $editsectionSection = "T-$sectionIndex";
4371 $editsectionContent = null;
4373 $editsectionPage = $this->mTitle
->getPrefixedText();
4374 $editsectionSection = $sectionIndex;
4375 $editsectionContent = $headlineHint;
4377 // We use a bit of pesudo-xml for editsection markers. The
4378 // language converter is run later on. Using a UNIQ style marker
4379 // leads to the converter screwing up the tokens when it
4380 // converts stuff. And trying to insert strip tags fails too. At
4381 // this point all real inputted tags have already been escaped,
4382 // so we don't have to worry about a user trying to input one of
4383 // these markers directly. We use a page and section attribute
4384 // to stop the language converter from converting these
4385 // important bits of data, but put the headline hint inside a
4386 // content block because the language converter is supposed to
4387 // be able to convert that piece of data.
4388 // Gets replaced with html in ParserOutput::getText
4389 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4390 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4391 if ( $editsectionContent !== null ) {
4392 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4399 $head[$headlineCount] = Linker
::makeHeadline( $level,
4400 $matches['attrib'][$headlineCount], $anchor, $headline,
4401 $editlink, $fallbackAnchor );
4406 $this->setOutputType( $oldType );
4408 # Never ever show TOC if no headers
4409 if ( $numVisible < 1 ) {
4414 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4415 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4417 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4418 $this->mOutput
->setTOCHTML( $toc );
4419 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4423 $this->mOutput
->setSections( $tocraw );
4426 # split up and insert constructed headlines
4427 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4430 // build an array of document sections
4432 foreach ( $blocks as $block ) {
4433 // $head is zero-based, sections aren't.
4434 if ( empty( $head[$i - 1] ) ) {
4435 $sections[$i] = $block;
4437 $sections[$i] = $head[$i - 1] . $block;
4441 * Send a hook, one per section.
4442 * The idea here is to be able to make section-level DIVs, but to do so in a
4443 * lower-impact, more correct way than r50769
4446 * $section : the section number
4447 * &$sectionContent : ref to the content of the section
4448 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4450 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4455 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4456 // append the TOC at the beginning
4457 // Top anchor now in skin
4458 $sections[0] = $sections[0] . $toc . "\n";
4461 $full .= implode( '', $sections );
4463 if ( $this->mForceTocPosition
) {
4464 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4471 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4472 * conversion, substituting signatures, {{subst:}} templates, etc.
4474 * @param string $text The text to transform
4475 * @param Title $title The Title object for the current article
4476 * @param User $user The User object describing the current user
4477 * @param ParserOptions $options Parsing options
4478 * @param bool $clearState Whether to clear the parser state first
4479 * @return string The altered wiki markup
4481 public function preSaveTransform( $text, Title
$title, User
$user,
4482 ParserOptions
$options, $clearState = true
4484 if ( $clearState ) {
4485 $magicScopeVariable = $this->lock();
4487 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4488 $this->setUser( $user );
4490 // Strip U+0000 NULL (T159174)
4491 $text = str_replace( "\000", '', $text );
4493 // We still normalize line endings for backwards-compatibility
4494 // with other code that just calls PST, but this should already
4495 // be handled in TextContent subclasses
4496 $text = TextContent
::normalizeLineEndings( $text );
4498 if ( $options->getPreSaveTransform() ) {
4499 $text = $this->pstPass2( $text, $user );
4501 $text = $this->mStripState
->unstripBoth( $text );
4503 $this->setUser( null ); # Reset
4509 * Pre-save transform helper function
4511 * @param string $text
4516 private function pstPass2( $text, $user ) {
4519 # Note: This is the timestamp saved as hardcoded wikitext to
4520 # the database, we use $wgContLang here in order to give
4521 # everyone the same signature and use the default one rather
4522 # than the one selected in each user's preferences.
4524 $ts = $this->mOptions
->getTimestamp();
4525 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4526 $ts = $timestamp->format( 'YmdHis' );
4527 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4529 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4531 # Variable replacement
4532 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4533 $text = $this->replaceVariables( $text );
4535 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4536 # which may corrupt this parser instance via its wfMessage()->text() call-
4539 if ( strpos( $text, '~~~' ) !== false ) {
4540 $sigText = $this->getUserSig( $user );
4541 $text = strtr( $text, [
4543 '~~~~' => "$sigText $d",
4546 # The main two signature forms used above are time-sensitive
4547 $this->mOutput
->setFlag( 'user-signature' );
4550 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4551 $tc = '[' . Title
::legalChars() . ']';
4552 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4554 // [[ns:page (context)|]]
4555 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4556 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4557 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4558 // [[ns:page (context), context|]] (using either single or double-width comma)
4559 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4560 // [[|page]] (reverse pipe trick: add context from page title)
4561 $p2 = "/\[\[\\|($tc+)]]/";
4563 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4564 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4565 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4566 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4568 $t = $this->mTitle
->getText();
4570 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4571 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4572 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4573 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4575 # if there's no context, don't bother duplicating the title
4576 $text = preg_replace( $p2, '[[\\1]]', $text );
4583 * Fetch the user's signature text, if any, and normalize to
4584 * validated, ready-to-insert wikitext.
4585 * If you have pre-fetched the nickname or the fancySig option, you can
4586 * specify them here to save a database query.
4587 * Do not reuse this parser instance after calling getUserSig(),
4588 * as it may have changed if it's the $wgParser.
4590 * @param User &$user
4591 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4592 * @param bool|null $fancySig whether the nicknname is the complete signature
4593 * or null to use default value
4596 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4597 global $wgMaxSigChars;
4599 $username = $user->getName();
4601 # If not given, retrieve from the user object.
4602 if ( $nickname === false ) {
4603 $nickname = $user->getOption( 'nickname' );
4606 if ( is_null( $fancySig ) ) {
4607 $fancySig = $user->getBoolOption( 'fancysig' );
4610 $nickname = $nickname == null ?
$username : $nickname;
4612 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4613 $nickname = $username;
4614 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4615 } elseif ( $fancySig !== false ) {
4616 # Sig. might contain markup; validate this
4617 if ( $this->validateSig( $nickname ) !== false ) {
4618 # Validated; clean up (if needed) and return it
4619 return $this->cleanSig( $nickname, true );
4621 # Failed to validate; fall back to the default
4622 $nickname = $username;
4623 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4627 # Make sure nickname doesnt get a sig in a sig
4628 $nickname = self
::cleanSigInSig( $nickname );
4630 # If we're still here, make it a link to the user page
4631 $userText = wfEscapeWikiText( $username );
4632 $nickText = wfEscapeWikiText( $nickname );
4633 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4635 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4636 ->title( $this->getTitle() )->text();
4640 * Check that the user's signature contains no bad XML
4642 * @param string $text
4643 * @return string|bool An expanded string, or false if invalid.
4645 public function validateSig( $text ) {
4646 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4650 * Clean up signature text
4652 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4653 * 2) Substitute all transclusions
4655 * @param string $text
4656 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4657 * @return string Signature text
4659 public function cleanSig( $text, $parsing = false ) {
4662 $magicScopeVariable = $this->lock();
4663 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4666 # Option to disable this feature
4667 if ( !$this->mOptions
->getCleanSignatures() ) {
4671 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4672 # => Move this logic to braceSubstitution()
4673 $substWord = $this->magicWordFactory
->get( 'subst' );
4674 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4675 $substText = '{{' . $substWord->getSynonym( 0 );
4677 $text = preg_replace( $substRegex, $substText, $text );
4678 $text = self
::cleanSigInSig( $text );
4679 $dom = $this->preprocessToDom( $text );
4680 $frame = $this->getPreprocessor()->newFrame();
4681 $text = $frame->expand( $dom );
4684 $text = $this->mStripState
->unstripBoth( $text );
4691 * Strip 3, 4 or 5 tildes out of signatures.
4693 * @param string $text
4694 * @return string Signature text with /~{3,5}/ removed
4696 public static function cleanSigInSig( $text ) {
4697 $text = preg_replace( '/~{3,5}/', '', $text );
4702 * Set up some variables which are usually set up in parse()
4703 * so that an external function can call some class members with confidence
4705 * @param Title|null $title
4706 * @param ParserOptions $options
4707 * @param int $outputType
4708 * @param bool $clearState
4710 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4711 $outputType, $clearState = true
4713 $this->startParse( $title, $options, $outputType, $clearState );
4717 * @param Title|null $title
4718 * @param ParserOptions $options
4719 * @param int $outputType
4720 * @param bool $clearState
4722 private function startParse( Title
$title = null, ParserOptions
$options,
4723 $outputType, $clearState = true
4725 $this->setTitle( $title );
4726 $this->mOptions
= $options;
4727 $this->setOutputType( $outputType );
4728 if ( $clearState ) {
4729 $this->clearState();
4734 * Wrapper for preprocess()
4736 * @param string $text The text to preprocess
4737 * @param ParserOptions $options
4738 * @param Title|null $title Title object or null to use $wgTitle
4741 public function transformMsg( $text, $options, $title = null ) {
4742 static $executing = false;
4744 # Guard against infinite recursion
4755 $text = $this->preprocess( $text, $title, $options );
4762 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4763 * The callback should have the following form:
4764 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4766 * Transform and return $text. Use $parser for any required context, e.g. use
4767 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4769 * Hooks may return extended information by returning an array, of which the
4770 * first numbered element (index 0) must be the return string, and all other
4771 * entries are extracted into local variables within an internal function
4772 * in the Parser class.
4774 * This interface (introduced r61913) appears to be undocumented, but
4775 * 'markerType' is used by some core tag hooks to override which strip
4776 * array their results are placed in. **Use great caution if attempting
4777 * this interface, as it is not documented and injudicious use could smash
4778 * private variables.**
4780 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4781 * @param callable $callback The callback function (and object) to use for the tag
4782 * @throws MWException
4783 * @return callable|null The old value of the mTagHooks array associated with the hook
4785 public function setHook( $tag, callable
$callback ) {
4786 $tag = strtolower( $tag );
4787 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4788 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4790 $oldVal = $this->mTagHooks
[$tag] ??
null;
4791 $this->mTagHooks
[$tag] = $callback;
4792 if ( !in_array( $tag, $this->mStripList
) ) {
4793 $this->mStripList
[] = $tag;
4800 * As setHook(), but letting the contents be parsed.
4802 * Transparent tag hooks are like regular XML-style tag hooks, except they
4803 * operate late in the transformation sequence, on HTML instead of wikitext.
4805 * This is probably obsoleted by things dealing with parser frames?
4806 * The only extension currently using it is geoserver.
4809 * @todo better document or deprecate this
4811 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4812 * @param callable $callback The callback function (and object) to use for the tag
4813 * @throws MWException
4814 * @return callable|null The old value of the mTagHooks array associated with the hook
4816 public function setTransparentTagHook( $tag, callable
$callback ) {
4817 $tag = strtolower( $tag );
4818 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4819 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4821 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4822 $this->mTransparentTagHooks
[$tag] = $callback;
4828 * Remove all tag hooks
4830 public function clearTagHooks() {
4831 $this->mTagHooks
= [];
4832 $this->mFunctionTagHooks
= [];
4833 $this->mStripList
= $this->mDefaultStripList
;
4837 * Create a function, e.g. {{sum:1|2|3}}
4838 * The callback function should have the form:
4839 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4841 * Or with Parser::SFH_OBJECT_ARGS:
4842 * function myParserFunction( $parser, $frame, $args ) { ... }
4844 * The callback may either return the text result of the function, or an array with the text
4845 * in element 0, and a number of flags in the other elements. The names of the flags are
4846 * specified in the keys. Valid flags are:
4847 * found The text returned is valid, stop processing the template. This
4849 * nowiki Wiki markup in the return value should be escaped
4850 * isHTML The returned text is HTML, armour it against wikitext transformation
4852 * @param string $id The magic word ID
4853 * @param callable $callback The callback function (and object) to use
4854 * @param int $flags A combination of the following flags:
4855 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4857 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4858 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4859 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4860 * the arguments, and to control the way they are expanded.
4862 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4863 * arguments, for instance:
4864 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4866 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4867 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4868 * working if/when this is changed.
4870 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4873 * Please read the documentation in includes/parser/Preprocessor.php for more information
4874 * about the methods available in PPFrame and PPNode.
4876 * @throws MWException
4877 * @return string|callable The old callback function for this name, if any
4879 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4882 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4883 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4885 # Add to function cache
4886 $mw = $this->magicWordFactory
->get( $id );
4888 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4891 $synonyms = $mw->getSynonyms();
4892 $sensitive = intval( $mw->isCaseSensitive() );
4894 foreach ( $synonyms as $syn ) {
4896 if ( !$sensitive ) {
4897 $syn = $wgContLang->lc( $syn );
4900 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4903 # Remove trailing colon
4904 if ( substr( $syn, -1, 1 ) === ':' ) {
4905 $syn = substr( $syn, 0, -1 );
4907 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4913 * Get all registered function hook identifiers
4917 public function getFunctionHooks() {
4918 return array_keys( $this->mFunctionHooks
);
4922 * Create a tag function, e.g. "<test>some stuff</test>".
4923 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4924 * Unlike parser functions, their content is not preprocessed.
4925 * @param string $tag
4926 * @param callable $callback
4928 * @throws MWException
4931 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4932 $tag = strtolower( $tag );
4933 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4934 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4936 $old = $this->mFunctionTagHooks
[$tag] ??
null;
4937 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4939 if ( !in_array( $tag, $this->mStripList
) ) {
4940 $this->mStripList
[] = $tag;
4947 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4948 * Placeholders created in Linker::link()
4950 * @param string &$text
4951 * @param int $options
4953 public function replaceLinkHolders( &$text, $options = 0 ) {
4954 $this->mLinkHolders
->replace( $text );
4958 * Replace "<!--LINK-->" link placeholders with plain text of links
4959 * (not HTML-formatted).
4961 * @param string $text
4964 public function replaceLinkHoldersText( $text ) {
4965 return $this->mLinkHolders
->replaceText( $text );
4969 * Renders an image gallery from a text with one line per image.
4970 * text labels may be given by using |-style alternative text. E.g.
4971 * Image:one.jpg|The number "1"
4972 * Image:tree.jpg|A tree
4973 * given as text will return the HTML of a gallery with two images,
4974 * labeled 'The number "1"' and
4977 * @param string $text
4978 * @param array $params
4979 * @return string HTML
4981 public function renderImageGallery( $text, $params ) {
4983 if ( isset( $params['mode'] ) ) {
4984 $mode = $params['mode'];
4988 $ig = ImageGalleryBase
::factory( $mode );
4989 } catch ( Exception
$e ) {
4990 // If invalid type set, fallback to default.
4991 $ig = ImageGalleryBase
::factory( false );
4994 $ig->setContextTitle( $this->mTitle
);
4995 $ig->setShowBytes( false );
4996 $ig->setShowDimensions( false );
4997 $ig->setShowFilename( false );
4998 $ig->setParser( $this );
4999 $ig->setHideBadImages();
5000 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5002 if ( isset( $params['showfilename'] ) ) {
5003 $ig->setShowFilename( true );
5005 $ig->setShowFilename( false );
5007 if ( isset( $params['caption'] ) ) {
5008 $caption = $params['caption'];
5009 $caption = htmlspecialchars( $caption );
5010 $caption = $this->replaceInternalLinks( $caption );
5011 $ig->setCaptionHtml( $caption );
5013 if ( isset( $params['perrow'] ) ) {
5014 $ig->setPerRow( $params['perrow'] );
5016 if ( isset( $params['widths'] ) ) {
5017 $ig->setWidths( $params['widths'] );
5019 if ( isset( $params['heights'] ) ) {
5020 $ig->setHeights( $params['heights'] );
5022 $ig->setAdditionalOptions( $params );
5024 // Avoid PHP 7.1 warning from passing $this by reference
5026 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5028 $lines = StringUtils
::explode( "\n", $text );
5029 foreach ( $lines as $line ) {
5030 # match lines like these:
5031 # Image:someimage.jpg|This is some image
5033 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5035 if ( count( $matches ) == 0 ) {
5039 if ( strpos( $matches[0], '%' ) !== false ) {
5040 $matches[1] = rawurldecode( $matches[1] );
5042 $title = Title
::newFromText( $matches[1], NS_FILE
);
5043 if ( is_null( $title ) ) {
5044 # Bogus title. Ignore these so we don't bomb out later.
5048 # We need to get what handler the file uses, to figure out parameters.
5049 # Note, a hook can overide the file name, and chose an entirely different
5050 # file (which potentially could be of a different type and have different handler).
5053 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5054 [ $this, $title, &$options, &$descQuery ] );
5055 # Don't register it now, as TraditionalImageGallery does that later.
5056 $file = $this->fetchFileNoRegister( $title, $options );
5057 $handler = $file ?
$file->getHandler() : false;
5060 'img_alt' => 'gallery-internal-alt',
5061 'img_link' => 'gallery-internal-link',
5064 $paramMap = $paramMap +
$handler->getParamMap();
5065 // We don't want people to specify per-image widths.
5066 // Additionally the width parameter would need special casing anyhow.
5067 unset( $paramMap['img_width'] );
5070 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5075 $handlerOptions = [];
5076 if ( isset( $matches[3] ) ) {
5077 // look for an |alt= definition while trying not to break existing
5078 // captions with multiple pipes (|) in it, until a more sensible grammar
5079 // is defined for images in galleries
5081 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5082 // splitting on '|' is a bit odd, and different from makeImage.
5083 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5084 // Protect LanguageConverter markup
5085 $parameterMatches = StringUtils
::delimiterExplode(
5086 '-{', '}-', '|', $matches[3], true /* nested */
5089 foreach ( $parameterMatches as $parameterMatch ) {
5090 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5092 $paramName = $paramMap[$magicName];
5094 switch ( $paramName ) {
5095 case 'gallery-internal-alt':
5096 $alt = $this->stripAltText( $match, false );
5098 case 'gallery-internal-link':
5099 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5100 $chars = self
::EXT_LINK_URL_CLASS
;
5101 $addr = self
::EXT_LINK_ADDR
;
5102 $prots = $this->mUrlProtocols
;
5103 // check to see if link matches an absolute url, if not then it must be a wiki link.
5104 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5105 // Result of LanguageConverter::markNoConversion
5106 // invoked on an external link.
5107 $linkValue = substr( $linkValue, 4, -2 );
5109 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5111 $this->mOutput
->addExternalLink( $link );
5113 $localLinkTitle = Title
::newFromText( $linkValue );
5114 if ( $localLinkTitle !== null ) {
5115 $this->mOutput
->addLink( $localLinkTitle );
5116 $link = $localLinkTitle->getLinkURL();
5121 // Must be a handler specific parameter.
5122 if ( $handler->validateParam( $paramName, $match ) ) {
5123 $handlerOptions[$paramName] = $match;
5125 // Guess not, consider it as caption.
5126 wfDebug( "$parameterMatch failed parameter validation\n" );
5127 $label = $parameterMatch;
5133 $label = $parameterMatch;
5138 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5140 $html = $ig->toHTML();
5141 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5146 * @param MediaHandler $handler
5149 public function getImageParams( $handler ) {
5151 $handlerClass = get_class( $handler );
5155 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5156 # Initialise static lists
5157 static $internalParamNames = [
5158 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5159 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5160 'bottom', 'text-bottom' ],
5161 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5162 'upright', 'border', 'link', 'alt', 'class' ],
5164 static $internalParamMap;
5165 if ( !$internalParamMap ) {
5166 $internalParamMap = [];
5167 foreach ( $internalParamNames as $type => $names ) {
5168 foreach ( $names as $name ) {
5169 // For grep: img_left, img_right, img_center, img_none,
5170 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5171 // img_bottom, img_text_bottom,
5172 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5173 // img_border, img_link, img_alt, img_class
5174 $magicName = str_replace( '-', '_', "img_$name" );
5175 $internalParamMap[$magicName] = [ $type, $name ];
5180 # Add handler params
5181 $paramMap = $internalParamMap;
5183 $handlerParamMap = $handler->getParamMap();
5184 foreach ( $handlerParamMap as $magic => $paramName ) {
5185 $paramMap[$magic] = [ 'handler', $paramName ];
5188 $this->mImageParams
[$handlerClass] = $paramMap;
5189 $this->mImageParamsMagicArray
[$handlerClass] =
5190 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5192 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5196 * Parse image options text and use it to make an image
5198 * @param Title $title
5199 * @param string $options
5200 * @param LinkHolderArray|bool $holders
5201 * @return string HTML
5203 public function makeImage( $title, $options, $holders = false ) {
5204 # Check if the options text is of the form "options|alt text"
5206 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5207 # * left no resizing, just left align. label is used for alt= only
5208 # * right same, but right aligned
5209 # * none same, but not aligned
5210 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5211 # * center center the image
5212 # * frame Keep original image size, no magnify-button.
5213 # * framed Same as "frame"
5214 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5215 # * upright reduce width for upright images, rounded to full __0 px
5216 # * border draw a 1px border around the image
5217 # * alt Text for HTML alt attribute (defaults to empty)
5218 # * class Set a class for img node
5219 # * link Set the target of the image link. Can be external, interwiki, or local
5220 # vertical-align values (no % or length right now):
5230 # Protect LanguageConverter markup when splitting into parts
5231 $parts = StringUtils
::delimiterExplode(
5232 '-{', '}-', '|', $options, true /* allow nesting */
5235 # Give extensions a chance to select the file revision for us
5238 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5239 [ $this, $title, &$options, &$descQuery ] );
5240 # Fetch and register the file (file title may be different via hooks)
5241 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5244 $handler = $file ?
$file->getHandler() : false;
5246 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5249 $this->addTrackingCategory( 'broken-file-category' );
5252 # Process the input parameters
5254 $params = [ 'frame' => [], 'handler' => [],
5255 'horizAlign' => [], 'vertAlign' => [] ];
5256 $seenformat = false;
5257 foreach ( $parts as $part ) {
5258 $part = trim( $part );
5259 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5261 if ( isset( $paramMap[$magicName] ) ) {
5262 list( $type, $paramName ) = $paramMap[$magicName];
5264 # Special case; width and height come in one variable together
5265 if ( $type === 'handler' && $paramName === 'width' ) {
5266 $parsedWidthParam = self
::parseWidthParam( $value );
5267 if ( isset( $parsedWidthParam['width'] ) ) {
5268 $width = $parsedWidthParam['width'];
5269 if ( $handler->validateParam( 'width', $width ) ) {
5270 $params[$type]['width'] = $width;
5274 if ( isset( $parsedWidthParam['height'] ) ) {
5275 $height = $parsedWidthParam['height'];
5276 if ( $handler->validateParam( 'height', $height ) ) {
5277 $params[$type]['height'] = $height;
5281 # else no validation -- T15436
5283 if ( $type === 'handler' ) {
5284 # Validate handler parameter
5285 $validated = $handler->validateParam( $paramName, $value );
5287 # Validate internal parameters
5288 switch ( $paramName ) {
5292 # @todo FIXME: Possibly check validity here for
5293 # manualthumb? downstream behavior seems odd with
5294 # missing manual thumbs.
5296 $value = $this->stripAltText( $value, $holders );
5299 $chars = self
::EXT_LINK_URL_CLASS
;
5300 $addr = self
::EXT_LINK_ADDR
;
5301 $prots = $this->mUrlProtocols
;
5302 if ( $value === '' ) {
5303 $paramName = 'no-link';
5306 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5307 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5308 $paramName = 'link-url';
5309 $this->mOutput
->addExternalLink( $value );
5310 if ( $this->mOptions
->getExternalLinkTarget() ) {
5311 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5316 $linkTitle = Title
::newFromText( $value );
5318 $paramName = 'link-title';
5319 $value = $linkTitle;
5320 $this->mOutput
->addLink( $linkTitle );
5328 // use first appearing option, discard others.
5329 $validated = !$seenformat;
5333 # Most other things appear to be empty or numeric...
5334 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5339 $params[$type][$paramName] = $value;
5343 if ( !$validated ) {
5348 # Process alignment parameters
5349 if ( $params['horizAlign'] ) {
5350 $params['frame']['align'] = key( $params['horizAlign'] );
5352 if ( $params['vertAlign'] ) {
5353 $params['frame']['valign'] = key( $params['vertAlign'] );
5356 $params['frame']['caption'] = $caption;
5358 # Will the image be presented in a frame, with the caption below?
5359 $imageIsFramed = isset( $params['frame']['frame'] )
5360 ||
isset( $params['frame']['framed'] )
5361 ||
isset( $params['frame']['thumbnail'] )
5362 ||
isset( $params['frame']['manualthumb'] );
5364 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5365 # came to also set the caption, ordinary text after the image -- which
5366 # makes no sense, because that just repeats the text multiple times in
5367 # screen readers. It *also* came to set the title attribute.
5368 # Now that we have an alt attribute, we should not set the alt text to
5369 # equal the caption: that's worse than useless, it just repeats the
5370 # text. This is the framed/thumbnail case. If there's no caption, we
5371 # use the unnamed parameter for alt text as well, just for the time be-
5372 # ing, if the unnamed param is set and the alt param is not.
5373 # For the future, we need to figure out if we want to tweak this more,
5374 # e.g., introducing a title= parameter for the title; ignoring the un-
5375 # named parameter entirely for images without a caption; adding an ex-
5376 # plicit caption= parameter and preserving the old magic unnamed para-
5378 if ( $imageIsFramed ) { # Framed image
5379 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5380 # No caption or alt text, add the filename as the alt text so
5381 # that screen readers at least get some description of the image
5382 $params['frame']['alt'] = $title->getText();
5384 # Do not set $params['frame']['title'] because tooltips don't make sense
5386 } else { # Inline image
5387 if ( !isset( $params['frame']['alt'] ) ) {
5388 # No alt text, use the "caption" for the alt text
5389 if ( $caption !== '' ) {
5390 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5392 # No caption, fall back to using the filename for the
5394 $params['frame']['alt'] = $title->getText();
5397 # Use the "caption" for the tooltip text
5398 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5401 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5403 # Linker does the rest
5404 $time = $options['time'] ??
false;
5405 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5406 $time, $descQuery, $this->mOptions
->getThumbSize() );
5408 # Give the handler a chance to modify the parser object
5410 $handler->parserTransformHook( $this, $file );
5417 * @param string $caption
5418 * @param LinkHolderArray|bool $holders
5419 * @return mixed|string
5421 protected function stripAltText( $caption, $holders ) {
5422 # Strip bad stuff out of the title (tooltip). We can't just use
5423 # replaceLinkHoldersText() here, because if this function is called
5424 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5426 $tooltip = $holders->replaceText( $caption );
5428 $tooltip = $this->replaceLinkHoldersText( $caption );
5431 # make sure there are no placeholders in thumbnail attributes
5432 # that are later expanded to html- so expand them now and
5434 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5435 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5441 * Set a flag in the output object indicating that the content is dynamic and
5442 * shouldn't be cached.
5443 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5445 public function disableCache() {
5446 wfDebug( "Parser output marked as uncacheable.\n" );
5447 if ( !$this->mOutput
) {
5448 throw new MWException( __METHOD__
.
5449 " can only be called when actually parsing something" );
5451 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5455 * Callback from the Sanitizer for expanding items found in HTML attribute
5456 * values, so they can be safely tested and escaped.
5458 * @param string &$text
5459 * @param bool|PPFrame $frame
5462 public function attributeStripCallback( &$text, $frame = false ) {
5463 $text = $this->replaceVariables( $text, $frame );
5464 $text = $this->mStripState
->unstripBoth( $text );
5473 public function getTags() {
5475 array_keys( $this->mTransparentTagHooks
),
5476 array_keys( $this->mTagHooks
),
5477 array_keys( $this->mFunctionTagHooks
)
5482 * Replace transparent tags in $text with the values given by the callbacks.
5484 * Transparent tag hooks are like regular XML-style tag hooks, except they
5485 * operate late in the transformation sequence, on HTML instead of wikitext.
5487 * @param string $text
5491 public function replaceTransparentTags( $text ) {
5493 $elements = array_keys( $this->mTransparentTagHooks
);
5494 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5497 foreach ( $matches as $marker => $data ) {
5498 list( $element, $content, $params, $tag ) = $data;
5499 $tagName = strtolower( $element );
5500 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5501 $output = call_user_func_array(
5502 $this->mTransparentTagHooks
[$tagName],
5503 [ $content, $params, $this ]
5508 $replacements[$marker] = $output;
5510 return strtr( $text, $replacements );
5514 * Break wikitext input into sections, and either pull or replace
5515 * some particular section's text.
5517 * External callers should use the getSection and replaceSection methods.
5519 * @param string $text Page wikitext
5520 * @param string|int $sectionId A section identifier string of the form:
5521 * "<flag1> - <flag2> - ... - <section number>"
5523 * Currently the only recognised flag is "T", which means the target section number
5524 * was derived during a template inclusion parse, in other words this is a template
5525 * section edit link. If no flags are given, it was an ordinary section edit link.
5526 * This flag is required to avoid a section numbering mismatch when a section is
5527 * enclosed by "<includeonly>" (T8563).
5529 * The section number 0 pulls the text before the first heading; other numbers will
5530 * pull the given section along with its lower-level subsections. If the section is
5531 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5533 * Section 0 is always considered to exist, even if it only contains the empty
5534 * string. If $text is the empty string and section 0 is replaced, $newText is
5537 * @param string $mode One of "get" or "replace"
5538 * @param string $newText Replacement text for section data.
5539 * @return string For "get", the extracted section text.
5540 * for "replace", the whole page with the section replaced.
5542 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5543 global $wgTitle; # not generally used but removes an ugly failure mode
5545 $magicScopeVariable = $this->lock();
5546 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5548 $frame = $this->getPreprocessor()->newFrame();
5550 # Process section extraction flags
5552 $sectionParts = explode( '-', $sectionId );
5553 $sectionIndex = array_pop( $sectionParts );
5554 foreach ( $sectionParts as $part ) {
5555 if ( $part === 'T' ) {
5556 $flags |
= self
::PTD_FOR_INCLUSION
;
5560 # Check for empty input
5561 if ( strval( $text ) === '' ) {
5562 # Only sections 0 and T-0 exist in an empty document
5563 if ( $sectionIndex == 0 ) {
5564 if ( $mode === 'get' ) {
5570 if ( $mode === 'get' ) {
5578 # Preprocess the text
5579 $root = $this->preprocessToDom( $text, $flags );
5581 # <h> nodes indicate section breaks
5582 # They can only occur at the top level, so we can find them by iterating the root's children
5583 $node = $root->getFirstChild();
5585 # Find the target section
5586 if ( $sectionIndex == 0 ) {
5587 # Section zero doesn't nest, level=big
5588 $targetLevel = 1000;
5591 if ( $node->getName() === 'h' ) {
5592 $bits = $node->splitHeading();
5593 if ( $bits['i'] == $sectionIndex ) {
5594 $targetLevel = $bits['level'];
5598 if ( $mode === 'replace' ) {
5599 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5601 $node = $node->getNextSibling();
5607 if ( $mode === 'get' ) {
5614 # Find the end of the section, including nested sections
5616 if ( $node->getName() === 'h' ) {
5617 $bits = $node->splitHeading();
5618 $curLevel = $bits['level'];
5619 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5623 if ( $mode === 'get' ) {
5624 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5626 $node = $node->getNextSibling();
5629 # Write out the remainder (in replace mode only)
5630 if ( $mode === 'replace' ) {
5631 # Output the replacement text
5632 # Add two newlines on -- trailing whitespace in $newText is conventionally
5633 # stripped by the editor, so we need both newlines to restore the paragraph gap
5634 # Only add trailing whitespace if there is newText
5635 if ( $newText != "" ) {
5636 $outText .= $newText . "\n\n";
5640 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5641 $node = $node->getNextSibling();
5645 if ( is_string( $outText ) ) {
5646 # Re-insert stripped tags
5647 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5654 * This function returns the text of a section, specified by a number ($section).
5655 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5656 * the first section before any such heading (section 0).
5658 * If a section contains subsections, these are also returned.
5660 * @param string $text Text to look in
5661 * @param string|int $sectionId Section identifier as a number or string
5662 * (e.g. 0, 1 or 'T-1').
5663 * @param string $defaultText Default to return if section is not found
5665 * @return string Text of the requested section
5667 public function getSection( $text, $sectionId, $defaultText = '' ) {
5668 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5672 * This function returns $oldtext after the content of the section
5673 * specified by $section has been replaced with $text. If the target
5674 * section does not exist, $oldtext is returned unchanged.
5676 * @param string $oldText Former text of the article
5677 * @param string|int $sectionId Section identifier as a number or string
5678 * (e.g. 0, 1 or 'T-1').
5679 * @param string $newText Replacing text
5681 * @return string Modified text
5683 public function replaceSection( $oldText, $sectionId, $newText ) {
5684 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5688 * Get the ID of the revision we are parsing
5692 public function getRevisionId() {
5693 return $this->mRevisionId
;
5697 * Get the revision object for $this->mRevisionId
5699 * @return Revision|null Either a Revision object or null
5700 * @since 1.23 (public since 1.23)
5702 public function getRevisionObject() {
5703 if ( !is_null( $this->mRevisionObject
) ) {
5704 return $this->mRevisionObject
;
5706 if ( is_null( $this->mRevisionId
) ) {
5710 $rev = call_user_func(
5711 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5714 # If the parse is for a new revision, then the callback should have
5715 # already been set to force the object and should match mRevisionId.
5716 # If not, try to fetch by mRevisionId for sanity.
5717 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5718 $rev = Revision
::newFromId( $this->mRevisionId
);
5721 $this->mRevisionObject
= $rev;
5723 return $this->mRevisionObject
;
5727 * Get the timestamp associated with the current revision, adjusted for
5728 * the default server-local timestamp
5731 public function getRevisionTimestamp() {
5732 if ( is_null( $this->mRevisionTimestamp
) ) {
5735 $revObject = $this->getRevisionObject();
5736 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5738 # The cryptic '' timezone parameter tells to use the site-default
5739 # timezone offset instead of the user settings.
5740 # Since this value will be saved into the parser cache, served
5741 # to other users, and potentially even used inside links and such,
5742 # it needs to be consistent for all visitors.
5743 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5746 return $this->mRevisionTimestamp
;
5750 * Get the name of the user that edited the last revision
5752 * @return string User name
5754 public function getRevisionUser() {
5755 if ( is_null( $this->mRevisionUser
) ) {
5756 $revObject = $this->getRevisionObject();
5758 # if this template is subst: the revision id will be blank,
5759 # so just use the current user's name
5761 $this->mRevisionUser
= $revObject->getUserText();
5762 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5763 $this->mRevisionUser
= $this->getUser()->getName();
5766 return $this->mRevisionUser
;
5770 * Get the size of the revision
5772 * @return int|null Revision size
5774 public function getRevisionSize() {
5775 if ( is_null( $this->mRevisionSize
) ) {
5776 $revObject = $this->getRevisionObject();
5778 # if this variable is subst: the revision id will be blank,
5779 # so just use the parser input size, because the own substituation
5780 # will change the size.
5782 $this->mRevisionSize
= $revObject->getSize();
5784 $this->mRevisionSize
= $this->mInputSize
;
5787 return $this->mRevisionSize
;
5791 * Mutator for $mDefaultSort
5793 * @param string $sort New value
5795 public function setDefaultSort( $sort ) {
5796 $this->mDefaultSort
= $sort;
5797 $this->mOutput
->setProperty( 'defaultsort', $sort );
5801 * Accessor for $mDefaultSort
5802 * Will use the empty string if none is set.
5804 * This value is treated as a prefix, so the
5805 * empty string is equivalent to sorting by
5810 public function getDefaultSort() {
5811 if ( $this->mDefaultSort
!== false ) {
5812 return $this->mDefaultSort
;
5819 * Accessor for $mDefaultSort
5820 * Unlike getDefaultSort(), will return false if none is set
5822 * @return string|bool
5824 public function getCustomDefaultSort() {
5825 return $this->mDefaultSort
;
5828 private static function getSectionNameFromStrippedText( $text ) {
5829 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5830 $text = Sanitizer
::decodeCharReferences( $text );
5831 $text = self
::normalizeSectionName( $text );
5835 private static function makeAnchor( $sectionName ) {
5836 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5839 private static function makeLegacyAnchor( $sectionName ) {
5840 global $wgFragmentMode;
5841 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5842 // ForAttribute() and ForLink() are the same for legacy encoding
5843 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5845 $id = Sanitizer
::escapeIdForLink( $sectionName );
5852 * Try to guess the section anchor name based on a wikitext fragment
5853 * presumably extracted from a heading, for example "Header" from
5856 * @param string $text
5857 * @return string Anchor (starting with '#')
5859 public function guessSectionNameFromWikiText( $text ) {
5860 # Strip out wikitext links(they break the anchor)
5861 $text = $this->stripSectionName( $text );
5862 $sectionName = self
::getSectionNameFromStrippedText( $text );
5863 return self
::makeAnchor( $sectionName );
5867 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5868 * instead, if possible. For use in redirects, since various versions
5869 * of Microsoft browsers interpret Location: headers as something other
5870 * than UTF-8, resulting in breakage.
5872 * @param string $text The section name
5873 * @return string Anchor (starting with '#')
5875 public function guessLegacySectionNameFromWikiText( $text ) {
5876 # Strip out wikitext links(they break the anchor)
5877 $text = $this->stripSectionName( $text );
5878 $sectionName = self
::getSectionNameFromStrippedText( $text );
5879 return self
::makeLegacyAnchor( $sectionName );
5883 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5884 * @param string $text Section name (plain text)
5885 * @return string Anchor (starting with '#')
5887 public static function guessSectionNameFromStrippedText( $text ) {
5888 $sectionName = self
::getSectionNameFromStrippedText( $text );
5889 return self
::makeAnchor( $sectionName );
5893 * Apply the same normalization as code making links to this section would
5895 * @param string $text
5898 private static function normalizeSectionName( $text ) {
5899 # T90902: ensure the same normalization is applied for IDs as to links
5900 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5903 $parts = $titleParser->splitTitleString( "#$text" );
5904 } catch ( MalformedTitleException
$ex ) {
5907 return $parts['fragment'];
5911 * Strips a text string of wikitext for use in a section anchor
5913 * Accepts a text string and then removes all wikitext from the
5914 * string and leaves only the resultant text (i.e. the result of
5915 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5916 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5917 * to create valid section anchors by mimicing the output of the
5918 * parser when headings are parsed.
5920 * @param string $text Text string to be stripped of wikitext
5921 * for use in a Section anchor
5922 * @return string Filtered text string
5924 public function stripSectionName( $text ) {
5925 # Strip internal link markup
5926 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5927 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5929 # Strip external link markup
5930 # @todo FIXME: Not tolerant to blank link text
5931 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5932 # on how many empty links there are on the page - need to figure that out.
5933 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5935 # Parse wikitext quotes (italics & bold)
5936 $text = $this->doQuotes( $text );
5939 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5944 * strip/replaceVariables/unstrip for preprocessor regression testing
5946 * @param string $text
5947 * @param Title $title
5948 * @param ParserOptions $options
5949 * @param int $outputType
5953 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5954 $outputType = self
::OT_HTML
5956 $magicScopeVariable = $this->lock();
5957 $this->startParse( $title, $options, $outputType, true );
5959 $text = $this->replaceVariables( $text );
5960 $text = $this->mStripState
->unstripBoth( $text );
5961 $text = Sanitizer
::removeHTMLtags( $text );
5966 * @param string $text
5967 * @param Title $title
5968 * @param ParserOptions $options
5971 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5972 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5976 * @param string $text
5977 * @param Title $title
5978 * @param ParserOptions $options
5981 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5982 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5986 * Call a callback function on all regions of the given text that are not
5987 * inside strip markers, and replace those regions with the return value
5988 * of the callback. For example, with input:
5992 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5993 * two strings will be replaced with the value returned by the callback in
5997 * @param callable $callback
6001 public function markerSkipCallback( $s, $callback ) {
6004 while ( $i < strlen( $s ) ) {
6005 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6006 if ( $markerStart === false ) {
6007 $out .= call_user_func( $callback, substr( $s, $i ) );
6010 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6011 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6012 if ( $markerEnd === false ) {
6013 $out .= substr( $s, $markerStart );
6016 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6017 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6026 * Remove any strip markers found in the given text.
6028 * @param string $text
6031 public function killMarkers( $text ) {
6032 return $this->mStripState
->killMarkers( $text );
6036 * Save the parser state required to convert the given half-parsed text to
6037 * HTML. "Half-parsed" in this context means the output of
6038 * recursiveTagParse() or internalParse(). This output has strip markers
6039 * from replaceVariables (extensionSubstitution() etc.), and link
6040 * placeholders from replaceLinkHolders().
6042 * Returns an array which can be serialized and stored persistently. This
6043 * array can later be loaded into another parser instance with
6044 * unserializeHalfParsedText(). The text can then be safely incorporated into
6045 * the return value of a parser hook.
6047 * @deprecated since 1.31
6048 * @param string $text
6052 public function serializeHalfParsedText( $text ) {
6053 wfDeprecated( __METHOD__
, '1.31' );
6056 'version' => self
::HALF_PARSED_VERSION
,
6057 'stripState' => $this->mStripState
->getSubState( $text ),
6058 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6064 * Load the parser state given in the $data array, which is assumed to
6065 * have been generated by serializeHalfParsedText(). The text contents is
6066 * extracted from the array, and its markers are transformed into markers
6067 * appropriate for the current Parser instance. This transformed text is
6068 * returned, and can be safely included in the return value of a parser
6071 * If the $data array has been stored persistently, the caller should first
6072 * check whether it is still valid, by calling isValidHalfParsedText().
6074 * @deprecated since 1.31
6075 * @param array $data Serialized data
6076 * @throws MWException
6079 public function unserializeHalfParsedText( $data ) {
6080 wfDeprecated( __METHOD__
, '1.31' );
6081 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6082 throw new MWException( __METHOD__
. ': invalid version' );
6085 # First, extract the strip state.
6086 $texts = [ $data['text'] ];
6087 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6089 # Now renumber links
6090 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6092 # Should be good to go.
6097 * Returns true if the given array, presumed to be generated by
6098 * serializeHalfParsedText(), is compatible with the current version of the
6101 * @deprecated since 1.31
6102 * @param array $data
6106 public function isValidHalfParsedText( $data ) {
6107 wfDeprecated( __METHOD__
, '1.31' );
6108 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6112 * Parsed a width param of imagelink like 300px or 200x300px
6114 * @param string $value
6115 * @param bool $parseHeight
6120 public static function parseWidthParam( $value, $parseHeight = true ) {
6121 $parsedWidthParam = [];
6122 if ( $value === '' ) {
6123 return $parsedWidthParam;
6126 # (T15500) In both cases (width/height and width only),
6127 # permit trailing "px" for backward compatibility.
6128 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6129 $width = intval( $m[1] );
6130 $height = intval( $m[2] );
6131 $parsedWidthParam['width'] = $width;
6132 $parsedWidthParam['height'] = $height;
6133 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6134 $width = intval( $value );
6135 $parsedWidthParam['width'] = $width;
6137 return $parsedWidthParam;
6141 * Lock the current instance of the parser.
6143 * This is meant to stop someone from calling the parser
6144 * recursively and messing up all the strip state.
6146 * @throws MWException If parser is in a parse
6147 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6149 protected function lock() {
6150 if ( $this->mInParse
) {
6151 throw new MWException( "Parser state cleared while parsing. "
6152 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6155 // Save the backtrace when locking, so that if some code tries locking again,
6156 // we can print the lock owner's backtrace for easier debugging
6158 $this->mInParse
= $e->getTraceAsString();
6160 $recursiveCheck = new ScopedCallback( function () {
6161 $this->mInParse
= false;
6164 return $recursiveCheck;
6168 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6170 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6171 * or if there is more than one <p/> tag in the input HTML.
6173 * @param string $html
6177 public static function stripOuterParagraph( $html ) {
6179 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6180 if ( strpos( $m[1], '</p>' ) === false ) {
6189 * Return this parser if it is not doing anything, otherwise
6190 * get a fresh parser. You can use this method by doing
6191 * $myParser = $wgParser->getFreshParser(), or more simply
6192 * $wgParser->getFreshParser()->parse( ... );
6193 * if you're unsure if $wgParser is safe to use.
6196 * @return Parser A parser object that is not parsing anything
6198 public function getFreshParser() {
6199 global $wgParserConf;
6200 if ( $this->mInParse
) {
6201 return new $wgParserConf['class']( $wgParserConf );
6208 * Set's up the PHP implementation of OOUI for use in this request
6209 * and instructs OutputPage to enable OOUI for itself.
6213 public function enableOOUI() {
6214 OutputPage
::setupOOUI();
6215 $this->mOutput
->setEnableOOUI( true );