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\Linker\LinkRendererFactory
;
25 use MediaWiki\Linker\LinkTarget
;
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Special\SpecialPageFactory
;
28 use Wikimedia\ScopedCallback
;
31 * @defgroup Parser Parser
35 * PHP Parser - Processes wiki markup (which uses a more user-friendly
36 * syntax, such as "[[link]]" for making links), and provides a one-way
37 * transformation of that wiki markup it into (X)HTML output / markup
38 * (which in turn the browser understands, and can display).
40 * There are seven main entry points into the Parser class:
43 * produces HTML output
44 * - Parser::preSaveTransform()
45 * produces altered wiki markup
46 * - Parser::preprocess()
47 * removes HTML comments and expands templates
48 * - Parser::cleanSig() and Parser::cleanSigInSig()
49 * cleans a signature before saving it to preferences
50 * - Parser::getSection()
51 * return the content of a section from an article for section editing
52 * - Parser::replaceSection()
53 * replaces a section by number inside an article
54 * - Parser::getPreloadText()
55 * 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;
272 /** @var ParserFactory */
275 /** @var SpecialPageFactory */
276 private $specialPageFactory;
281 /** @var LinkRendererFactory */
282 private $linkRendererFactory;
284 /** @var NamespaceInfo */
288 * @param array $parserConf See $wgParserConf documentation
289 * @param MagicWordFactory|null $magicWordFactory
290 * @param Language|null $contLang Content language
291 * @param ParserFactory|null $factory
292 * @param string|null $urlProtocols As returned from wfUrlProtocols()
293 * @param SpecialPageFactory|null $spFactory
294 * @param Config|null $siteConfig
295 * @param LinkRendererFactory|null $linkRendererFactory
296 * @param NamespaceInfo|null $nsInfo
298 public function __construct(
299 array $parserConf = [], MagicWordFactory
$magicWordFactory = null,
300 Language
$contLang = null, ParserFactory
$factory = null, $urlProtocols = null,
301 SpecialPageFactory
$spFactory = null, Config
$siteConfig = null,
302 LinkRendererFactory
$linkRendererFactory = null,
303 NamespaceInfo
$nsInfo = null
305 $this->mConf
= $parserConf;
306 $this->mUrlProtocols
= $urlProtocols ??
wfUrlProtocols();
307 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
308 self
::EXT_LINK_ADDR
.
309 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
310 if ( isset( $parserConf['preprocessorClass'] ) ) {
311 $this->mPreprocessorClass
= $parserConf['preprocessorClass'];
312 } elseif ( wfIsHHVM() ) {
313 # Under HHVM Preprocessor_Hash is much faster than Preprocessor_DOM
314 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
315 } elseif ( extension_loaded( 'domxml' ) ) {
316 # PECL extension that conflicts with the core DOM extension (T15770)
317 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
318 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
319 } elseif ( extension_loaded( 'dom' ) ) {
320 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
322 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
324 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
326 $services = MediaWikiServices
::getInstance();
327 $this->magicWordFactory
= $magicWordFactory ??
328 $services->getMagicWordFactory();
330 $this->contLang
= $contLang ??
$services->getContentLanguage();
332 $this->factory
= $factory ??
$services->getParserFactory();
333 $this->specialPageFactory
= $spFactory ??
$services->getSpecialPageFactory();
334 $this->siteConfig
= $siteConfig ??
$services->getMainConfig();
335 $this->linkRendererFactory
=
336 $linkRendererFactory ??
$services->getLinkRendererFactory();
337 $this->nsInfo
= $nsInfo ??
$services->getNamespaceInfo();
341 * Reduce memory usage to reduce the impact of circular references
343 public function __destruct() {
344 if ( isset( $this->mLinkHolders
) ) {
345 unset( $this->mLinkHolders
);
347 foreach ( $this as $name => $value ) {
348 unset( $this->$name );
353 * Allow extensions to clean up when the parser is cloned
355 public function __clone() {
356 $this->mInParse
= false;
358 // T58226: When you create a reference "to" an object field, that
359 // makes the object field itself be a reference too (until the other
360 // reference goes out of scope). When cloning, any field that's a
361 // reference is copied as a reference in the new object. Both of these
362 // are defined PHP5 behaviors, as inconvenient as it is for us when old
363 // hooks from PHP4 days are passing fields by reference.
364 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
365 // Make a non-reference copy of the field, then rebind the field to
366 // reference the new copy.
372 Hooks
::run( 'ParserCloned', [ $this ] );
376 * Do various kinds of initialisation on the first call of the parser
378 public function firstCallInit() {
379 if ( !$this->mFirstCall
) {
382 $this->mFirstCall
= false;
384 CoreParserFunctions
::register( $this );
385 CoreTagHooks
::register( $this );
386 $this->initialiseVariables();
388 // Avoid PHP 7.1 warning from passing $this by reference
390 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
398 public function clearState() {
399 $this->firstCallInit();
400 $this->mOutput
= new ParserOutput
;
401 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
402 $this->mAutonumber
= 0;
403 $this->mIncludeCount
= [];
404 $this->mLinkHolders
= new LinkHolderArray( $this );
406 $this->mRevisionObject
= $this->mRevisionTimestamp
=
407 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
408 $this->mVarCache
= [];
410 $this->mLangLinkLanguages
= [];
411 $this->currentRevisionCache
= null;
413 $this->mStripState
= new StripState( $this );
415 # Clear these on every parse, T6549
416 $this->mTplRedirCache
= $this->mTplDomCache
= [];
418 $this->mShowToc
= true;
419 $this->mForceTocPosition
= false;
420 $this->mIncludeSizes
= [
424 $this->mPPNodeCount
= 0;
425 $this->mGeneratedPPNodeCount
= 0;
426 $this->mHighestExpansionDepth
= 0;
427 $this->mDefaultSort
= false;
428 $this->mHeadings
= [];
429 $this->mDoubleUnderscores
= [];
430 $this->mExpensiveFunctionCount
= 0;
433 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
434 $this->mPreprocessor
= null;
437 $this->mProfiler
= new SectionProfiler();
439 // Avoid PHP 7.1 warning from passing $this by reference
441 Hooks
::run( 'ParserClearState', [ &$parser ] );
445 * Convert wikitext to HTML
446 * Do not call this function recursively.
448 * @param string $text Text we want to parse
449 * @param-taint $text escapes_htmlnoent
450 * @param Title $title
451 * @param ParserOptions $options
452 * @param bool $linestart
453 * @param bool $clearState
454 * @param int|null $revid Number to pass in {{REVISIONID}}
455 * @return ParserOutput A ParserOutput
456 * @return-taint escaped
458 public function parse(
459 $text, Title
$title, ParserOptions
$options,
460 $linestart = true, $clearState = true, $revid = null
463 // We use U+007F DELETE to construct strip markers, so we have to make
464 // sure that this character does not occur in the input text.
465 $text = strtr( $text, "\x7f", "?" );
466 $magicScopeVariable = $this->lock();
468 // Strip U+0000 NULL (T159174)
469 $text = str_replace( "\000", '', $text );
471 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
473 $this->currentRevisionCache
= null;
474 $this->mInputSize
= strlen( $text );
475 if ( $this->mOptions
->getEnableLimitReport() ) {
476 $this->mOutput
->resetParseStartTime();
479 $oldRevisionId = $this->mRevisionId
;
480 $oldRevisionObject = $this->mRevisionObject
;
481 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
482 $oldRevisionUser = $this->mRevisionUser
;
483 $oldRevisionSize = $this->mRevisionSize
;
484 if ( $revid !== null ) {
485 $this->mRevisionId
= $revid;
486 $this->mRevisionObject
= null;
487 $this->mRevisionTimestamp
= null;
488 $this->mRevisionUser
= null;
489 $this->mRevisionSize
= null;
492 // Avoid PHP 7.1 warning from passing $this by reference
494 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
496 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
497 $text = $this->internalParse( $text );
498 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
500 $text = $this->internalParseHalfParsed( $text, true, $linestart );
503 * A converted title will be provided in the output object if title and
504 * content conversion are enabled, the article text does not contain
505 * a conversion-suppressing double-underscore tag, and no
506 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
507 * automatic link conversion.
509 if ( !( $options->getDisableTitleConversion()
510 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
511 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
512 ||
$this->mOutput
->getDisplayTitle() !== false )
514 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
515 if ( $convruletitle ) {
516 $this->mOutput
->setTitleText( $convruletitle );
518 $titleText = $this->getTargetLanguage()->convertTitle( $title );
519 $this->mOutput
->setTitleText( $titleText );
523 # Compute runtime adaptive expiry if set
524 $this->mOutput
->finalizeAdaptiveCacheExpiry();
526 # Warn if too many heavyweight parser functions were used
527 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
528 $this->limitationWarn( 'expensive-parserfunction',
529 $this->mExpensiveFunctionCount
,
530 $this->mOptions
->getExpensiveParserFunctionLimit()
534 # Information on limits, for the benefit of users who try to skirt them
535 if ( $this->mOptions
->getEnableLimitReport() ) {
536 $text .= $this->makeLimitReport();
539 # Wrap non-interface parser output in a <div> so it can be targeted
541 $class = $this->mOptions
->getWrapOutputClass();
542 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
543 $this->mOutput
->addWrapperDivClass( $class );
546 $this->mOutput
->setText( $text );
548 $this->mRevisionId
= $oldRevisionId;
549 $this->mRevisionObject
= $oldRevisionObject;
550 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
551 $this->mRevisionUser
= $oldRevisionUser;
552 $this->mRevisionSize
= $oldRevisionSize;
553 $this->mInputSize
= false;
554 $this->currentRevisionCache
= null;
556 return $this->mOutput
;
560 * Set the limit report data in the current ParserOutput, and return the
561 * limit report HTML comment.
565 protected function makeLimitReport() {
566 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
568 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
569 if ( $cpuTime !== null ) {
570 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
571 sprintf( "%.3f", $cpuTime )
575 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
576 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
577 sprintf( "%.3f", $wallTime )
580 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
581 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
583 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
584 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
586 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
587 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
589 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
590 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
592 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
593 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
595 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
596 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
599 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
600 $this->mOutput
->setLimitReportData( $key, $value );
603 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
605 $limitReport = "NewPP limit report\n";
606 if ( $this->siteConfig
->get( 'ShowHostnames' ) ) {
607 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
609 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
610 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
611 $limitReport .= 'Dynamic content: ' .
612 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
615 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
616 if ( Hooks
::run( 'ParserLimitReportFormat',
617 [ $key, &$value, &$limitReport, false, false ]
619 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
620 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
621 ->inLanguage( 'en' )->useDatabase( false );
622 if ( !$valueMsg->exists() ) {
623 $valueMsg = new RawMessage( '$1' );
625 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
626 $valueMsg->params( $value );
627 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
631 // Since we're not really outputting HTML, decode the entities and
632 // then re-encode the things that need hiding inside HTML comments.
633 $limitReport = htmlspecialchars_decode( $limitReport );
635 // Sanitize for comment. Note '‐' in the replacement is U+2010,
636 // which looks much like the problematic '-'.
637 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
638 $text = "\n<!-- \n$limitReport-->\n";
640 // Add on template profiling data in human/machine readable way
641 $dataByFunc = $this->mProfiler
->getFunctionStats();
642 uasort( $dataByFunc, function ( $a, $b ) {
643 return $b['real'] <=> $a['real']; // descending order
646 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
647 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
648 $item['%real'], $item['real'], $item['calls'],
649 htmlspecialchars( $item['name'] ) );
651 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
652 $text .= implode( "\n", $profileReport ) . "\n-->\n";
654 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
656 // Add other cache related metadata
657 if ( $this->siteConfig
->get( 'ShowHostnames' ) ) {
658 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
660 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
661 $this->mOutput
->getCacheTime() );
662 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
663 $this->mOutput
->getCacheExpiry() );
664 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
665 $this->mOutput
->hasDynamicContent() );
667 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
668 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
669 $this->mTitle
->getPrefixedDBkey() );
675 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
676 * can be called from an extension tag hook.
678 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
679 * instead, which means that lists and links have not been fully parsed yet,
680 * and strip markers are still present.
682 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
684 * Use this function if you're a parser tag hook and you want to parse
685 * wikitext before or after applying additional transformations, and you
686 * intend to *return the result as hook output*, which will cause it to go
687 * through the rest of parsing process automatically.
689 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
690 * $text are not expanded
692 * @param string $text Text extension wants to have parsed
693 * @param-taint $text escapes_htmlnoent
694 * @param bool|PPFrame $frame The frame to use for expanding any template variables
695 * @return string UNSAFE half-parsed HTML
696 * @return-taint escaped
698 public function recursiveTagParse( $text, $frame = false ) {
699 // Avoid PHP 7.1 warning from passing $this by reference
701 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
702 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
703 $text = $this->internalParse( $text, false, $frame );
708 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
709 * point can be called from an extension tag hook.
711 * The output of this function is fully-parsed HTML that is safe for output.
712 * If you're a parser tag hook, you might want to use recursiveTagParse()
715 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
716 * $text are not expanded
720 * @param string $text Text extension wants to have parsed
721 * @param-taint $text escapes_htmlnoent
722 * @param bool|PPFrame $frame The frame to use for expanding any template variables
723 * @return string Fully parsed HTML
724 * @return-taint escaped
726 public function recursiveTagParseFully( $text, $frame = false ) {
727 $text = $this->recursiveTagParse( $text, $frame );
728 $text = $this->internalParseHalfParsed( $text, false );
733 * Expand templates and variables in the text, producing valid, static wikitext.
734 * Also removes comments.
735 * Do not call this function recursively.
736 * @param string $text
737 * @param Title|null $title
738 * @param ParserOptions $options
739 * @param int|null $revid
740 * @param bool|PPFrame $frame
741 * @return mixed|string
743 public function preprocess( $text, Title
$title = null,
744 ParserOptions
$options, $revid = null, $frame = false
746 $magicScopeVariable = $this->lock();
747 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
748 if ( $revid !== null ) {
749 $this->mRevisionId
= $revid;
751 // Avoid PHP 7.1 warning from passing $this by reference
753 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
754 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
755 $text = $this->replaceVariables( $text, $frame );
756 $text = $this->mStripState
->unstripBoth( $text );
761 * Recursive parser entry point that can be called from an extension tag
764 * @param string $text Text to be expanded
765 * @param bool|PPFrame $frame The frame to use for expanding any template variables
769 public function recursivePreprocess( $text, $frame = false ) {
770 $text = $this->replaceVariables( $text, $frame );
771 $text = $this->mStripState
->unstripBoth( $text );
776 * Process the wikitext for the "?preload=" feature. (T7210)
778 * "<noinclude>", "<includeonly>" etc. are parsed as for template
779 * transclusion, comments, templates, arguments, tags hooks and parser
780 * functions are untouched.
782 * @param string $text
783 * @param Title $title
784 * @param ParserOptions $options
785 * @param array $params
788 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
789 $msg = new RawMessage( $text );
790 $text = $msg->params( $params )->plain();
792 # Parser (re)initialisation
793 $magicScopeVariable = $this->lock();
794 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
796 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
797 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
798 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
799 $text = $this->mStripState
->unstripBoth( $text );
804 * Set the current user.
805 * Should only be used when doing pre-save transform.
807 * @param User|null $user User object or null (to reset)
809 public function setUser( $user ) {
810 $this->mUser
= $user;
814 * Set the context title
818 public function setTitle( $t ) {
820 $t = Title
::newFromText( 'NO TITLE' );
823 if ( $t->hasFragment() ) {
824 # Strip the fragment to avoid various odd effects
825 $this->mTitle
= $t->createFragmentTarget( '' );
832 * Accessor for the Title object
836 public function getTitle() {
837 return $this->mTitle
;
841 * Accessor/mutator for the Title object
843 * @param Title|null $x Title object or null to just get the current one
846 public function Title( $x = null ) {
847 return wfSetVar( $this->mTitle
, $x );
851 * Set the output type
853 * @param int $ot New value
855 public function setOutputType( $ot ) {
856 $this->mOutputType
= $ot;
859 'html' => $ot == self
::OT_HTML
,
860 'wiki' => $ot == self
::OT_WIKI
,
861 'pre' => $ot == self
::OT_PREPROCESS
,
862 'plain' => $ot == self
::OT_PLAIN
,
867 * Accessor/mutator for the output type
869 * @param int|null $x New value or null to just get the current one
872 public function OutputType( $x = null ) {
873 return wfSetVar( $this->mOutputType
, $x );
877 * Get the ParserOutput object
879 * @return ParserOutput
881 public function getOutput() {
882 return $this->mOutput
;
886 * Get the ParserOptions object
888 * @return ParserOptions
890 public function getOptions() {
891 return $this->mOptions
;
895 * Accessor/mutator for the ParserOptions object
897 * @param ParserOptions|null $x New value or null to just get the current one
898 * @return ParserOptions Current ParserOptions object
900 public function Options( $x = null ) {
901 return wfSetVar( $this->mOptions
, $x );
907 public function nextLinkID() {
908 return $this->mLinkID++
;
914 public function setLinkID( $id ) {
915 $this->mLinkID
= $id;
919 * Get a language object for use in parser functions such as {{FORMATNUM:}}
922 public function getFunctionLang() {
923 return $this->getTargetLanguage();
927 * Get the target language for the content being parsed. This is usually the
928 * language that the content is in.
932 * @throws MWException
935 public function getTargetLanguage() {
936 $target = $this->mOptions
->getTargetLanguage();
938 if ( $target !== null ) {
940 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
941 return $this->mOptions
->getUserLangObj();
942 } elseif ( is_null( $this->mTitle
) ) {
943 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
946 return $this->mTitle
->getPageLanguage();
950 * Get the language object for language conversion
951 * @deprecated since 1.32, just use getTargetLanguage()
952 * @return Language|null
954 public function getConverterLanguage() {
955 return $this->getTargetLanguage();
959 * Get a User object either from $this->mUser, if set, or from the
960 * ParserOptions object otherwise
964 public function getUser() {
965 if ( !is_null( $this->mUser
) ) {
968 return $this->mOptions
->getUser();
972 * Get a preprocessor object
974 * @return Preprocessor
976 public function getPreprocessor() {
977 if ( !isset( $this->mPreprocessor
) ) {
978 $class = $this->mPreprocessorClass
;
979 $this->mPreprocessor
= new $class( $this );
981 return $this->mPreprocessor
;
985 * Get a LinkRenderer instance to make links with
988 * @return LinkRenderer
990 public function getLinkRenderer() {
991 // XXX We make the LinkRenderer with current options and then cache it forever
992 if ( !$this->mLinkRenderer
) {
993 $this->mLinkRenderer
= $this->linkRendererFactory
->create();
994 $this->mLinkRenderer
->setStubThreshold(
995 $this->getOptions()->getStubThreshold()
999 return $this->mLinkRenderer
;
1003 * Get the MagicWordFactory that this Parser is using
1006 * @return MagicWordFactory
1008 public function getMagicWordFactory() {
1009 return $this->magicWordFactory
;
1013 * Get the content language that this Parser is using
1018 public function getContentLanguage() {
1019 return $this->contLang
;
1023 * Replaces all occurrences of HTML-style comments and the given tags
1024 * in the text with a random marker and returns the next text. The output
1025 * parameter $matches will be an associative array filled with data in
1032 * [ 'param' => 'x' ],
1033 * '<element param="x">tag content</element>' ]
1036 * @param array $elements List of element names. Comments are always extracted.
1037 * @param string $text Source text string.
1038 * @param array &$matches Out parameter, Array: extracted tags
1039 * @return string Stripped text
1041 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1046 $taglist = implode( '|', $elements );
1047 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
1049 while ( $text != '' ) {
1050 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1052 if ( count( $p ) < 5 ) {
1055 if ( count( $p ) > 5 ) {
1063 list( , $element, $attributes, $close, $inside ) = $p;
1066 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1067 $stripped .= $marker;
1069 if ( $close === '/>' ) {
1070 # Empty element tag, <tag />
1075 if ( $element === '!--' ) {
1078 $end = "/(<\\/$element\\s*>)/i";
1080 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1082 if ( count( $q ) < 3 ) {
1083 # No end tag -- let it run out to the end of the text.
1087 list( , $tail, $text ) = $q;
1091 $matches[$marker] = [ $element,
1093 Sanitizer
::decodeTagAttributes( $attributes ),
1094 "<$element$attributes$close$content$tail" ];
1100 * Get a list of strippable XML-like elements
1104 public function getStripList() {
1105 return $this->mStripList
;
1109 * Add an item to the strip state
1110 * Returns the unique tag which must be inserted into the stripped text
1111 * The tag will be replaced with the original text in unstrip()
1113 * @param string $text
1117 public function insertStripItem( $text ) {
1118 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1119 $this->mMarkerIndex++
;
1120 $this->mStripState
->addGeneral( $marker, $text );
1125 * parse the wiki syntax used to render tables
1128 * @param string $text
1131 public function doTableStuff( $text ) {
1132 $lines = StringUtils
::explode( "\n", $text );
1134 $td_history = []; # Is currently a td tag open?
1135 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1136 $tr_history = []; # Is currently a tr tag open?
1137 $tr_attributes = []; # history of tr attributes
1138 $has_opened_tr = []; # Did this table open a <tr> element?
1139 $indent_level = 0; # indent level of the table
1141 foreach ( $lines as $outLine ) {
1142 $line = trim( $outLine );
1144 if ( $line === '' ) { # empty line, go to next line
1145 $out .= $outLine . "\n";
1149 $first_character = $line[0];
1150 $first_two = substr( $line, 0, 2 );
1153 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1154 # First check if we are starting a new table
1155 $indent_level = strlen( $matches[1] );
1157 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1158 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1160 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1161 array_push( $td_history, false );
1162 array_push( $last_tag_history, '' );
1163 array_push( $tr_history, false );
1164 array_push( $tr_attributes, '' );
1165 array_push( $has_opened_tr, false );
1166 } elseif ( count( $td_history ) == 0 ) {
1167 # Don't do any of the following
1168 $out .= $outLine . "\n";
1170 } elseif ( $first_two === '|}' ) {
1171 # We are ending a table
1172 $line = '</table>' . substr( $line, 2 );
1173 $last_tag = array_pop( $last_tag_history );
1175 if ( !array_pop( $has_opened_tr ) ) {
1176 $line = "<tr><td></td></tr>{$line}";
1179 if ( array_pop( $tr_history ) ) {
1180 $line = "</tr>{$line}";
1183 if ( array_pop( $td_history ) ) {
1184 $line = "</{$last_tag}>{$line}";
1186 array_pop( $tr_attributes );
1187 if ( $indent_level > 0 ) {
1188 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1192 } elseif ( $first_two === '|-' ) {
1193 # Now we have a table row
1194 $line = preg_replace( '#^\|-+#', '', $line );
1196 # Whats after the tag is now only attributes
1197 $attributes = $this->mStripState
->unstripBoth( $line );
1198 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1199 array_pop( $tr_attributes );
1200 array_push( $tr_attributes, $attributes );
1203 $last_tag = array_pop( $last_tag_history );
1204 array_pop( $has_opened_tr );
1205 array_push( $has_opened_tr, true );
1207 if ( array_pop( $tr_history ) ) {
1211 if ( array_pop( $td_history ) ) {
1212 $line = "</{$last_tag}>{$line}";
1216 array_push( $tr_history, false );
1217 array_push( $td_history, false );
1218 array_push( $last_tag_history, '' );
1219 } elseif ( $first_character === '|'
1220 ||
$first_character === '!'
1221 ||
$first_two === '|+'
1223 # This might be cell elements, td, th or captions
1224 if ( $first_two === '|+' ) {
1225 $first_character = '+';
1226 $line = substr( $line, 2 );
1228 $line = substr( $line, 1 );
1231 // Implies both are valid for table headings.
1232 if ( $first_character === '!' ) {
1233 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1236 # Split up multiple cells on the same line.
1237 # FIXME : This can result in improper nesting of tags processed
1238 # by earlier parser steps.
1239 $cells = explode( '||', $line );
1243 # Loop through each table cell
1244 foreach ( $cells as $cell ) {
1246 if ( $first_character !== '+' ) {
1247 $tr_after = array_pop( $tr_attributes );
1248 if ( !array_pop( $tr_history ) ) {
1249 $previous = "<tr{$tr_after}>\n";
1251 array_push( $tr_history, true );
1252 array_push( $tr_attributes, '' );
1253 array_pop( $has_opened_tr );
1254 array_push( $has_opened_tr, true );
1257 $last_tag = array_pop( $last_tag_history );
1259 if ( array_pop( $td_history ) ) {
1260 $previous = "</{$last_tag}>\n{$previous}";
1263 if ( $first_character === '|' ) {
1265 } elseif ( $first_character === '!' ) {
1267 } elseif ( $first_character === '+' ) {
1268 $last_tag = 'caption';
1273 array_push( $last_tag_history, $last_tag );
1275 # A cell could contain both parameters and data
1276 $cell_data = explode( '|', $cell, 2 );
1278 # T2553: Note that a '|' inside an invalid link should not
1279 # be mistaken as delimiting cell parameters
1280 # Bug T153140: Neither should language converter markup.
1281 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1282 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1283 } elseif ( count( $cell_data ) == 1 ) {
1284 // Whitespace in cells is trimmed
1285 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1287 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1288 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1289 // Whitespace in cells is trimmed
1290 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1294 array_push( $td_history, true );
1297 $out .= $outLine . "\n";
1300 # Closing open td, tr && table
1301 while ( count( $td_history ) > 0 ) {
1302 if ( array_pop( $td_history ) ) {
1305 if ( array_pop( $tr_history ) ) {
1308 if ( !array_pop( $has_opened_tr ) ) {
1309 $out .= "<tr><td></td></tr>\n";
1312 $out .= "</table>\n";
1315 # Remove trailing line-ending (b/c)
1316 if ( substr( $out, -1 ) === "\n" ) {
1317 $out = substr( $out, 0, -1 );
1320 # special case: don't return empty table
1321 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1329 * Helper function for parse() that transforms wiki markup into half-parsed
1330 * HTML. Only called for $mOutputType == self::OT_HTML.
1334 * @param string $text The text to parse
1335 * @param-taint $text escapes_html
1336 * @param bool $isMain Whether this is being called from the main parse() function
1337 * @param PPFrame|bool $frame A pre-processor frame
1341 public function internalParse( $text, $isMain = true, $frame = false ) {
1344 // Avoid PHP 7.1 warning from passing $this by reference
1347 # Hook to suspend the parser in this state
1348 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1352 # if $frame is provided, then use $frame for replacing any variables
1354 # use frame depth to infer how include/noinclude tags should be handled
1355 # depth=0 means this is the top-level document; otherwise it's an included document
1356 if ( !$frame->depth
) {
1359 $flag = self
::PTD_FOR_INCLUSION
;
1361 $dom = $this->preprocessToDom( $text, $flag );
1362 $text = $frame->expand( $dom );
1364 # if $frame is not provided, then use old-style replaceVariables
1365 $text = $this->replaceVariables( $text );
1368 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1369 $text = Sanitizer
::removeHTMLtags(
1371 [ $this, 'attributeStripCallback' ],
1373 array_keys( $this->mTransparentTagHooks
),
1375 [ $this, 'addTrackingCategory' ]
1377 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1379 # Tables need to come after variable replacement for things to work
1380 # properly; putting them before other transformations should keep
1381 # exciting things like link expansions from showing up in surprising
1383 $text = $this->doTableStuff( $text );
1385 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1387 $text = $this->doDoubleUnderscore( $text );
1389 $text = $this->doHeadings( $text );
1390 $text = $this->replaceInternalLinks( $text );
1391 $text = $this->doAllQuotes( $text );
1392 $text = $this->replaceExternalLinks( $text );
1394 # replaceInternalLinks may sometimes leave behind
1395 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1396 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1398 $text = $this->doMagicLinks( $text );
1399 $text = $this->formatHeadings( $text, $origText, $isMain );
1405 * Helper function for parse() that transforms half-parsed HTML into fully
1408 * @param string $text
1409 * @param bool $isMain
1410 * @param bool $linestart
1413 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1414 $text = $this->mStripState
->unstripGeneral( $text );
1416 // Avoid PHP 7.1 warning from passing $this by reference
1420 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1423 # Clean up special characters, only run once, next-to-last before doBlockLevels
1424 $text = Sanitizer
::armorFrenchSpaces( $text );
1426 $text = $this->doBlockLevels( $text, $linestart );
1428 $this->replaceLinkHolders( $text );
1431 * The input doesn't get language converted if
1433 * b) Content isn't converted
1434 * c) It's a conversion table
1435 * d) it is an interface message (which is in the user language)
1437 if ( !( $this->mOptions
->getDisableContentConversion()
1438 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1439 && !$this->mOptions
->getInterfaceMessage()
1441 # The position of the convert() call should not be changed. it
1442 # assumes that the links are all replaced and the only thing left
1443 # is the <nowiki> mark.
1444 $text = $this->getTargetLanguage()->convert( $text );
1447 $text = $this->mStripState
->unstripNoWiki( $text );
1450 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1453 $text = $this->replaceTransparentTags( $text );
1454 $text = $this->mStripState
->unstripGeneral( $text );
1456 $text = Sanitizer
::normalizeCharReferences( $text );
1458 if ( MWTidy
::isEnabled() ) {
1459 if ( $this->mOptions
->getTidy() ) {
1460 $text = MWTidy
::tidy( $text );
1463 # attempt to sanitize at least some nesting problems
1464 # (T4702 and quite a few others)
1465 # This code path is buggy and deprecated!
1466 wfDeprecated( 'disabling tidy', '1.33' );
1468 # ''Something [http://www.cool.com cool''] -->
1469 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1470 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1471 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1472 # fix up an anchor inside another anchor, only
1473 # at least for a single single nested link (T5695)
1474 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1475 '\\1\\2</a>\\3</a>\\1\\4</a>',
1476 # fix div inside inline elements- doBlockLevels won't wrap a line which
1477 # contains a div, so fix it up here; replace
1478 # div with escaped text
1479 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1480 '\\1\\3<div\\5>\\6</div>\\8\\9',
1481 # remove empty italic or bold tag pairs, some
1482 # introduced by rules above
1483 '/<([bi])><\/\\1>/' => '',
1486 $text = preg_replace(
1487 array_keys( $tidyregs ),
1488 array_values( $tidyregs ),
1493 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1500 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1501 * magic external links.
1506 * @param string $text
1510 public function doMagicLinks( $text ) {
1511 $prots = wfUrlProtocolsWithoutProtRel();
1512 $urlChar = self
::EXT_LINK_URL_CLASS
;
1513 $addr = self
::EXT_LINK_ADDR
;
1514 $space = self
::SPACE_NOT_NL
; # non-newline space
1515 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1516 $spaces = "$space++"; # possessive match of 1 or more spaces
1517 $text = preg_replace_callback(
1519 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1520 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1521 (\b # m[3]: Free external links
1523 ($addr$urlChar*) # m[4]: Post-protocol path
1525 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1527 \bISBN $spaces ( # m[6]: ISBN, capture number
1528 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1529 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1530 [0-9Xx] # check digit
1532 )!xu", [ $this, 'magicLinkCallback' ], $text );
1537 * @throws MWException
1539 * @return string HTML
1541 public function magicLinkCallback( $m ) {
1542 if ( isset( $m[1] ) && $m[1] !== '' ) {
1545 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1548 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1549 # Free external link
1550 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1551 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1553 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1554 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1559 $cssClass = 'mw-magiclink-rfc';
1560 $trackingCat = 'magiclink-tracking-rfc';
1562 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1563 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1567 $urlmsg = 'pubmedurl';
1568 $cssClass = 'mw-magiclink-pmid';
1569 $trackingCat = 'magiclink-tracking-pmid';
1572 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1573 substr( $m[0], 0, 20 ) . '"' );
1575 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1576 $this->addTrackingCategory( $trackingCat );
1577 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1578 } elseif ( isset( $m[6] ) && $m[6] !== ''
1579 && $this->mOptions
->getMagicISBNLinks()
1583 $space = self
::SPACE_NOT_NL
; # non-newline space
1584 $isbn = preg_replace( "/$space/", ' ', $isbn );
1585 $num = strtr( $isbn, [
1590 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1591 return $this->getLinkRenderer()->makeKnownLink(
1592 SpecialPage
::getTitleFor( 'Booksources', $num ),
1595 'class' => 'internal mw-magiclink-isbn',
1596 'title' => false // suppress title attribute
1605 * Make a free external link, given a user-supplied URL
1607 * @param string $url
1608 * @param int $numPostProto
1609 * The number of characters after the protocol.
1610 * @return string HTML
1613 public function makeFreeExternalLink( $url, $numPostProto ) {
1616 # The characters '<' and '>' (which were escaped by
1617 # removeHTMLtags()) should not be included in
1618 # URLs, per RFC 2396.
1619 # Make terminate a URL as well (bug T84937)
1622 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1627 $trail = substr( $url, $m2[0][1] ) . $trail;
1628 $url = substr( $url, 0, $m2[0][1] );
1631 # Move trailing punctuation to $trail
1633 # If there is no left bracket, then consider right brackets fair game too
1634 if ( strpos( $url, '(' ) === false ) {
1638 $urlRev = strrev( $url );
1639 $numSepChars = strspn( $urlRev, $sep );
1640 # Don't break a trailing HTML entity by moving the ; into $trail
1641 # This is in hot code, so use substr_compare to avoid having to
1642 # create a new string object for the comparison
1643 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1644 # more optimization: instead of running preg_match with a $
1645 # anchor, which can be slow, do the match on the reversed
1646 # string starting at the desired offset.
1647 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1648 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1652 if ( $numSepChars ) {
1653 $trail = substr( $url, -$numSepChars ) . $trail;
1654 $url = substr( $url, 0, -$numSepChars );
1657 # Verify that we still have a real URL after trail removal, and
1658 # not just lone protocol
1659 if ( strlen( $trail ) >= $numPostProto ) {
1660 return $url . $trail;
1663 $url = Sanitizer
::cleanUrl( $url );
1665 # Is this an external image?
1666 $text = $this->maybeMakeExternalImage( $url );
1667 if ( $text === false ) {
1668 # Not an image, make a link
1669 $text = Linker
::makeExternalLink( $url,
1670 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1672 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1673 # Register it in the output object...
1674 $this->mOutput
->addExternalLink( $url );
1676 return $text . $trail;
1680 * Parse headers and return html
1684 * @param string $text
1688 public function doHeadings( $text ) {
1689 for ( $i = 6; $i >= 1; --$i ) {
1690 $h = str_repeat( '=', $i );
1691 // Trim non-newline whitespace from headings
1692 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1693 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1699 * Replace single quotes with HTML markup
1702 * @param string $text
1704 * @return string The altered text
1706 public function doAllQuotes( $text ) {
1708 $lines = StringUtils
::explode( "\n", $text );
1709 foreach ( $lines as $line ) {
1710 $outtext .= $this->doQuotes( $line ) . "\n";
1712 $outtext = substr( $outtext, 0, -1 );
1717 * Helper function for doAllQuotes()
1719 * @param string $text
1723 public function doQuotes( $text ) {
1724 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1725 $countarr = count( $arr );
1726 if ( $countarr == 1 ) {
1730 // First, do some preliminary work. This may shift some apostrophes from
1731 // being mark-up to being text. It also counts the number of occurrences
1732 // of bold and italics mark-ups.
1735 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1736 $thislen = strlen( $arr[$i] );
1737 // If there are ever four apostrophes, assume the first is supposed to
1738 // be text, and the remaining three constitute mark-up for bold text.
1739 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1740 if ( $thislen == 4 ) {
1741 $arr[$i - 1] .= "'";
1744 } elseif ( $thislen > 5 ) {
1745 // If there are more than 5 apostrophes in a row, assume they're all
1746 // text except for the last 5.
1747 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1748 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1752 // Count the number of occurrences of bold and italics mark-ups.
1753 if ( $thislen == 2 ) {
1755 } elseif ( $thislen == 3 ) {
1757 } elseif ( $thislen == 5 ) {
1763 // If there is an odd number of both bold and italics, it is likely
1764 // that one of the bold ones was meant to be an apostrophe followed
1765 // by italics. Which one we cannot know for certain, but it is more
1766 // likely to be one that has a single-letter word before it.
1767 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1768 $firstsingleletterword = -1;
1769 $firstmultiletterword = -1;
1771 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1772 if ( strlen( $arr[$i] ) == 3 ) {
1773 $x1 = substr( $arr[$i - 1], -1 );
1774 $x2 = substr( $arr[$i - 1], -2, 1 );
1775 if ( $x1 === ' ' ) {
1776 if ( $firstspace == -1 ) {
1779 } elseif ( $x2 === ' ' ) {
1780 $firstsingleletterword = $i;
1781 // if $firstsingleletterword is set, we don't
1782 // look at the other options, so we can bail early.
1784 } elseif ( $firstmultiletterword == -1 ) {
1785 $firstmultiletterword = $i;
1790 // If there is a single-letter word, use it!
1791 if ( $firstsingleletterword > -1 ) {
1792 $arr[$firstsingleletterword] = "''";
1793 $arr[$firstsingleletterword - 1] .= "'";
1794 } elseif ( $firstmultiletterword > -1 ) {
1795 // If not, but there's a multi-letter word, use that one.
1796 $arr[$firstmultiletterword] = "''";
1797 $arr[$firstmultiletterword - 1] .= "'";
1798 } elseif ( $firstspace > -1 ) {
1799 // ... otherwise use the first one that has neither.
1800 // (notice that it is possible for all three to be -1 if, for example,
1801 // there is only one pentuple-apostrophe in the line)
1802 $arr[$firstspace] = "''";
1803 $arr[$firstspace - 1] .= "'";
1807 // Now let's actually convert our apostrophic mush to HTML!
1812 foreach ( $arr as $r ) {
1813 if ( ( $i %
2 ) == 0 ) {
1814 if ( $state === 'both' ) {
1820 $thislen = strlen( $r );
1821 if ( $thislen == 2 ) {
1822 if ( $state === 'i' ) {
1825 } elseif ( $state === 'bi' ) {
1828 } elseif ( $state === 'ib' ) {
1829 $output .= '</b></i><b>';
1831 } elseif ( $state === 'both' ) {
1832 $output .= '<b><i>' . $buffer . '</i>';
1834 } else { // $state can be 'b' or ''
1838 } elseif ( $thislen == 3 ) {
1839 if ( $state === 'b' ) {
1842 } elseif ( $state === 'bi' ) {
1843 $output .= '</i></b><i>';
1845 } elseif ( $state === 'ib' ) {
1848 } elseif ( $state === 'both' ) {
1849 $output .= '<i><b>' . $buffer . '</b>';
1851 } else { // $state can be 'i' or ''
1855 } elseif ( $thislen == 5 ) {
1856 if ( $state === 'b' ) {
1857 $output .= '</b><i>';
1859 } elseif ( $state === 'i' ) {
1860 $output .= '</i><b>';
1862 } elseif ( $state === 'bi' ) {
1863 $output .= '</i></b>';
1865 } elseif ( $state === 'ib' ) {
1866 $output .= '</b></i>';
1868 } elseif ( $state === 'both' ) {
1869 $output .= '<i><b>' . $buffer . '</b></i>';
1871 } else { // ($state == '')
1879 // Now close all remaining tags. Notice that the order is important.
1880 if ( $state === 'b' ||
$state === 'ib' ) {
1883 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1886 if ( $state === 'bi' ) {
1889 // There might be lonely ''''', so make sure we have a buffer
1890 if ( $state === 'both' && $buffer ) {
1891 $output .= '<b><i>' . $buffer . '</i></b>';
1897 * Replace external links (REL)
1899 * Note: this is all very hackish and the order of execution matters a lot.
1900 * Make sure to run tests/parser/parserTests.php if you change this code.
1904 * @param string $text
1906 * @throws MWException
1909 public function replaceExternalLinks( $text ) {
1910 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1911 if ( $bits === false ) {
1912 throw new MWException( "PCRE needs to be compiled with "
1913 . "--enable-unicode-properties in order for MediaWiki to function" );
1915 $s = array_shift( $bits );
1918 while ( $i < count( $bits ) ) {
1921 $text = $bits[$i++
];
1922 $trail = $bits[$i++
];
1924 # The characters '<' and '>' (which were escaped by
1925 # removeHTMLtags()) should not be included in
1926 # URLs, per RFC 2396.
1928 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1929 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1930 $url = substr( $url, 0, $m2[0][1] );
1933 # If the link text is an image URL, replace it with an <img> tag
1934 # This happened by accident in the original parser, but some people used it extensively
1935 $img = $this->maybeMakeExternalImage( $text );
1936 if ( $img !== false ) {
1942 # Set linktype for CSS
1945 # No link text, e.g. [http://domain.tld/some.link]
1946 if ( $text == '' ) {
1948 $langObj = $this->getTargetLanguage();
1949 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1950 $linktype = 'autonumber';
1952 # Have link text, e.g. [http://domain.tld/some.link text]s
1954 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1957 // Excluding protocol-relative URLs may avoid many false positives.
1958 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1959 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1962 $url = Sanitizer
::cleanUrl( $url );
1964 # Use the encoded URL
1965 # This means that users can paste URLs directly into the text
1966 # Funny characters like ö aren't valid in URLs anyway
1967 # This was changed in August 2004
1968 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1969 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1971 # Register link in the output object.
1972 $this->mOutput
->addExternalLink( $url );
1979 * Get the rel attribute for a particular external link.
1982 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1983 * nofollow if appropriate
1984 * @param LinkTarget|null $title Optional LinkTarget, for wgNoFollowNsExceptions lookups
1985 * @return string|null Rel attribute for $url
1987 public static function getExternalLinkRel( $url = false, $title = null ) {
1988 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1989 $ns = $title ?
$title->getNamespace() : false;
1990 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1991 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1999 * Get an associative array of additional HTML attributes appropriate for a
2000 * particular external link. This currently may include rel => nofollow
2001 * (depending on configuration, namespace, and the URL's domain) and/or a
2002 * target attribute (depending on configuration).
2004 * @param string $url URL to extract the domain from for rel =>
2005 * nofollow if appropriate
2006 * @return array Associative array of HTML attributes
2008 public function getExternalLinkAttribs( $url ) {
2010 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
2012 $target = $this->mOptions
->getExternalLinkTarget();
2014 $attribs['target'] = $target;
2015 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
2016 // T133507. New windows can navigate parent cross-origin.
2017 // Including noreferrer due to lacking browser
2018 // support of noopener. Eventually noreferrer should be removed.
2019 if ( $rel !== '' ) {
2022 $rel .= 'noreferrer noopener';
2025 $attribs['rel'] = $rel;
2030 * Replace unusual escape codes in a URL with their equivalent characters
2032 * This generally follows the syntax defined in RFC 3986, with special
2033 * consideration for HTTP query strings.
2035 * @param string $url
2038 public static function normalizeLinkUrl( $url ) {
2039 # Test for RFC 3986 IPv6 syntax
2040 $scheme = '[a-z][a-z0-9+.-]*:';
2041 $userinfo = '(?:[a-z0-9\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*';
2042 $ipv6Host = '\\[((?:[0-9a-f:]|%3[0-A]|%[46][1-6])+)\\]';
2043 if ( preg_match( "<^(?:{$scheme})?//(?:{$userinfo}@)?{$ipv6Host}(?:[:/?#].*|)$>i", $url, $m ) &&
2044 IP
::isValid( rawurldecode( $m[1] ) )
2046 $isIPv6 = rawurldecode( $m[1] );
2051 # Make sure unsafe characters are encoded
2052 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2054 return rawurlencode( $m[0] );
2060 $end = strlen( $url );
2062 # Fragment part - 'fragment'
2063 $start = strpos( $url, '#' );
2064 if ( $start !== false && $start < $end ) {
2065 $ret = self
::normalizeUrlComponent(
2066 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2070 # Query part - 'query' minus &=+;
2071 $start = strpos( $url, '?' );
2072 if ( $start !== false && $start < $end ) {
2073 $ret = self
::normalizeUrlComponent(
2074 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2078 # Scheme and path part - 'pchar'
2079 # (we assume no userinfo or encoded colons in the host)
2080 $ret = self
::normalizeUrlComponent(
2081 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2084 if ( $isIPv6 !== false ) {
2085 $ipv6Host = "%5B({$isIPv6})%5D";
2086 $ret = preg_replace(
2087 "<^((?:{$scheme})?//(?:{$userinfo}@)?){$ipv6Host}(?=[:/?#]|$)>i",
2096 private static function normalizeUrlComponent( $component, $unsafe ) {
2097 $callback = function ( $matches ) use ( $unsafe ) {
2098 $char = urldecode( $matches[0] );
2099 $ord = ord( $char );
2100 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2104 # Leave it escaped, but use uppercase for a-f
2105 return strtoupper( $matches[0] );
2108 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2112 * make an image if it's allowed, either through the global
2113 * option, through the exception, or through the on-wiki whitelist
2115 * @param string $url
2119 private function maybeMakeExternalImage( $url ) {
2120 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2121 $imagesexception = !empty( $imagesfrom );
2123 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2124 if ( $imagesexception && is_array( $imagesfrom ) ) {
2125 $imagematch = false;
2126 foreach ( $imagesfrom as $match ) {
2127 if ( strpos( $url, $match ) === 0 ) {
2132 } elseif ( $imagesexception ) {
2133 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2135 $imagematch = false;
2138 if ( $this->mOptions
->getAllowExternalImages()
2139 ||
( $imagesexception && $imagematch )
2141 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2143 $text = Linker
::makeExternalImage( $url );
2146 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2147 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2149 $whitelist = explode(
2151 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2154 foreach ( $whitelist as $entry ) {
2155 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2156 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2159 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2160 # Image matches a whitelist entry
2161 $text = Linker
::makeExternalImage( $url );
2170 * Process [[ ]] wikilinks
2174 * @return string Processed text
2178 public function replaceInternalLinks( $s ) {
2179 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2184 * Process [[ ]] wikilinks (RIL)
2186 * @throws MWException
2187 * @return LinkHolderArray
2191 public function replaceInternalLinks2( &$s ) {
2192 static $tc = false, $e1, $e1_img;
2193 # the % is needed to support urlencoded titles as well
2195 $tc = Title
::legalChars() . '#%';
2196 # Match a link having the form [[namespace:link|alternate]]trail
2197 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2198 # Match cases where there is no "]]", which might still be images
2199 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2202 $holders = new LinkHolderArray( $this );
2204 # split the entire text string on occurrences of [[
2205 $a = StringUtils
::explode( '[[', ' ' . $s );
2206 # get the first element (all text up to first [[), and remove the space we added
2209 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2210 $s = substr( $s, 1 );
2212 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2214 if ( $useLinkPrefixExtension ) {
2215 # Match the end of a line for a word that's not followed by whitespace,
2216 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2217 $charset = $this->contLang
->linkPrefixCharset();
2218 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2221 if ( is_null( $this->mTitle
) ) {
2222 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2224 $nottalk = !$this->mTitle
->isTalkPage();
2226 if ( $useLinkPrefixExtension ) {
2228 if ( preg_match( $e2, $s, $m ) ) {
2229 $first_prefix = $m[2];
2231 $first_prefix = false;
2237 $useSubpages = $this->areSubpagesAllowed();
2239 # Loop for each link
2240 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2241 # Check for excessive memory usage
2242 if ( $holders->isBig() ) {
2244 # Do the existence check, replace the link holders and clear the array
2245 $holders->replace( $s );
2249 if ( $useLinkPrefixExtension ) {
2250 if ( preg_match( $e2, $s, $m ) ) {
2251 list( , $s, $prefix ) = $m;
2256 if ( $first_prefix ) {
2257 $prefix = $first_prefix;
2258 $first_prefix = false;
2262 $might_be_img = false;
2264 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2266 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2267 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2268 # the real problem is with the $e1 regex
2270 # Still some problems for cases where the ] is meant to be outside punctuation,
2271 # and no image is in sight. See T4095.
2273 && substr( $m[3], 0, 1 ) === ']'
2274 && strpos( $text, '[' ) !== false
2276 $text .= ']'; # so that replaceExternalLinks($text) works later
2277 $m[3] = substr( $m[3], 1 );
2279 # fix up urlencoded title texts
2280 if ( strpos( $m[1], '%' ) !== false ) {
2281 # Should anchors '#' also be rejected?
2282 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2285 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2286 # Invalid, but might be an image with a link in its caption
2287 $might_be_img = true;
2289 if ( strpos( $m[1], '%' ) !== false ) {
2290 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2293 } else { # Invalid form; output directly
2294 $s .= $prefix . '[[' . $line;
2298 $origLink = ltrim( $m[1], ' ' );
2300 # Don't allow internal links to pages containing
2301 # PROTO: where PROTO is a valid URL protocol; these
2302 # should be external links.
2303 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2304 $s .= $prefix . '[[' . $line;
2308 # Make subpage if necessary
2309 if ( $useSubpages ) {
2310 $link = $this->maybeDoSubpageLink( $origLink, $text );
2315 // \x7f isn't a default legal title char, so most likely strip
2316 // markers will force us into the "invalid form" path above. But,
2317 // just in case, let's assert that xmlish tags aren't valid in
2318 // the title position.
2319 $unstrip = $this->mStripState
->killMarkers( $link );
2320 $noMarkers = ( $unstrip === $link );
2322 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2323 if ( $nt === null ) {
2324 $s .= $prefix . '[[' . $line;
2328 $ns = $nt->getNamespace();
2329 $iw = $nt->getInterwiki();
2331 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2333 if ( $might_be_img ) { # if this is actually an invalid link
2334 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2337 # look at the next 'line' to see if we can close it there
2339 $next_line = $a->current();
2340 if ( $next_line === false ||
$next_line === null ) {
2343 $m = explode( ']]', $next_line, 3 );
2344 if ( count( $m ) == 3 ) {
2345 # the first ]] closes the inner link, the second the image
2347 $text .= "[[{$m[0]}]]{$m[1]}";
2350 } elseif ( count( $m ) == 2 ) {
2351 # if there's exactly one ]] that's fine, we'll keep looking
2352 $text .= "[[{$m[0]}]]{$m[1]}";
2354 # if $next_line is invalid too, we need look no further
2355 $text .= '[[' . $next_line;
2360 # we couldn't find the end of this imageLink, so output it raw
2361 # but don't ignore what might be perfectly normal links in the text we've examined
2362 $holders->merge( $this->replaceInternalLinks2( $text ) );
2363 $s .= "{$prefix}[[$link|$text";
2364 # note: no $trail, because without an end, there *is* no trail
2367 } else { # it's not an image, so output it raw
2368 $s .= "{$prefix}[[$link|$text";
2369 # note: no $trail, because without an end, there *is* no trail
2374 $wasblank = ( $text == '' );
2378 # Strip off leading ':'
2379 $text = substr( $text, 1 );
2382 # T6598 madness. Handle the quotes only if they come from the alternate part
2383 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2384 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2385 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2386 $text = $this->doQuotes( $text );
2389 # Link not escaped by : , create the various objects
2390 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2393 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2394 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2395 in_array( $iw, $this->siteConfig
->get( 'ExtraInterlanguageLinkPrefixes' ) )
2398 # T26502: filter duplicates
2399 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2400 $this->mLangLinkLanguages
[$iw] = true;
2401 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2405 * Strip the whitespace interwiki links produce, see T10897
2407 $s = rtrim( $s . $prefix ) . $trail; # T175416
2411 if ( $ns == NS_FILE
) {
2412 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2414 # if no parameters were passed, $text
2415 # becomes something like "File:Foo.png",
2416 # which we don't want to pass on to the
2420 # recursively parse links inside the image caption
2421 # actually, this will parse them in any other parameters, too,
2422 # but it might be hard to fix that, and it doesn't matter ATM
2423 $text = $this->replaceExternalLinks( $text );
2424 $holders->merge( $this->replaceInternalLinks2( $text ) );
2426 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2427 $s .= $prefix . $this->armorLinks(
2428 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2431 } elseif ( $ns == NS_CATEGORY
) {
2433 * Strip the whitespace Category links produce, see T2087
2435 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2438 $sortkey = $this->getDefaultSort();
2442 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2443 $sortkey = str_replace( "\n", '', $sortkey );
2444 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2445 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2451 # Self-link checking. For some languages, variants of the title are checked in
2452 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2453 # for linking to a different variant.
2454 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2455 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2459 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2460 # @todo FIXME: Should do batch file existence checks, see comment below
2461 if ( $ns == NS_MEDIA
) {
2462 # Give extensions a chance to select the file revision for us
2465 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2466 [ $this, $nt, &$options, &$descQuery ] );
2467 # Fetch and register the file (file title may be different via hooks)
2468 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2469 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2470 $s .= $prefix . $this->armorLinks(
2471 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2475 # Some titles, such as valid special pages or files in foreign repos, should
2476 # be shown as bluelinks even though they're not included in the page table
2477 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2478 # batch file existence checks for NS_FILE and NS_MEDIA
2479 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2480 $this->mOutput
->addLink( $nt );
2481 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2483 # Links will be added to the output link list after checking
2484 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2491 * Render a forced-blue link inline; protect against double expansion of
2492 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2493 * Since this little disaster has to split off the trail text to avoid
2494 * breaking URLs in the following text without breaking trails on the
2495 * wiki links, it's been made into a horrible function.
2498 * @param string $text
2499 * @param string $trail
2500 * @param string $prefix
2501 * @return string HTML-wikitext mix oh yuck
2503 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2504 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2506 if ( $text == '' ) {
2507 $text = htmlspecialchars( $nt->getPrefixedText() );
2510 $link = $this->getLinkRenderer()->makeKnownLink(
2511 $nt, new HtmlArmor( "$prefix$text$inside" )
2514 return $this->armorLinks( $link ) . $trail;
2518 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2519 * going to go through further parsing steps before inline URL expansion.
2521 * Not needed quite as much as it used to be since free links are a bit
2522 * more sensible these days. But bracketed links are still an issue.
2524 * @param string $text More-or-less HTML
2525 * @return string Less-or-more HTML with NOPARSE bits
2527 public function armorLinks( $text ) {
2528 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2529 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2533 * Return true if subpage links should be expanded on this page.
2536 public function areSubpagesAllowed() {
2537 # Some namespaces don't allow subpages
2538 return $this->nsInfo
->hasSubpages( $this->mTitle
->getNamespace() );
2542 * Handle link to subpage if necessary
2544 * @param string $target The source of the link
2545 * @param string &$text The link text, modified as necessary
2546 * @return string The full name of the link
2549 public function maybeDoSubpageLink( $target, &$text ) {
2550 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2554 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2556 * @param string $text
2557 * @param bool $linestart Whether or not this is at the start of a line.
2559 * @return string The lists rendered as HTML
2561 public function doBlockLevels( $text, $linestart ) {
2562 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2566 * Return value of a magic variable (like PAGENAME)
2570 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2571 * @param bool|PPFrame $frame
2573 * @throws MWException
2576 public function getVariableValue( $index, $frame = false ) {
2577 if ( is_null( $this->mTitle
) ) {
2578 // If no title set, bad things are going to happen
2579 // later. Title should always be set since this
2580 // should only be called in the middle of a parse
2581 // operation (but the unit-tests do funky stuff)
2582 throw new MWException( __METHOD__
. ' Should only be '
2583 . ' called while parsing (no title set)' );
2586 // Avoid PHP 7.1 warning from passing $this by reference
2590 * Some of these require message or data lookups and can be
2591 * expensive to check many times.
2594 Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) &&
2595 isset( $this->mVarCache
[$index] )
2597 return $this->mVarCache
[$index];
2600 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2601 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2603 $pageLang = $this->getFunctionLang();
2609 case 'currentmonth':
2610 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2612 case 'currentmonth1':
2613 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2615 case 'currentmonthname':
2616 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2618 case 'currentmonthnamegen':
2619 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2621 case 'currentmonthabbrev':
2622 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2625 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2628 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2631 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2634 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2636 case 'localmonthname':
2637 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2639 case 'localmonthnamegen':
2640 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2642 case 'localmonthabbrev':
2643 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2646 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2649 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2652 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2655 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2657 case 'fullpagename':
2658 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2660 case 'fullpagenamee':
2661 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2664 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2666 case 'subpagenamee':
2667 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2669 case 'rootpagename':
2670 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2672 case 'rootpagenamee':
2673 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2676 $this->mTitle
->getRootText()
2679 case 'basepagename':
2680 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2682 case 'basepagenamee':
2683 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2686 $this->mTitle
->getBaseText()
2689 case 'talkpagename':
2690 if ( $this->mTitle
->canHaveTalkPage() ) {
2691 $talkPage = $this->mTitle
->getTalkPage();
2692 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2697 case 'talkpagenamee':
2698 if ( $this->mTitle
->canHaveTalkPage() ) {
2699 $talkPage = $this->mTitle
->getTalkPage();
2700 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2705 case 'subjectpagename':
2706 $subjPage = $this->mTitle
->getSubjectPage();
2707 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2709 case 'subjectpagenamee':
2710 $subjPage = $this->mTitle
->getSubjectPage();
2711 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2713 case 'pageid': // requested in T25427
2714 $pageid = $this->getTitle()->getArticleID();
2715 if ( $pageid == 0 ) {
2716 # 0 means the page doesn't exist in the database,
2717 # which means the user is previewing a new page.
2718 # The vary-revision flag must be set, because the magic word
2719 # will have a different value once the page is saved.
2720 $this->mOutput
->setFlag( 'vary-revision' );
2721 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2723 $value = $pageid ?
: null;
2727 $this->siteConfig
->get( 'MiserMode' ) &&
2728 !$this->mOptions
->getInterfaceMessage() &&
2729 // @TODO: disallow this word on all namespaces
2730 $this->nsInfo
->isContent( $this->mTitle
->getNamespace() )
2732 // Use a stub result instead of the actual revision ID in order to avoid
2733 // double parses on page save but still allow preview detection (T137900)
2734 if ( $this->getRevisionId() ||
$this->mOptions
->getSpeculativeRevId() ) {
2737 $this->mOutput
->setFlag( 'vary-revision-exists' );
2741 # Inform the edit saving system that getting the canonical output after
2742 # revision insertion requires another parse using the actual revision ID
2743 $this->mOutput
->setFlag( 'vary-revision-id' );
2744 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2745 $value = $this->getRevisionId();
2746 if ( $value === 0 ) {
2747 $rev = $this->getRevisionObject();
2748 $value = $rev ?
$rev->getId() : $value;
2751 $value = $this->mOptions
->getSpeculativeRevId();
2753 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2759 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2761 case 'revisionday2':
2762 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2764 case 'revisionmonth':
2765 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2767 case 'revisionmonth1':
2768 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2770 case 'revisionyear':
2771 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2773 case 'revisiontimestamp':
2774 # Let the edit saving system know we should parse the page
2775 # *after* a revision ID has been assigned. This is for null edits.
2776 $this->mOutput
->setFlag( 'vary-revision' );
2777 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2778 $value = $this->getRevisionTimestamp();
2780 case 'revisionuser':
2781 # Let the edit saving system know we should parse the page
2782 # *after* a revision ID has been assigned for null edits.
2783 $this->mOutput
->setFlag( 'vary-user' );
2784 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2785 $value = $this->getRevisionUser();
2787 case 'revisionsize':
2788 $value = $this->getRevisionSize();
2791 $value = str_replace( '_', ' ',
2792 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2795 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2797 case 'namespacenumber':
2798 $value = $this->mTitle
->getNamespace();
2801 $value = $this->mTitle
->canHaveTalkPage()
2802 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2806 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2808 case 'subjectspace':
2809 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2811 case 'subjectspacee':
2812 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2814 case 'currentdayname':
2815 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2818 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2821 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2824 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2827 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2828 # int to remove the padding
2829 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2832 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2834 case 'localdayname':
2835 $value = $pageLang->getWeekdayName(
2836 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2840 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2843 $value = $pageLang->time(
2844 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2850 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2853 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2854 # int to remove the padding
2855 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2858 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2860 case 'numberofarticles':
2861 $value = $pageLang->formatNum( SiteStats
::articles() );
2863 case 'numberoffiles':
2864 $value = $pageLang->formatNum( SiteStats
::images() );
2866 case 'numberofusers':
2867 $value = $pageLang->formatNum( SiteStats
::users() );
2869 case 'numberofactiveusers':
2870 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2872 case 'numberofpages':
2873 $value = $pageLang->formatNum( SiteStats
::pages() );
2875 case 'numberofadmins':
2876 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2878 case 'numberofedits':
2879 $value = $pageLang->formatNum( SiteStats
::edits() );
2881 case 'currenttimestamp':
2882 $value = wfTimestamp( TS_MW
, $ts );
2884 case 'localtimestamp':
2885 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2887 case 'currentversion':
2888 $value = SpecialVersion
::getVersion();
2891 return $this->siteConfig
->get( 'ArticlePath' );
2893 return $this->siteConfig
->get( 'Sitename' );
2895 return $this->siteConfig
->get( 'Server' );
2897 return $this->siteConfig
->get( 'ServerName' );
2899 return $this->siteConfig
->get( 'ScriptPath' );
2901 return $this->siteConfig
->get( 'StylePath' );
2902 case 'directionmark':
2903 return $pageLang->getDirMark();
2904 case 'contentlanguage':
2905 return $this->siteConfig
->get( 'LanguageCode' );
2906 case 'pagelanguage':
2907 $value = $pageLang->getCode();
2909 case 'cascadingsources':
2910 $value = CoreParserFunctions
::cascadingsources( $this );
2915 'ParserGetVariableValueSwitch',
2916 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2923 $this->mVarCache
[$index] = $value;
2932 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2933 * @param string $variable Parser variable name
2936 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2937 # Get the timezone-adjusted timestamp to be used for this revision
2938 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2939 # Possibly set vary-revision if there is not yet an associated revision
2940 if ( !$this->getRevisionObject() ) {
2941 # Get the timezone-adjusted timestamp $mtts seconds in the future
2943 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2948 if ( $resNow !== $resThen ) {
2949 # Let the edit saving system know we should parse the page
2950 # *after* a revision ID has been assigned. This is for null edits.
2951 $this->mOutput
->setFlag( 'vary-revision' );
2952 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2960 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2964 public function initialiseVariables() {
2965 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2966 $substIDs = $this->magicWordFactory
->getSubstIDs();
2968 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2969 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2973 * Preprocess some wikitext and return the document tree.
2974 * This is the ghost of replace_variables().
2976 * @param string $text The text to parse
2977 * @param int $flags Bitwise combination of:
2978 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2979 * included. Default is to assume a direct page view.
2981 * The generated DOM tree must depend only on the input text and the flags.
2982 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2984 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2985 * change in the DOM tree for a given text, must be passed through the section identifier
2986 * in the section edit link and thus back to extractSections().
2988 * The output of this function is currently only cached in process memory, but a persistent
2989 * cache may be implemented at a later date which takes further advantage of these strict
2990 * dependency requirements.
2994 public function preprocessToDom( $text, $flags = 0 ) {
2995 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3000 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3006 public static function splitWhitespace( $s ) {
3007 $ltrimmed = ltrim( $s );
3008 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3009 $trimmed = rtrim( $ltrimmed );
3010 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3012 $w2 = substr( $ltrimmed, -$diff );
3016 return [ $w1, $trimmed, $w2 ];
3020 * Replace magic variables, templates, and template arguments
3021 * with the appropriate text. Templates are substituted recursively,
3022 * taking care to avoid infinite loops.
3024 * Note that the substitution depends on value of $mOutputType:
3025 * self::OT_WIKI: only {{subst:}} templates
3026 * self::OT_PREPROCESS: templates but not extension tags
3027 * self::OT_HTML: all templates and extension tags
3029 * @param string $text The text to transform
3030 * @param bool|PPFrame $frame Object describing the arguments passed to the
3031 * template. Arguments may also be provided as an associative array, as
3032 * was the usual case before MW1.12. Providing arguments this way may be
3033 * useful for extensions wishing to perform variable replacement
3035 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3036 * double-brace expansion.
3039 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3040 # Is there any text? Also, Prevent too big inclusions!
3041 $textSize = strlen( $text );
3042 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3046 if ( $frame === false ) {
3047 $frame = $this->getPreprocessor()->newFrame();
3048 } elseif ( !( $frame instanceof PPFrame
) ) {
3049 wfDebug( __METHOD__
. " called using plain parameters instead of "
3050 . "a PPFrame instance. Creating custom frame.\n" );
3051 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3054 $dom = $this->preprocessToDom( $text );
3055 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3056 $text = $frame->expand( $dom, $flags );
3062 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3064 * @param array $args
3068 public static function createAssocArgs( $args ) {
3071 foreach ( $args as $arg ) {
3072 $eqpos = strpos( $arg, '=' );
3073 if ( $eqpos === false ) {
3074 $assocArgs[$index++
] = $arg;
3076 $name = trim( substr( $arg, 0, $eqpos ) );
3077 $value = trim( substr( $arg, $eqpos +
1 ) );
3078 if ( $value === false ) {
3081 if ( $name !== false ) {
3082 $assocArgs[$name] = $value;
3091 * Warn the user when a parser limitation is reached
3092 * Will warn at most once the user per limitation type
3094 * The results are shown during preview and run through the Parser (See EditPage.php)
3096 * @param string $limitationType Should be one of:
3097 * 'expensive-parserfunction' (corresponding messages:
3098 * 'expensive-parserfunction-warning',
3099 * 'expensive-parserfunction-category')
3100 * 'post-expand-template-argument' (corresponding messages:
3101 * 'post-expand-template-argument-warning',
3102 * 'post-expand-template-argument-category')
3103 * 'post-expand-template-inclusion' (corresponding messages:
3104 * 'post-expand-template-inclusion-warning',
3105 * 'post-expand-template-inclusion-category')
3106 * 'node-count-exceeded' (corresponding messages:
3107 * 'node-count-exceeded-warning',
3108 * 'node-count-exceeded-category')
3109 * 'expansion-depth-exceeded' (corresponding messages:
3110 * 'expansion-depth-exceeded-warning',
3111 * 'expansion-depth-exceeded-category')
3112 * @param string|int|null $current Current value
3113 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3114 * exceeded, provide the values (optional)
3116 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3117 # does no harm if $current and $max are present but are unnecessary for the message
3118 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3119 # only during preview, and that would split the parser cache unnecessarily.
3120 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3122 $this->mOutput
->addWarning( $warning );
3123 $this->addTrackingCategory( "$limitationType-category" );
3127 * Return the text of a template, after recursively
3128 * replacing any variables or templates within the template.
3130 * @param array $piece The parts of the template
3131 * $piece['title']: the title, i.e. the part before the |
3132 * $piece['parts']: the parameter array
3133 * $piece['lineStart']: whether the brace was at the start of a line
3134 * @param PPFrame $frame The current frame, contains template arguments
3136 * @return string The text of the template
3138 public function braceSubstitution( $piece, $frame ) {
3141 // $text has been filled
3143 // wiki markup in $text should be escaped
3145 // $text is HTML, armour it against wikitext transformation
3147 // Force interwiki transclusion to be done in raw mode not rendered
3148 $forceRawInterwiki = false;
3149 // $text is a DOM node needing expansion in a child frame
3150 $isChildObj = false;
3151 // $text is a DOM node needing expansion in the current frame
3152 $isLocalObj = false;
3154 # Title object, where $text came from
3157 # $part1 is the bit before the first |, and must contain only title characters.
3158 # Various prefixes will be stripped from it later.
3159 $titleWithSpaces = $frame->expand( $piece['title'] );
3160 $part1 = trim( $titleWithSpaces );
3163 # Original title text preserved for various purposes
3164 $originalTitle = $part1;
3166 # $args is a list of argument nodes, starting from index 0, not including $part1
3167 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3168 # below won't work b/c this $args isn't an object
3169 $args = ( $piece['parts'] == null ) ?
[] : $piece['parts'];
3171 $profileSection = null; // profile templates
3175 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3177 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3178 # Decide whether to expand template or keep wikitext as-is.
3179 if ( $this->ot
['wiki'] ) {
3180 if ( $substMatch === false ) {
3181 $literal = true; # literal when in PST with no prefix
3183 $literal = false; # expand when in PST with subst: or safesubst:
3186 if ( $substMatch == 'subst' ) {
3187 $literal = true; # literal when not in PST with plain subst:
3189 $literal = false; # expand when not in PST with safesubst: or no prefix
3193 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3200 if ( !$found && $args->getLength() == 0 ) {
3201 $id = $this->mVariables
->matchStartToEnd( $part1 );
3202 if ( $id !== false ) {
3203 $text = $this->getVariableValue( $id, $frame );
3204 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3205 $this->mOutput
->updateCacheExpiry(
3206 $this->magicWordFactory
->getCacheTTL( $id ) );
3212 # MSG, MSGNW and RAW
3215 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3216 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3219 # Remove obsolete MSG:
3220 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3221 $mwMsg->matchStartAndRemove( $part1 );
3225 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3226 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3227 $forceRawInterwiki = true;
3233 $colonPos = strpos( $part1, ':' );
3234 if ( $colonPos !== false ) {
3235 $func = substr( $part1, 0, $colonPos );
3236 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3237 $argsLength = $args->getLength();
3238 for ( $i = 0; $i < $argsLength; $i++
) {
3239 $funcArgs[] = $args->item( $i );
3242 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3244 // Extract any forwarded flags
3245 if ( isset( $result['title'] ) ) {
3246 $title = $result['title'];
3248 if ( isset( $result['found'] ) ) {
3249 $found = $result['found'];
3251 if ( array_key_exists( 'text', $result ) ) {
3253 $text = $result['text'];
3255 if ( isset( $result['nowiki'] ) ) {
3256 $nowiki = $result['nowiki'];
3258 if ( isset( $result['isHTML'] ) ) {
3259 $isHTML = $result['isHTML'];
3261 if ( isset( $result['forceRawInterwiki'] ) ) {
3262 $forceRawInterwiki = $result['forceRawInterwiki'];
3264 if ( isset( $result['isChildObj'] ) ) {
3265 $isChildObj = $result['isChildObj'];
3267 if ( isset( $result['isLocalObj'] ) ) {
3268 $isLocalObj = $result['isLocalObj'];
3273 # Finish mangling title and then check for loops.
3274 # Set $title to a Title object and $titleText to the PDBK
3277 # Split the title into page and subpage
3279 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3280 if ( $part1 !== $relative ) {
3282 $ns = $this->mTitle
->getNamespace();
3284 $title = Title
::newFromText( $part1, $ns );
3286 $titleText = $title->getPrefixedText();
3287 # Check for language variants if the template is not found
3288 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3289 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3291 # Do recursion depth check
3292 $limit = $this->mOptions
->getMaxTemplateDepth();
3293 if ( $frame->depth
>= $limit ) {
3295 $text = '<span class="error">'
3296 . wfMessage( 'parser-template-recursion-depth-warning' )
3297 ->numParams( $limit )->inContentLanguage()->text()
3303 # Load from database
3304 if ( !$found && $title ) {
3305 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3306 if ( !$title->isExternal() ) {
3307 if ( $title->isSpecialPage()
3308 && $this->mOptions
->getAllowSpecialInclusion()
3309 && $this->ot
['html']
3311 $specialPage = $this->specialPageFactory
->getPage( $title->getDBkey() );
3312 // Pass the template arguments as URL parameters.
3313 // "uselang" will have no effect since the Language object
3314 // is forced to the one defined in ParserOptions.
3316 $argsLength = $args->getLength();
3317 for ( $i = 0; $i < $argsLength; $i++
) {
3318 $bits = $args->item( $i )->splitArg();
3319 if ( strval( $bits['index'] ) === '' ) {
3320 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3321 $value = trim( $frame->expand( $bits['value'] ) );
3322 $pageArgs[$name] = $value;
3326 // Create a new context to execute the special page
3327 $context = new RequestContext
;
3328 $context->setTitle( $title );
3329 $context->setRequest( new FauxRequest( $pageArgs ) );
3330 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3331 $context->setUser( $this->getUser() );
3333 // If this page is cached, then we better not be per user.
3334 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3336 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3337 $ret = $this->specialPageFactory
->capturePath( $title, $context, $this->getLinkRenderer() );
3339 $text = $context->getOutput()->getHTML();
3340 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3343 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3344 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3345 $specialPage->maxIncludeCacheTime()
3349 } elseif ( $this->nsInfo
->isNonincludable( $title->getNamespace() ) ) {
3350 $found = false; # access denied
3351 wfDebug( __METHOD__
. ": template inclusion denied for " .
3352 $title->getPrefixedDBkey() . "\n" );
3354 list( $text, $title ) = $this->getTemplateDom( $title );
3355 if ( $text !== false ) {
3361 # If the title is valid but undisplayable, make a link to it
3362 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3363 $text = "[[:$titleText]]";
3366 } elseif ( $title->isTrans() ) {
3367 # Interwiki transclusion
3368 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3369 $text = $this->interwikiTransclude( $title, 'render' );
3372 $text = $this->interwikiTransclude( $title, 'raw' );
3373 # Preprocess it like a template
3374 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3380 # Do infinite loop check
3381 # This has to be done after redirect resolution to avoid infinite loops via redirects
3382 if ( !$frame->loopCheck( $title ) ) {
3384 $text = '<span class="error">'
3385 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3387 $this->addTrackingCategory( 'template-loop-category' );
3388 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3389 wfEscapeWikiText( $titleText ) )->text() );
3390 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3394 # If we haven't found text to substitute by now, we're done
3395 # Recover the source wikitext and return it
3397 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3398 if ( $profileSection ) {
3399 $this->mProfiler
->scopedProfileOut( $profileSection );
3401 return [ 'object' => $text ];
3404 # Expand DOM-style return values in a child frame
3405 if ( $isChildObj ) {
3406 # Clean up argument array
3407 $newFrame = $frame->newChild( $args, $title );
3410 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3411 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3412 # Expansion is eligible for the empty-frame cache
3413 $text = $newFrame->cachedExpand( $titleText, $text );
3415 # Uncached expansion
3416 $text = $newFrame->expand( $text );
3419 if ( $isLocalObj && $nowiki ) {
3420 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3421 $isLocalObj = false;
3424 if ( $profileSection ) {
3425 $this->mProfiler
->scopedProfileOut( $profileSection );
3428 # Replace raw HTML by a placeholder
3430 $text = $this->insertStripItem( $text );
3431 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3432 # Escape nowiki-style return values
3433 $text = wfEscapeWikiText( $text );
3434 } elseif ( is_string( $text )
3435 && !$piece['lineStart']
3436 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3438 # T2529: if the template begins with a table or block-level
3439 # element, it should be treated as beginning a new line.
3440 # This behavior is somewhat controversial.
3441 $text = "\n" . $text;
3444 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3445 # Error, oversize inclusion
3446 if ( $titleText !== false ) {
3447 # Make a working, properly escaped link if possible (T25588)
3448 $text = "[[:$titleText]]";
3450 # This will probably not be a working link, but at least it may
3451 # provide some hint of where the problem is
3452 preg_replace( '/^:/', '', $originalTitle );
3453 $text = "[[:$originalTitle]]";
3455 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3456 . 'post-expand include size too large -->' );
3457 $this->limitationWarn( 'post-expand-template-inclusion' );
3460 if ( $isLocalObj ) {
3461 $ret = [ 'object' => $text ];
3463 $ret = [ 'text' => $text ];
3470 * Call a parser function and return an array with text and flags.
3472 * The returned array will always contain a boolean 'found', indicating
3473 * whether the parser function was found or not. It may also contain the
3475 * text: string|object, resulting wikitext or PP DOM object
3476 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3477 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3478 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3479 * nowiki: bool, wiki markup in $text should be escaped
3482 * @param PPFrame $frame The current frame, contains template arguments
3483 * @param string $function Function name
3484 * @param array $args Arguments to the function
3485 * @throws MWException
3488 public function callParserFunction( $frame, $function, array $args = [] ) {
3489 # Case sensitive functions
3490 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3491 $function = $this->mFunctionSynonyms
[1][$function];
3493 # Case insensitive functions
3494 $function = $this->contLang
->lc( $function );
3495 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3496 $function = $this->mFunctionSynonyms
[0][$function];
3498 return [ 'found' => false ];
3502 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3504 // Avoid PHP 7.1 warning from passing $this by reference
3507 $allArgs = [ &$parser ];
3508 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3509 # Convert arguments to PPNodes and collect for appending to $allArgs
3511 foreach ( $args as $k => $v ) {
3512 if ( $v instanceof PPNode ||
$k === 0 ) {
3515 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3519 # Add a frame parameter, and pass the arguments as an array
3520 $allArgs[] = $frame;
3521 $allArgs[] = $funcArgs;
3523 # Convert arguments to plain text and append to $allArgs
3524 foreach ( $args as $k => $v ) {
3525 if ( $v instanceof PPNode
) {
3526 $allArgs[] = trim( $frame->expand( $v ) );
3527 } elseif ( is_int( $k ) && $k >= 0 ) {
3528 $allArgs[] = trim( $v );
3530 $allArgs[] = trim( "$k=$v" );
3535 $result = $callback( ...$allArgs );
3537 # The interface for function hooks allows them to return a wikitext
3538 # string or an array containing the string and any flags. This mungs
3539 # things around to match what this method should return.
3540 if ( !is_array( $result ) ) {
3546 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3547 $result['text'] = $result[0];
3549 unset( $result[0] );
3556 $preprocessFlags = 0;
3557 if ( isset( $result['noparse'] ) ) {
3558 $noparse = $result['noparse'];
3560 if ( isset( $result['preprocessFlags'] ) ) {
3561 $preprocessFlags = $result['preprocessFlags'];
3565 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3566 $result['isChildObj'] = true;
3573 * Get the semi-parsed DOM representation of a template with a given title,
3574 * and its redirect destination title. Cached.
3576 * @param Title $title
3580 public function getTemplateDom( $title ) {
3581 $cacheTitle = $title;
3582 $titleText = $title->getPrefixedDBkey();
3584 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3585 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3586 $title = Title
::makeTitle( $ns, $dbk );
3587 $titleText = $title->getPrefixedDBkey();
3589 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3590 return [ $this->mTplDomCache
[$titleText], $title ];
3593 # Cache miss, go to the database
3594 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3596 if ( $text === false ) {
3597 $this->mTplDomCache
[$titleText] = false;
3598 return [ false, $title ];
3601 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3602 $this->mTplDomCache
[$titleText] = $dom;
3604 if ( !$title->equals( $cacheTitle ) ) {
3605 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3606 [ $title->getNamespace(), $title->getDBkey() ];
3609 return [ $dom, $title ];
3613 * Fetch the current revision of a given title. Note that the revision
3614 * (and even the title) may not exist in the database, so everything
3615 * contributing to the output of the parser should use this method
3616 * where possible, rather than getting the revisions themselves. This
3617 * method also caches its results, so using it benefits performance.
3620 * @param Title $title
3623 public function fetchCurrentRevisionOfTitle( $title ) {
3624 $cacheKey = $title->getPrefixedDBkey();
3625 if ( !$this->currentRevisionCache
) {
3626 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3628 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3629 $this->currentRevisionCache
->set( $cacheKey,
3630 // Defaults to Parser::statelessFetchRevision()
3631 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3634 return $this->currentRevisionCache
->get( $cacheKey );
3638 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3639 * without passing them on to it.
3642 * @param Title $title
3643 * @param Parser|bool $parser
3644 * @return Revision|bool False if missing
3646 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3647 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3653 * Fetch the unparsed text of a template and register a reference to it.
3654 * @param Title $title
3655 * @return array ( string or false, Title )
3657 public function fetchTemplateAndTitle( $title ) {
3658 // Defaults to Parser::statelessFetchTemplate()
3659 $templateCb = $this->mOptions
->getTemplateCallback();
3660 $stuff = call_user_func( $templateCb, $title, $this );
3661 // We use U+007F DELETE to distinguish strip markers from regular text.
3662 $text = $stuff['text'];
3663 if ( is_string( $stuff['text'] ) ) {
3664 $text = strtr( $text, "\x7f", "?" );
3666 $finalTitle = $stuff['finalTitle'] ??
$title;
3667 if ( isset( $stuff['deps'] ) ) {
3668 foreach ( $stuff['deps'] as $dep ) {
3669 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3670 if ( $dep['title']->equals( $this->getTitle() ) ) {
3671 // If we transclude ourselves, the final result
3672 // will change based on the new version of the page
3673 $this->mOutput
->setFlag( 'vary-revision' );
3677 return [ $text, $finalTitle ];
3681 * Fetch the unparsed text of a template and register a reference to it.
3682 * @param Title $title
3683 * @return string|bool
3685 public function fetchTemplate( $title ) {
3686 return $this->fetchTemplateAndTitle( $title )[0];
3690 * Static function to get a template
3691 * Can be overridden via ParserOptions::setTemplateCallback().
3693 * @param Title $title
3694 * @param bool|Parser $parser
3698 public static function statelessFetchTemplate( $title, $parser = false ) {
3699 $text = $skip = false;
3700 $finalTitle = $title;
3703 # Loop to fetch the article, with up to 1 redirect
3704 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3705 # Give extensions a chance to select the revision instead
3706 $id = false; # Assume current
3707 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3708 [ $parser, $title, &$skip, &$id ] );
3714 'page_id' => $title->getArticleID(),
3721 $rev = Revision
::newFromId( $id );
3722 } elseif ( $parser ) {
3723 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3725 $rev = Revision
::newFromTitle( $title );
3727 $rev_id = $rev ?
$rev->getId() : 0;
3728 # If there is no current revision, there is no page
3729 if ( $id === false && !$rev ) {
3730 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3731 $linkCache->addBadLinkObj( $title );
3736 'page_id' => $title->getArticleID(),
3737 'rev_id' => $rev_id ];
3738 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3739 # We fetched a rev from a different title; register it too...
3741 'title' => $rev->getTitle(),
3742 'page_id' => $rev->getPage(),
3743 'rev_id' => $rev_id ];
3747 $content = $rev->getContent();
3748 $text = $content ?
$content->getWikitextForTransclusion() : null;
3750 Hooks
::run( 'ParserFetchTemplate',
3751 [ $parser, $title, $rev, &$text, &$deps ] );
3753 if ( $text === false ||
$text === null ) {
3757 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3758 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3759 lcfirst( $title->getText() ) )->inContentLanguage();
3760 if ( !$message->exists() ) {
3764 $content = $message->content();
3765 $text = $message->plain();
3773 $finalTitle = $title;
3774 $title = $content->getRedirectTarget();
3778 'finalTitle' => $finalTitle,
3783 * Fetch a file and its title and register a reference to it.
3784 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3785 * @param Title $title
3786 * @param array $options Array of options to RepoGroup::findFile
3788 * @deprecated since 1.32, use fetchFileAndTitle instead
3790 public function fetchFile( $title, $options = [] ) {
3791 wfDeprecated( __METHOD__
, '1.32' );
3792 return $this->fetchFileAndTitle( $title, $options )[0];
3796 * Fetch a file and its title and register a reference to it.
3797 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3798 * @param Title $title
3799 * @param array $options Array of options to RepoGroup::findFile
3800 * @return array ( File or false, Title of file )
3802 public function fetchFileAndTitle( $title, $options = [] ) {
3803 $file = $this->fetchFileNoRegister( $title, $options );
3805 $time = $file ?
$file->getTimestamp() : false;
3806 $sha1 = $file ?
$file->getSha1() : false;
3807 # Register the file as a dependency...
3808 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3809 if ( $file && !$title->equals( $file->getTitle() ) ) {
3810 # Update fetched file title
3811 $title = $file->getTitle();
3812 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3814 return [ $file, $title ];
3818 * Helper function for fetchFileAndTitle.
3820 * Also useful if you need to fetch a file but not use it yet,
3821 * for example to get the file's handler.
3823 * @param Title $title
3824 * @param array $options Array of options to RepoGroup::findFile
3827 protected function fetchFileNoRegister( $title, $options = [] ) {
3828 if ( isset( $options['broken'] ) ) {
3829 $file = false; // broken thumbnail forced by hook
3830 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3831 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3832 } else { // get by (name,timestamp)
3833 $file = wfFindFile( $title, $options );
3839 * Transclude an interwiki link.
3841 * @param Title $title
3842 * @param string $action Usually one of (raw, render)
3846 public function interwikiTransclude( $title, $action ) {
3847 if ( !$this->siteConfig
->get( 'EnableScaryTranscluding' ) ) {
3848 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3851 $url = $title->getFullURL( [ 'action' => $action ] );
3852 if ( strlen( $url ) > 1024 ) {
3853 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3856 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3858 $fname = __METHOD__
;
3859 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3861 $data = $cache->getWithSetCallback(
3862 $cache->makeGlobalKey(
3863 'interwiki-transclude',
3864 ( $wikiId !== false ) ?
$wikiId : 'external',
3867 $this->siteConfig
->get( 'TranscludeCacheExpiry' ),
3868 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3869 $req = MWHttpRequest
::factory( $url, [], $fname );
3871 $status = $req->execute(); // Status object
3872 if ( !$status->isOK() ) {
3873 $ttl = $cache::TTL_UNCACHEABLE
;
3874 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3875 $ttl = min( $cache::TTL_LAGGED
, $ttl );
3879 'text' => $status->isOK() ?
$req->getContent() : null,
3880 'code' => $req->getStatus()
3884 'checkKeys' => ( $wikiId !== false )
3885 ?
[ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
3887 'pcGroup' => 'interwiki-transclude:5',
3888 'pcTTL' => $cache::TTL_PROC_LONG
3892 if ( is_string( $data['text'] ) ) {
3893 $text = $data['text'];
3894 } elseif ( $data['code'] != 200 ) {
3895 // Though we failed to fetch the content, this status is useless.
3896 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
3897 ->params( $url, $data['code'] )->inContentLanguage()->text();
3899 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3906 * Triple brace replacement -- used for template arguments
3909 * @param array $piece
3910 * @param PPFrame $frame
3914 public function argSubstitution( $piece, $frame ) {
3916 $parts = $piece['parts'];
3917 $nameWithSpaces = $frame->expand( $piece['title'] );
3918 $argName = trim( $nameWithSpaces );
3920 $text = $frame->getArgument( $argName );
3921 if ( $text === false && $parts->getLength() > 0
3922 && ( $this->ot
['html']
3924 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3927 # No match in frame, use the supplied default
3928 $object = $parts->item( 0 )->getChildren();
3930 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3931 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3932 $this->limitationWarn( 'post-expand-template-argument' );
3935 if ( $text === false && $object === false ) {
3937 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3939 if ( $error !== false ) {
3942 if ( $object !== false ) {
3943 $ret = [ 'object' => $object ];
3945 $ret = [ 'text' => $text ];
3952 * Return the text to be used for a given extension tag.
3953 * This is the ghost of strip().
3955 * @param array $params Associative array of parameters:
3956 * name PPNode for the tag name
3957 * attr PPNode for unparsed text where tag attributes are thought to be
3958 * attributes Optional associative array of parsed attributes
3959 * inner Contents of extension element
3960 * noClose Original text did not have a close tag
3961 * @param PPFrame $frame
3963 * @throws MWException
3966 public function extensionSubstitution( $params, $frame ) {
3967 static $errorStr = '<span class="error">';
3968 static $errorLen = 20;
3970 $name = $frame->expand( $params['name'] );
3971 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3972 // Probably expansion depth or node count exceeded. Just punt the
3977 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3978 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3983 // We can't safely check if the expansion for $content resulted in an
3984 // error, because the content could happen to be the error string
3986 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3988 $marker = self
::MARKER_PREFIX
. "-$name-"
3989 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3991 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3992 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3993 if ( $isFunctionTag ) {
3994 $markerType = 'none';
3996 $markerType = 'general';
3998 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3999 $name = strtolower( $name );
4000 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4001 if ( isset( $params['attributes'] ) ) {
4002 $attributes +
= $params['attributes'];
4005 if ( isset( $this->mTagHooks
[$name] ) ) {
4006 $output = call_user_func_array( $this->mTagHooks
[$name],
4007 [ $content, $attributes, $this, $frame ] );
4008 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4009 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4011 // Avoid PHP 7.1 warning from passing $this by reference
4013 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
4015 $output = '<span class="error">Invalid tag extension name: ' .
4016 htmlspecialchars( $name ) . '</span>';
4019 if ( is_array( $output ) ) {
4022 $output = $flags[0];
4023 if ( isset( $flags['markerType'] ) ) {
4024 $markerType = $flags['markerType'];
4028 if ( is_null( $attrText ) ) {
4031 if ( isset( $params['attributes'] ) ) {
4032 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4033 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4034 htmlspecialchars( $attrValue ) . '"';
4037 if ( $content === null ) {
4038 $output = "<$name$attrText/>";
4040 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4041 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4045 $output = "<$name$attrText>$content$close";
4049 if ( $markerType === 'none' ) {
4051 } elseif ( $markerType === 'nowiki' ) {
4052 $this->mStripState
->addNoWiki( $marker, $output );
4053 } elseif ( $markerType === 'general' ) {
4054 $this->mStripState
->addGeneral( $marker, $output );
4056 throw new MWException( __METHOD__
. ': invalid marker type' );
4062 * Increment an include size counter
4064 * @param string $type The type of expansion
4065 * @param int $size The size of the text
4066 * @return bool False if this inclusion would take it over the maximum, true otherwise
4068 public function incrementIncludeSize( $type, $size ) {
4069 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4072 $this->mIncludeSizes
[$type] +
= $size;
4078 * Increment the expensive function count
4080 * @return bool False if the limit has been exceeded
4082 public function incrementExpensiveFunctionCount() {
4083 $this->mExpensiveFunctionCount++
;
4084 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4088 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4089 * Fills $this->mDoubleUnderscores, returns the modified text
4091 * @param string $text
4095 public function doDoubleUnderscore( $text ) {
4096 # The position of __TOC__ needs to be recorded
4097 $mw = $this->magicWordFactory
->get( 'toc' );
4098 if ( $mw->match( $text ) ) {
4099 $this->mShowToc
= true;
4100 $this->mForceTocPosition
= true;
4102 # Set a placeholder. At the end we'll fill it in with the TOC.
4103 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4105 # Only keep the first one.
4106 $text = $mw->replace( '', $text );
4109 # Now match and remove the rest of them
4110 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4111 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4113 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4114 $this->mOutput
->mNoGallery
= true;
4116 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4117 $this->mShowToc
= false;
4119 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4120 && $this->mTitle
->getNamespace() == NS_CATEGORY
4122 $this->addTrackingCategory( 'hidden-category-category' );
4124 # (T10068) Allow control over whether robots index a page.
4125 # __INDEX__ always overrides __NOINDEX__, see T16899
4126 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4127 $this->mOutput
->setIndexPolicy( 'noindex' );
4128 $this->addTrackingCategory( 'noindex-category' );
4130 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4131 $this->mOutput
->setIndexPolicy( 'index' );
4132 $this->addTrackingCategory( 'index-category' );
4135 # Cache all double underscores in the database
4136 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4137 $this->mOutput
->setProperty( $key, '' );
4144 * @see ParserOutput::addTrackingCategory()
4145 * @param string $msg Message key
4146 * @return bool Whether the addition was successful
4148 public function addTrackingCategory( $msg ) {
4149 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4153 * This function accomplishes several tasks:
4154 * 1) Auto-number headings if that option is enabled
4155 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4156 * 3) Add a Table of contents on the top for users who have enabled the option
4157 * 4) Auto-anchor headings
4159 * It loops through all headlines, collects the necessary data, then splits up the
4160 * string and re-inserts the newly formatted headlines.
4162 * @param string $text
4163 * @param string $origText Original, untouched wikitext
4164 * @param bool $isMain
4165 * @return mixed|string
4168 public function formatHeadings( $text, $origText, $isMain = true ) {
4169 # Inhibit editsection links if requested in the page
4170 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4171 $maybeShowEditLink = false;
4173 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4176 # Get all headlines for numbering them and adding funky stuff like [edit]
4177 # links - this is for later, but we need the number of headlines right now
4178 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4179 # be trimmed here since whitespace in HTML headings is significant.
4181 $numMatches = preg_match_all(
4182 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4187 # if there are fewer than 4 headlines in the article, do not show TOC
4188 # unless it's been explicitly enabled.
4189 $enoughToc = $this->mShowToc
&&
4190 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4192 # Allow user to stipulate that a page should have a "new section"
4193 # link added via __NEWSECTIONLINK__
4194 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4195 $this->mOutput
->setNewSection( true );
4198 # Allow user to remove the "new section"
4199 # link via __NONEWSECTIONLINK__
4200 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4201 $this->mOutput
->hideNewSection( true );
4204 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4205 # override above conditions and always show TOC above first header
4206 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4207 $this->mShowToc
= true;
4215 # Ugh .. the TOC should have neat indentation levels which can be
4216 # passed to the skin functions. These are determined here
4220 $sublevelCount = [];
4226 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4227 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4228 $oldType = $this->mOutputType
;
4229 $this->setOutputType( self
::OT_WIKI
);
4230 $frame = $this->getPreprocessor()->newFrame();
4231 $root = $this->preprocessToDom( $origText );
4232 $node = $root->getFirstChild();
4237 $headlines = $numMatches !== false ?
$matches[3] : [];
4239 $maxTocLevel = $this->siteConfig
->get( 'MaxTocLevel' );
4240 foreach ( $headlines as $headline ) {
4241 $isTemplate = false;
4243 $sectionIndex = false;
4245 $markerMatches = [];
4246 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4247 $serial = $markerMatches[1];
4248 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4249 $isTemplate = ( $titleText != $baseTitleText );
4250 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4254 $prevlevel = $level;
4256 $level = $matches[1][$headlineCount];
4258 if ( $level > $prevlevel ) {
4259 # Increase TOC level
4261 $sublevelCount[$toclevel] = 0;
4262 if ( $toclevel < $maxTocLevel ) {
4263 $prevtoclevel = $toclevel;
4264 $toc .= Linker
::tocIndent();
4267 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4268 # Decrease TOC level, find level to jump to
4270 for ( $i = $toclevel; $i > 0; $i-- ) {
4271 if ( $levelCount[$i] == $level ) {
4272 # Found last matching level
4275 } elseif ( $levelCount[$i] < $level ) {
4276 # Found first matching level below current level
4284 if ( $toclevel < $maxTocLevel ) {
4285 if ( $prevtoclevel < $maxTocLevel ) {
4286 # Unindent only if the previous toc level was shown :p
4287 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4288 $prevtoclevel = $toclevel;
4290 $toc .= Linker
::tocLineEnd();
4294 # No change in level, end TOC line
4295 if ( $toclevel < $maxTocLevel ) {
4296 $toc .= Linker
::tocLineEnd();
4300 $levelCount[$toclevel] = $level;
4302 # count number of headlines for each level
4303 $sublevelCount[$toclevel]++
;
4305 for ( $i = 1; $i <= $toclevel; $i++
) {
4306 if ( !empty( $sublevelCount[$i] ) ) {
4310 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4315 # The safe header is a version of the header text safe to use for links
4317 # Remove link placeholders by the link text.
4318 # <!--LINK number-->
4320 # link text with suffix
4321 # Do this before unstrip since link text can contain strip markers
4322 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4324 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4325 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4327 # Remove any <style> or <script> tags (T198618)
4328 $safeHeadline = preg_replace(
4329 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4334 # Strip out HTML (first regex removes any tag not allowed)
4336 # * <sup> and <sub> (T10393)
4340 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4341 # * <s> and <strike> (T35715)
4342 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4343 # to allow setting directionality in toc items.
4344 $tocline = preg_replace(
4346 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4347 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4353 # Strip '<span></span>', which is the result from the above if
4354 # <span id="foo"></span> is used to produce an additional anchor
4356 $tocline = str_replace( '<span></span>', '', $tocline );
4358 $tocline = trim( $tocline );
4360 # For the anchor, strip out HTML-y stuff period
4361 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4362 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4364 # Save headline for section edit hint before it's escaped
4365 $headlineHint = $safeHeadline;
4367 # Decode HTML entities
4368 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4370 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4372 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4373 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4374 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4375 if ( $fallbackHeadline === $safeHeadline ) {
4376 # No reason to have both (in fact, we can't)
4377 $fallbackHeadline = false;
4380 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4381 # @todo FIXME: We may be changing them depending on the current locale.
4382 $arrayKey = strtolower( $safeHeadline );
4383 if ( $fallbackHeadline === false ) {
4384 $fallbackArrayKey = false;
4386 $fallbackArrayKey = strtolower( $fallbackHeadline );
4389 # Create the anchor for linking from the TOC to the section
4390 $anchor = $safeHeadline;
4391 $fallbackAnchor = $fallbackHeadline;
4392 if ( isset( $refers[$arrayKey] ) ) {
4393 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4394 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4396 $linkAnchor .= "_$i";
4397 $refers["${arrayKey}_$i"] = true;
4399 $refers[$arrayKey] = true;
4401 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4402 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4403 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4404 $fallbackAnchor .= "_$i";
4405 $refers["${fallbackArrayKey}_$i"] = true;
4407 $refers[$fallbackArrayKey] = true;
4410 # Don't number the heading if it is the only one (looks silly)
4411 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4412 # the two are different if the line contains a link
4413 $headline = Html
::element(
4415 [ 'class' => 'mw-headline-number' ],
4417 ) . ' ' . $headline;
4420 if ( $enoughToc && ( !isset( $maxTocLevel ) ||
$toclevel < $maxTocLevel ) ) {
4421 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4422 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4425 # Add the section to the section tree
4426 # Find the DOM node for this header
4427 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4428 while ( $node && !$noOffset ) {
4429 if ( $node->getName() === 'h' ) {
4430 $bits = $node->splitHeading();
4431 if ( $bits['i'] == $sectionIndex ) {
4435 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4436 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4437 $node = $node->getNextSibling();
4440 'toclevel' => $toclevel,
4443 'number' => $numbering,
4444 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4445 'fromtitle' => $titleText,
4446 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4447 'anchor' => $anchor,
4450 # give headline the correct <h#> tag
4451 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4452 // Output edit section links as markers with styles that can be customized by skins
4453 if ( $isTemplate ) {
4454 # Put a T flag in the section identifier, to indicate to extractSections()
4455 # that sections inside <includeonly> should be counted.
4456 $editsectionPage = $titleText;
4457 $editsectionSection = "T-$sectionIndex";
4458 $editsectionContent = null;
4460 $editsectionPage = $this->mTitle
->getPrefixedText();
4461 $editsectionSection = $sectionIndex;
4462 $editsectionContent = $headlineHint;
4464 // We use a bit of pesudo-xml for editsection markers. The
4465 // language converter is run later on. Using a UNIQ style marker
4466 // leads to the converter screwing up the tokens when it
4467 // converts stuff. And trying to insert strip tags fails too. At
4468 // this point all real inputted tags have already been escaped,
4469 // so we don't have to worry about a user trying to input one of
4470 // these markers directly. We use a page and section attribute
4471 // to stop the language converter from converting these
4472 // important bits of data, but put the headline hint inside a
4473 // content block because the language converter is supposed to
4474 // be able to convert that piece of data.
4475 // Gets replaced with html in ParserOutput::getText
4476 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4477 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4478 if ( $editsectionContent !== null ) {
4479 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4486 $head[$headlineCount] = Linker
::makeHeadline( $level,
4487 $matches['attrib'][$headlineCount], $anchor, $headline,
4488 $editlink, $fallbackAnchor );
4493 $this->setOutputType( $oldType );
4495 # Never ever show TOC if no headers
4496 if ( $numVisible < 1 ) {
4501 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4502 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4504 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4505 $this->mOutput
->setTOCHTML( $toc );
4506 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4510 $this->mOutput
->setSections( $tocraw );
4513 # split up and insert constructed headlines
4514 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4517 // build an array of document sections
4519 foreach ( $blocks as $block ) {
4520 // $head is zero-based, sections aren't.
4521 if ( empty( $head[$i - 1] ) ) {
4522 $sections[$i] = $block;
4524 $sections[$i] = $head[$i - 1] . $block;
4528 * Send a hook, one per section.
4529 * The idea here is to be able to make section-level DIVs, but to do so in a
4530 * lower-impact, more correct way than r50769
4533 * $section : the section number
4534 * &$sectionContent : ref to the content of the section
4535 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4537 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4542 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4543 // append the TOC at the beginning
4544 // Top anchor now in skin
4545 $sections[0] .= $toc . "\n";
4548 $full .= implode( '', $sections );
4550 if ( $this->mForceTocPosition
) {
4551 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4558 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4559 * conversion, substituting signatures, {{subst:}} templates, etc.
4561 * @param string $text The text to transform
4562 * @param Title $title The Title object for the current article
4563 * @param User $user The User object describing the current user
4564 * @param ParserOptions $options Parsing options
4565 * @param bool $clearState Whether to clear the parser state first
4566 * @return string The altered wiki markup
4568 public function preSaveTransform( $text, Title
$title, User
$user,
4569 ParserOptions
$options, $clearState = true
4571 if ( $clearState ) {
4572 $magicScopeVariable = $this->lock();
4574 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4575 $this->setUser( $user );
4577 // Strip U+0000 NULL (T159174)
4578 $text = str_replace( "\000", '', $text );
4580 // We still normalize line endings for backwards-compatibility
4581 // with other code that just calls PST, but this should already
4582 // be handled in TextContent subclasses
4583 $text = TextContent
::normalizeLineEndings( $text );
4585 if ( $options->getPreSaveTransform() ) {
4586 $text = $this->pstPass2( $text, $user );
4588 $text = $this->mStripState
->unstripBoth( $text );
4590 $this->setUser( null ); # Reset
4596 * Pre-save transform helper function
4598 * @param string $text
4603 private function pstPass2( $text, $user ) {
4604 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4605 # $this->contLang here in order to give everyone the same signature and use the default one
4606 # rather than the one selected in each user's preferences. (see also T14815)
4607 $ts = $this->mOptions
->getTimestamp();
4608 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4609 $ts = $timestamp->format( 'YmdHis' );
4610 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4612 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4614 # Variable replacement
4615 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4616 $text = $this->replaceVariables( $text );
4618 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4619 # which may corrupt this parser instance via its wfMessage()->text() call-
4622 if ( strpos( $text, '~~~' ) !== false ) {
4623 $sigText = $this->getUserSig( $user );
4624 $text = strtr( $text, [
4626 '~~~~' => "$sigText $d",
4629 # The main two signature forms used above are time-sensitive
4630 $this->mOutput
->setFlag( 'user-signature' );
4633 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4634 $tc = '[' . Title
::legalChars() . ']';
4635 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4637 // [[ns:page (context)|]]
4638 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4639 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4640 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4641 // [[ns:page (context), context|]] (using either single or double-width comma)
4642 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4643 // [[|page]] (reverse pipe trick: add context from page title)
4644 $p2 = "/\[\[\\|($tc+)]]/";
4646 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4647 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4648 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4649 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4651 $t = $this->mTitle
->getText();
4653 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4654 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4655 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4656 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4658 # if there's no context, don't bother duplicating the title
4659 $text = preg_replace( $p2, '[[\\1]]', $text );
4666 * Fetch the user's signature text, if any, and normalize to
4667 * validated, ready-to-insert wikitext.
4668 * If you have pre-fetched the nickname or the fancySig option, you can
4669 * specify them here to save a database query.
4670 * Do not reuse this parser instance after calling getUserSig(),
4671 * as it may have changed.
4673 * @param User &$user
4674 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4675 * @param bool|null $fancySig whether the nicknname is the complete signature
4676 * or null to use default value
4679 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4680 $username = $user->getName();
4682 # If not given, retrieve from the user object.
4683 if ( $nickname === false ) {
4684 $nickname = $user->getOption( 'nickname' );
4687 if ( is_null( $fancySig ) ) {
4688 $fancySig = $user->getBoolOption( 'fancysig' );
4691 $nickname = $nickname == null ?
$username : $nickname;
4693 if ( mb_strlen( $nickname ) > $this->siteConfig
->get( 'MaxSigChars' ) ) {
4694 $nickname = $username;
4695 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4696 } elseif ( $fancySig !== false ) {
4697 # Sig. might contain markup; validate this
4698 if ( $this->validateSig( $nickname ) !== false ) {
4699 # Validated; clean up (if needed) and return it
4700 return $this->cleanSig( $nickname, true );
4702 # Failed to validate; fall back to the default
4703 $nickname = $username;
4704 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4708 # Make sure nickname doesnt get a sig in a sig
4709 $nickname = self
::cleanSigInSig( $nickname );
4711 # If we're still here, make it a link to the user page
4712 $userText = wfEscapeWikiText( $username );
4713 $nickText = wfEscapeWikiText( $nickname );
4714 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4716 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4717 ->title( $this->getTitle() )->text();
4721 * Check that the user's signature contains no bad XML
4723 * @param string $text
4724 * @return string|bool An expanded string, or false if invalid.
4726 public function validateSig( $text ) {
4727 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4731 * Clean up signature text
4733 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4734 * 2) Substitute all transclusions
4736 * @param string $text
4737 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4738 * @return string Signature text
4740 public function cleanSig( $text, $parsing = false ) {
4743 $magicScopeVariable = $this->lock();
4744 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4747 # Option to disable this feature
4748 if ( !$this->mOptions
->getCleanSignatures() ) {
4752 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4753 # => Move this logic to braceSubstitution()
4754 $substWord = $this->magicWordFactory
->get( 'subst' );
4755 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4756 $substText = '{{' . $substWord->getSynonym( 0 );
4758 $text = preg_replace( $substRegex, $substText, $text );
4759 $text = self
::cleanSigInSig( $text );
4760 $dom = $this->preprocessToDom( $text );
4761 $frame = $this->getPreprocessor()->newFrame();
4762 $text = $frame->expand( $dom );
4765 $text = $this->mStripState
->unstripBoth( $text );
4772 * Strip 3, 4 or 5 tildes out of signatures.
4774 * @param string $text
4775 * @return string Signature text with /~{3,5}/ removed
4777 public static function cleanSigInSig( $text ) {
4778 $text = preg_replace( '/~{3,5}/', '', $text );
4783 * Set up some variables which are usually set up in parse()
4784 * so that an external function can call some class members with confidence
4786 * @param Title|null $title
4787 * @param ParserOptions $options
4788 * @param int $outputType
4789 * @param bool $clearState
4791 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4792 $outputType, $clearState = true
4794 $this->startParse( $title, $options, $outputType, $clearState );
4798 * @param Title|null $title
4799 * @param ParserOptions $options
4800 * @param int $outputType
4801 * @param bool $clearState
4803 private function startParse( Title
$title = null, ParserOptions
$options,
4804 $outputType, $clearState = true
4806 $this->setTitle( $title );
4807 $this->mOptions
= $options;
4808 $this->setOutputType( $outputType );
4809 if ( $clearState ) {
4810 $this->clearState();
4815 * Wrapper for preprocess()
4817 * @param string $text The text to preprocess
4818 * @param ParserOptions $options
4819 * @param Title|null $title Title object or null to use $wgTitle
4822 public function transformMsg( $text, $options, $title = null ) {
4823 static $executing = false;
4825 # Guard against infinite recursion
4836 $text = $this->preprocess( $text, $title, $options );
4843 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4844 * The callback should have the following form:
4845 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4847 * Transform and return $text. Use $parser for any required context, e.g. use
4848 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4850 * Hooks may return extended information by returning an array, of which the
4851 * first numbered element (index 0) must be the return string, and all other
4852 * entries are extracted into local variables within an internal function
4853 * in the Parser class.
4855 * This interface (introduced r61913) appears to be undocumented, but
4856 * 'markerType' is used by some core tag hooks to override which strip
4857 * array their results are placed in. **Use great caution if attempting
4858 * this interface, as it is not documented and injudicious use could smash
4859 * private variables.**
4861 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4862 * @param callable $callback The callback function (and object) to use for the tag
4863 * @throws MWException
4864 * @return callable|null The old value of the mTagHooks array associated with the hook
4866 public function setHook( $tag, callable
$callback ) {
4867 $tag = strtolower( $tag );
4868 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4869 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4871 $oldVal = $this->mTagHooks
[$tag] ??
null;
4872 $this->mTagHooks
[$tag] = $callback;
4873 if ( !in_array( $tag, $this->mStripList
) ) {
4874 $this->mStripList
[] = $tag;
4881 * As setHook(), but letting the contents be parsed.
4883 * Transparent tag hooks are like regular XML-style tag hooks, except they
4884 * operate late in the transformation sequence, on HTML instead of wikitext.
4886 * This is probably obsoleted by things dealing with parser frames?
4887 * The only extension currently using it is geoserver.
4890 * @todo better document or deprecate this
4892 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4893 * @param callable $callback The callback function (and object) to use for the tag
4894 * @throws MWException
4895 * @return callable|null The old value of the mTagHooks array associated with the hook
4897 public function setTransparentTagHook( $tag, callable
$callback ) {
4898 $tag = strtolower( $tag );
4899 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4900 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4902 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4903 $this->mTransparentTagHooks
[$tag] = $callback;
4909 * Remove all tag hooks
4911 public function clearTagHooks() {
4912 $this->mTagHooks
= [];
4913 $this->mFunctionTagHooks
= [];
4914 $this->mStripList
= $this->mDefaultStripList
;
4918 * Create a function, e.g. {{sum:1|2|3}}
4919 * The callback function should have the form:
4920 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4922 * Or with Parser::SFH_OBJECT_ARGS:
4923 * function myParserFunction( $parser, $frame, $args ) { ... }
4925 * The callback may either return the text result of the function, or an array with the text
4926 * in element 0, and a number of flags in the other elements. The names of the flags are
4927 * specified in the keys. Valid flags are:
4928 * found The text returned is valid, stop processing the template. This
4930 * nowiki Wiki markup in the return value should be escaped
4931 * isHTML The returned text is HTML, armour it against wikitext transformation
4933 * @param string $id The magic word ID
4934 * @param callable $callback The callback function (and object) to use
4935 * @param int $flags A combination of the following flags:
4936 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4938 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4939 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4940 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4941 * the arguments, and to control the way they are expanded.
4943 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4944 * arguments, for instance:
4945 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4947 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4948 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4949 * working if/when this is changed.
4951 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4954 * Please read the documentation in includes/parser/Preprocessor.php for more information
4955 * about the methods available in PPFrame and PPNode.
4957 * @throws MWException
4958 * @return string|callable The old callback function for this name, if any
4960 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4961 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4962 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4964 # Add to function cache
4965 $mw = $this->magicWordFactory
->get( $id );
4967 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4970 $synonyms = $mw->getSynonyms();
4971 $sensitive = intval( $mw->isCaseSensitive() );
4973 foreach ( $synonyms as $syn ) {
4975 if ( !$sensitive ) {
4976 $syn = $this->contLang
->lc( $syn );
4979 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4982 # Remove trailing colon
4983 if ( substr( $syn, -1, 1 ) === ':' ) {
4984 $syn = substr( $syn, 0, -1 );
4986 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4992 * Get all registered function hook identifiers
4996 public function getFunctionHooks() {
4997 $this->firstCallInit();
4998 return array_keys( $this->mFunctionHooks
);
5002 * Create a tag function, e.g. "<test>some stuff</test>".
5003 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5004 * Unlike parser functions, their content is not preprocessed.
5005 * @param string $tag
5006 * @param callable $callback
5008 * @throws MWException
5011 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
5012 $tag = strtolower( $tag );
5013 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5014 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5016 $old = $this->mFunctionTagHooks
[$tag] ??
null;
5017 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
5019 if ( !in_array( $tag, $this->mStripList
) ) {
5020 $this->mStripList
[] = $tag;
5027 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5028 * Placeholders created in Linker::link()
5030 * @param string &$text
5031 * @param int $options
5033 public function replaceLinkHolders( &$text, $options = 0 ) {
5034 $this->mLinkHolders
->replace( $text );
5038 * Replace "<!--LINK-->" link placeholders with plain text of links
5039 * (not HTML-formatted).
5041 * @param string $text
5044 public function replaceLinkHoldersText( $text ) {
5045 return $this->mLinkHolders
->replaceText( $text );
5049 * Renders an image gallery from a text with one line per image.
5050 * text labels may be given by using |-style alternative text. E.g.
5051 * Image:one.jpg|The number "1"
5052 * Image:tree.jpg|A tree
5053 * given as text will return the HTML of a gallery with two images,
5054 * labeled 'The number "1"' and
5057 * @param string $text
5058 * @param array $params
5059 * @return string HTML
5061 public function renderImageGallery( $text, $params ) {
5063 if ( isset( $params['mode'] ) ) {
5064 $mode = $params['mode'];
5068 $ig = ImageGalleryBase
::factory( $mode );
5069 } catch ( Exception
$e ) {
5070 // If invalid type set, fallback to default.
5071 $ig = ImageGalleryBase
::factory( false );
5074 $ig->setContextTitle( $this->mTitle
);
5075 $ig->setShowBytes( false );
5076 $ig->setShowDimensions( false );
5077 $ig->setShowFilename( false );
5078 $ig->setParser( $this );
5079 $ig->setHideBadImages();
5080 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5082 if ( isset( $params['showfilename'] ) ) {
5083 $ig->setShowFilename( true );
5085 $ig->setShowFilename( false );
5087 if ( isset( $params['caption'] ) ) {
5088 // NOTE: We aren't passing a frame here or below. Frame info
5089 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5090 // See T107332#4030581
5091 $caption = $this->recursiveTagParse( $params['caption'] );
5092 $ig->setCaptionHtml( $caption );
5094 if ( isset( $params['perrow'] ) ) {
5095 $ig->setPerRow( $params['perrow'] );
5097 if ( isset( $params['widths'] ) ) {
5098 $ig->setWidths( $params['widths'] );
5100 if ( isset( $params['heights'] ) ) {
5101 $ig->setHeights( $params['heights'] );
5103 $ig->setAdditionalOptions( $params );
5105 // Avoid PHP 7.1 warning from passing $this by reference
5107 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5109 $lines = StringUtils
::explode( "\n", $text );
5110 foreach ( $lines as $line ) {
5111 # match lines like these:
5112 # Image:someimage.jpg|This is some image
5114 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5116 if ( count( $matches ) == 0 ) {
5120 if ( strpos( $matches[0], '%' ) !== false ) {
5121 $matches[1] = rawurldecode( $matches[1] );
5123 $title = Title
::newFromText( $matches[1], NS_FILE
);
5124 if ( is_null( $title ) ) {
5125 # Bogus title. Ignore these so we don't bomb out later.
5129 # We need to get what handler the file uses, to figure out parameters.
5130 # Note, a hook can overide the file name, and chose an entirely different
5131 # file (which potentially could be of a different type and have different handler).
5134 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5135 [ $this, $title, &$options, &$descQuery ] );
5136 # Don't register it now, as TraditionalImageGallery does that later.
5137 $file = $this->fetchFileNoRegister( $title, $options );
5138 $handler = $file ?
$file->getHandler() : false;
5141 'img_alt' => 'gallery-internal-alt',
5142 'img_link' => 'gallery-internal-link',
5145 $paramMap +
= $handler->getParamMap();
5146 // We don't want people to specify per-image widths.
5147 // Additionally the width parameter would need special casing anyhow.
5148 unset( $paramMap['img_width'] );
5151 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5156 $handlerOptions = [];
5157 if ( isset( $matches[3] ) ) {
5158 // look for an |alt= definition while trying not to break existing
5159 // captions with multiple pipes (|) in it, until a more sensible grammar
5160 // is defined for images in galleries
5162 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5163 // splitting on '|' is a bit odd, and different from makeImage.
5164 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5165 // Protect LanguageConverter markup
5166 $parameterMatches = StringUtils
::delimiterExplode(
5167 '-{', '}-', '|', $matches[3], true /* nested */
5170 foreach ( $parameterMatches as $parameterMatch ) {
5171 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5173 $paramName = $paramMap[$magicName];
5175 switch ( $paramName ) {
5176 case 'gallery-internal-alt':
5177 $alt = $this->stripAltText( $match, false );
5179 case 'gallery-internal-link':
5180 $linkValue = $this->stripAltText( $match, false );
5181 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5182 // Result of LanguageConverter::markNoConversion
5183 // invoked on an external link.
5184 $linkValue = substr( $linkValue, 4, -2 );
5186 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5187 if ( $type === 'link-url' ) {
5189 $this->mOutput
->addExternalLink( $target );
5190 } elseif ( $type === 'link-title' ) {
5191 $link = $target->getLinkURL();
5192 $this->mOutput
->addLink( $target );
5196 // Must be a handler specific parameter.
5197 if ( $handler->validateParam( $paramName, $match ) ) {
5198 $handlerOptions[$paramName] = $match;
5200 // Guess not, consider it as caption.
5201 wfDebug( "$parameterMatch failed parameter validation\n" );
5202 $label = $parameterMatch;
5208 $label = $parameterMatch;
5213 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5215 $html = $ig->toHTML();
5216 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5221 * @param MediaHandler $handler
5224 public function getImageParams( $handler ) {
5226 $handlerClass = get_class( $handler );
5230 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5231 # Initialise static lists
5232 static $internalParamNames = [
5233 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5234 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5235 'bottom', 'text-bottom' ],
5236 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5237 'upright', 'border', 'link', 'alt', 'class' ],
5239 static $internalParamMap;
5240 if ( !$internalParamMap ) {
5241 $internalParamMap = [];
5242 foreach ( $internalParamNames as $type => $names ) {
5243 foreach ( $names as $name ) {
5244 // For grep: img_left, img_right, img_center, img_none,
5245 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5246 // img_bottom, img_text_bottom,
5247 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5248 // img_border, img_link, img_alt, img_class
5249 $magicName = str_replace( '-', '_', "img_$name" );
5250 $internalParamMap[$magicName] = [ $type, $name ];
5255 # Add handler params
5256 $paramMap = $internalParamMap;
5258 $handlerParamMap = $handler->getParamMap();
5259 foreach ( $handlerParamMap as $magic => $paramName ) {
5260 $paramMap[$magic] = [ 'handler', $paramName ];
5263 $this->mImageParams
[$handlerClass] = $paramMap;
5264 $this->mImageParamsMagicArray
[$handlerClass] =
5265 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5267 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5271 * Parse image options text and use it to make an image
5273 * @param Title $title
5274 * @param string $options
5275 * @param LinkHolderArray|bool $holders
5276 * @return string HTML
5278 public function makeImage( $title, $options, $holders = false ) {
5279 # Check if the options text is of the form "options|alt text"
5281 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5282 # * left no resizing, just left align. label is used for alt= only
5283 # * right same, but right aligned
5284 # * none same, but not aligned
5285 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5286 # * center center the image
5287 # * frame Keep original image size, no magnify-button.
5288 # * framed Same as "frame"
5289 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5290 # * upright reduce width for upright images, rounded to full __0 px
5291 # * border draw a 1px border around the image
5292 # * alt Text for HTML alt attribute (defaults to empty)
5293 # * class Set a class for img node
5294 # * link Set the target of the image link. Can be external, interwiki, or local
5295 # vertical-align values (no % or length right now):
5305 # Protect LanguageConverter markup when splitting into parts
5306 $parts = StringUtils
::delimiterExplode(
5307 '-{', '}-', '|', $options, true /* allow nesting */
5310 # Give extensions a chance to select the file revision for us
5313 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5314 [ $this, $title, &$options, &$descQuery ] );
5315 # Fetch and register the file (file title may be different via hooks)
5316 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5319 $handler = $file ?
$file->getHandler() : false;
5321 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5324 $this->addTrackingCategory( 'broken-file-category' );
5327 # Process the input parameters
5329 $params = [ 'frame' => [], 'handler' => [],
5330 'horizAlign' => [], 'vertAlign' => [] ];
5331 $seenformat = false;
5332 foreach ( $parts as $part ) {
5333 $part = trim( $part );
5334 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5336 if ( isset( $paramMap[$magicName] ) ) {
5337 list( $type, $paramName ) = $paramMap[$magicName];
5339 # Special case; width and height come in one variable together
5340 if ( $type === 'handler' && $paramName === 'width' ) {
5341 $parsedWidthParam = self
::parseWidthParam( $value );
5342 if ( isset( $parsedWidthParam['width'] ) ) {
5343 $width = $parsedWidthParam['width'];
5344 if ( $handler->validateParam( 'width', $width ) ) {
5345 $params[$type]['width'] = $width;
5349 if ( isset( $parsedWidthParam['height'] ) ) {
5350 $height = $parsedWidthParam['height'];
5351 if ( $handler->validateParam( 'height', $height ) ) {
5352 $params[$type]['height'] = $height;
5356 # else no validation -- T15436
5358 if ( $type === 'handler' ) {
5359 # Validate handler parameter
5360 $validated = $handler->validateParam( $paramName, $value );
5362 # Validate internal parameters
5363 switch ( $paramName ) {
5367 # @todo FIXME: Possibly check validity here for
5368 # manualthumb? downstream behavior seems odd with
5369 # missing manual thumbs.
5371 $value = $this->stripAltText( $value, $holders );
5374 list( $paramName, $value ) =
5375 $this->parseLinkParameter(
5376 $this->stripAltText( $value, $holders )
5380 if ( $paramName === 'no-link' ) {
5383 if ( ( $paramName === 'link-url' ) && $this->mOptions
->getExternalLinkTarget() ) {
5384 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5391 // use first appearing option, discard others.
5392 $validated = !$seenformat;
5396 # Most other things appear to be empty or numeric...
5397 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5402 $params[$type][$paramName] = $value;
5406 if ( !$validated ) {
5411 # Process alignment parameters
5412 if ( $params['horizAlign'] ) {
5413 $params['frame']['align'] = key( $params['horizAlign'] );
5415 if ( $params['vertAlign'] ) {
5416 $params['frame']['valign'] = key( $params['vertAlign'] );
5419 $params['frame']['caption'] = $caption;
5421 # Will the image be presented in a frame, with the caption below?
5422 $imageIsFramed = isset( $params['frame']['frame'] )
5423 ||
isset( $params['frame']['framed'] )
5424 ||
isset( $params['frame']['thumbnail'] )
5425 ||
isset( $params['frame']['manualthumb'] );
5427 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5428 # came to also set the caption, ordinary text after the image -- which
5429 # makes no sense, because that just repeats the text multiple times in
5430 # screen readers. It *also* came to set the title attribute.
5431 # Now that we have an alt attribute, we should not set the alt text to
5432 # equal the caption: that's worse than useless, it just repeats the
5433 # text. This is the framed/thumbnail case. If there's no caption, we
5434 # use the unnamed parameter for alt text as well, just for the time be-
5435 # ing, if the unnamed param is set and the alt param is not.
5436 # For the future, we need to figure out if we want to tweak this more,
5437 # e.g., introducing a title= parameter for the title; ignoring the un-
5438 # named parameter entirely for images without a caption; adding an ex-
5439 # plicit caption= parameter and preserving the old magic unnamed para-
5441 if ( $imageIsFramed ) { # Framed image
5442 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5443 # No caption or alt text, add the filename as the alt text so
5444 # that screen readers at least get some description of the image
5445 $params['frame']['alt'] = $title->getText();
5447 # Do not set $params['frame']['title'] because tooltips don't make sense
5449 } else { # Inline image
5450 if ( !isset( $params['frame']['alt'] ) ) {
5451 # No alt text, use the "caption" for the alt text
5452 if ( $caption !== '' ) {
5453 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5455 # No caption, fall back to using the filename for the
5457 $params['frame']['alt'] = $title->getText();
5460 # Use the "caption" for the tooltip text
5461 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5463 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5465 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5467 # Linker does the rest
5468 $time = $options['time'] ??
false;
5469 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5470 $time, $descQuery, $this->mOptions
->getThumbSize() );
5472 # Give the handler a chance to modify the parser object
5474 $handler->parserTransformHook( $this, $file );
5481 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5483 * Adds an entry to appropriate link tables.
5486 * @param string $value
5487 * @return array of `[ type, target ]`, where:
5488 * - `type` is one of:
5489 * - `null`: Given value is not a valid link target, use default
5490 * - `'no-link'`: Given value is empty, do not generate a link
5491 * - `'link-url'`: Given value is a valid external link
5492 * - `'link-title'`: Given value is a valid internal link
5494 * - When `type` is `null` or `'no-link'`: `false`
5495 * - When `type` is `'link-url'`: URL string corresponding to given value
5496 * - When `type` is `'link-title'`: Title object corresponding to given value
5498 public function parseLinkParameter( $value ) {
5499 $chars = self
::EXT_LINK_URL_CLASS
;
5500 $addr = self
::EXT_LINK_ADDR
;
5501 $prots = $this->mUrlProtocols
;
5504 if ( $value === '' ) {
5506 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5507 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5508 $this->mOutput
->addExternalLink( $value );
5513 $linkTitle = Title
::newFromText( $value );
5515 $this->mOutput
->addLink( $linkTitle );
5516 $type = 'link-title';
5517 $target = $linkTitle;
5520 return [ $type, $target ];
5524 * @param string $caption
5525 * @param LinkHolderArray|bool $holders
5526 * @return mixed|string
5528 protected function stripAltText( $caption, $holders ) {
5529 # Strip bad stuff out of the title (tooltip). We can't just use
5530 # replaceLinkHoldersText() here, because if this function is called
5531 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5533 $tooltip = $holders->replaceText( $caption );
5535 $tooltip = $this->replaceLinkHoldersText( $caption );
5538 # make sure there are no placeholders in thumbnail attributes
5539 # that are later expanded to html- so expand them now and
5541 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5542 # Compatibility hack! In HTML certain entity references not terminated
5543 # by a semicolon are decoded (but not if we're in an attribute; that's
5544 # how link URLs get away without properly escaping & in queries).
5545 # But wikitext has always required semicolon-termination of entities,
5546 # so encode & where needed to avoid decode of semicolon-less entities.
5548 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5549 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5550 $tooltip = preg_replace( "/
5551 & # 1. entity prefix
5552 (?= # 2. followed by:
5553 (?: # a. one of the legacy semicolon-less named entities
5554 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5555 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5556 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5557 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5558 U(?:acute|circ|grave|uml)|Yacute|
5559 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5560 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5561 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5562 frac(?:1(?:2|4)|34)|
5563 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5564 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5565 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5566 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5567 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5568 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5569 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5570 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5571 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5573 (?:[^;]|$)) # b. and not followed by a semicolon
5574 # S = study, for efficiency
5575 /Sx", '&', $tooltip );
5576 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5582 * Set a flag in the output object indicating that the content is dynamic and
5583 * shouldn't be cached.
5584 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5586 public function disableCache() {
5587 wfDebug( "Parser output marked as uncacheable.\n" );
5588 if ( !$this->mOutput
) {
5589 throw new MWException( __METHOD__
.
5590 " can only be called when actually parsing something" );
5592 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5596 * Callback from the Sanitizer for expanding items found in HTML attribute
5597 * values, so they can be safely tested and escaped.
5599 * @param string &$text
5600 * @param bool|PPFrame $frame
5603 public function attributeStripCallback( &$text, $frame = false ) {
5604 $text = $this->replaceVariables( $text, $frame );
5605 $text = $this->mStripState
->unstripBoth( $text );
5614 public function getTags() {
5615 $this->firstCallInit();
5617 array_keys( $this->mTransparentTagHooks
),
5618 array_keys( $this->mTagHooks
),
5619 array_keys( $this->mFunctionTagHooks
)
5627 public function getFunctionSynonyms() {
5628 $this->firstCallInit();
5629 return $this->mFunctionSynonyms
;
5636 public function getUrlProtocols() {
5637 return $this->mUrlProtocols
;
5641 * Replace transparent tags in $text with the values given by the callbacks.
5643 * Transparent tag hooks are like regular XML-style tag hooks, except they
5644 * operate late in the transformation sequence, on HTML instead of wikitext.
5646 * @param string $text
5650 public function replaceTransparentTags( $text ) {
5652 $elements = array_keys( $this->mTransparentTagHooks
);
5653 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5656 foreach ( $matches as $marker => $data ) {
5657 list( $element, $content, $params, $tag ) = $data;
5658 $tagName = strtolower( $element );
5659 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5660 $output = call_user_func_array(
5661 $this->mTransparentTagHooks
[$tagName],
5662 [ $content, $params, $this ]
5667 $replacements[$marker] = $output;
5669 return strtr( $text, $replacements );
5673 * Break wikitext input into sections, and either pull or replace
5674 * some particular section's text.
5676 * External callers should use the getSection and replaceSection methods.
5678 * @param string $text Page wikitext
5679 * @param string|int $sectionId A section identifier string of the form:
5680 * "<flag1> - <flag2> - ... - <section number>"
5682 * Currently the only recognised flag is "T", which means the target section number
5683 * was derived during a template inclusion parse, in other words this is a template
5684 * section edit link. If no flags are given, it was an ordinary section edit link.
5685 * This flag is required to avoid a section numbering mismatch when a section is
5686 * enclosed by "<includeonly>" (T8563).
5688 * The section number 0 pulls the text before the first heading; other numbers will
5689 * pull the given section along with its lower-level subsections. If the section is
5690 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5692 * Section 0 is always considered to exist, even if it only contains the empty
5693 * string. If $text is the empty string and section 0 is replaced, $newText is
5696 * @param string $mode One of "get" or "replace"
5697 * @param string $newText Replacement text for section data.
5698 * @return string For "get", the extracted section text.
5699 * for "replace", the whole page with the section replaced.
5701 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5702 global $wgTitle; # not generally used but removes an ugly failure mode
5704 $magicScopeVariable = $this->lock();
5705 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5707 $frame = $this->getPreprocessor()->newFrame();
5709 # Process section extraction flags
5711 $sectionParts = explode( '-', $sectionId );
5712 $sectionIndex = array_pop( $sectionParts );
5713 foreach ( $sectionParts as $part ) {
5714 if ( $part === 'T' ) {
5715 $flags |
= self
::PTD_FOR_INCLUSION
;
5719 # Check for empty input
5720 if ( strval( $text ) === '' ) {
5721 # Only sections 0 and T-0 exist in an empty document
5722 if ( $sectionIndex == 0 ) {
5723 if ( $mode === 'get' ) {
5729 if ( $mode === 'get' ) {
5737 # Preprocess the text
5738 $root = $this->preprocessToDom( $text, $flags );
5740 # <h> nodes indicate section breaks
5741 # They can only occur at the top level, so we can find them by iterating the root's children
5742 $node = $root->getFirstChild();
5744 # Find the target section
5745 if ( $sectionIndex == 0 ) {
5746 # Section zero doesn't nest, level=big
5747 $targetLevel = 1000;
5750 if ( $node->getName() === 'h' ) {
5751 $bits = $node->splitHeading();
5752 if ( $bits['i'] == $sectionIndex ) {
5753 $targetLevel = $bits['level'];
5757 if ( $mode === 'replace' ) {
5758 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5760 $node = $node->getNextSibling();
5766 if ( $mode === 'get' ) {
5773 # Find the end of the section, including nested sections
5775 if ( $node->getName() === 'h' ) {
5776 $bits = $node->splitHeading();
5777 $curLevel = $bits['level'];
5778 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5782 if ( $mode === 'get' ) {
5783 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5785 $node = $node->getNextSibling();
5788 # Write out the remainder (in replace mode only)
5789 if ( $mode === 'replace' ) {
5790 # Output the replacement text
5791 # Add two newlines on -- trailing whitespace in $newText is conventionally
5792 # stripped by the editor, so we need both newlines to restore the paragraph gap
5793 # Only add trailing whitespace if there is newText
5794 if ( $newText != "" ) {
5795 $outText .= $newText . "\n\n";
5799 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5800 $node = $node->getNextSibling();
5804 if ( is_string( $outText ) ) {
5805 # Re-insert stripped tags
5806 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5813 * This function returns the text of a section, specified by a number ($section).
5814 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5815 * the first section before any such heading (section 0).
5817 * If a section contains subsections, these are also returned.
5819 * @param string $text Text to look in
5820 * @param string|int $sectionId Section identifier as a number or string
5821 * (e.g. 0, 1 or 'T-1').
5822 * @param string $defaultText Default to return if section is not found
5824 * @return string Text of the requested section
5826 public function getSection( $text, $sectionId, $defaultText = '' ) {
5827 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5831 * This function returns $oldtext after the content of the section
5832 * specified by $section has been replaced with $text. If the target
5833 * section does not exist, $oldtext is returned unchanged.
5835 * @param string $oldText Former text of the article
5836 * @param string|int $sectionId Section identifier as a number or string
5837 * (e.g. 0, 1 or 'T-1').
5838 * @param string $newText Replacing text
5840 * @return string Modified text
5842 public function replaceSection( $oldText, $sectionId, $newText ) {
5843 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5847 * Get the ID of the revision we are parsing
5849 * The return value will be either:
5850 * - a) Positive, indicating a specific revision ID (current or old)
5851 * - b) Zero, meaning the revision ID specified by getCurrentRevisionCallback()
5852 * - c) Null, meaning the parse is for preview mode and there is no revision
5856 public function getRevisionId() {
5857 return $this->mRevisionId
;
5861 * Get the revision object for $this->mRevisionId
5863 * @return Revision|null Either a Revision object or null
5864 * @since 1.23 (public since 1.23)
5866 public function getRevisionObject() {
5867 if ( !is_null( $this->mRevisionObject
) ) {
5868 return $this->mRevisionObject
;
5871 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5872 // This is useful when parsing revision that has not yet been saved.
5873 // However, if we get back a saved revision even though we are in
5874 // preview mode, we'll have to ignore it, see below.
5875 // NOTE: This callback may be used to inject an OLD revision that was
5876 // already loaded, so "current" is a bit of a misnomer. We can't just
5877 // skip it if mRevisionId is set.
5878 $rev = call_user_func(
5879 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5882 if ( $this->mRevisionId
=== null && $rev && $rev->getId() ) {
5883 // We are in preview mode (mRevisionId is null), and the current revision callback
5884 // returned an existing revision. Ignore it and return null, it's probably the page's
5885 // current revision, which is not what we want here. Note that we do want to call the
5886 // callback to allow the unsaved revision to be injected here, e.g. for
5887 // self-transclusion previews.
5891 // If the parse is for a new revision, then the callback should have
5892 // already been set to force the object and should match mRevisionId.
5893 // If not, try to fetch by mRevisionId for sanity.
5894 if ( $this->mRevisionId
&& $rev && $rev->getId() != $this->mRevisionId
) {
5895 $rev = Revision
::newFromId( $this->mRevisionId
);
5898 $this->mRevisionObject
= $rev;
5900 return $this->mRevisionObject
;
5904 * Get the timestamp associated with the current revision, adjusted for
5905 * the default server-local timestamp
5908 public function getRevisionTimestamp() {
5909 if ( is_null( $this->mRevisionTimestamp
) ) {
5910 $revObject = $this->getRevisionObject();
5911 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5913 # The cryptic '' timezone parameter tells to use the site-default
5914 # timezone offset instead of the user settings.
5915 # Since this value will be saved into the parser cache, served
5916 # to other users, and potentially even used inside links and such,
5917 # it needs to be consistent for all visitors.
5918 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
5920 return $this->mRevisionTimestamp
;
5924 * Get the name of the user that edited the last revision
5926 * @return string User name
5928 public function getRevisionUser() {
5929 if ( is_null( $this->mRevisionUser
) ) {
5930 $revObject = $this->getRevisionObject();
5932 # if this template is subst: the revision id will be blank,
5933 # so just use the current user's name
5935 $this->mRevisionUser
= $revObject->getUserText();
5936 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5937 $this->mRevisionUser
= $this->getUser()->getName();
5940 return $this->mRevisionUser
;
5944 * Get the size of the revision
5946 * @return int|null Revision size
5948 public function getRevisionSize() {
5949 if ( is_null( $this->mRevisionSize
) ) {
5950 $revObject = $this->getRevisionObject();
5952 # if this variable is subst: the revision id will be blank,
5953 # so just use the parser input size, because the own substituation
5954 # will change the size.
5956 $this->mRevisionSize
= $revObject->getSize();
5958 $this->mRevisionSize
= $this->mInputSize
;
5961 return $this->mRevisionSize
;
5965 * Mutator for $mDefaultSort
5967 * @param string $sort New value
5969 public function setDefaultSort( $sort ) {
5970 $this->mDefaultSort
= $sort;
5971 $this->mOutput
->setProperty( 'defaultsort', $sort );
5975 * Accessor for $mDefaultSort
5976 * Will use the empty string if none is set.
5978 * This value is treated as a prefix, so the
5979 * empty string is equivalent to sorting by
5984 public function getDefaultSort() {
5985 if ( $this->mDefaultSort
!== false ) {
5986 return $this->mDefaultSort
;
5993 * Accessor for $mDefaultSort
5994 * Unlike getDefaultSort(), will return false if none is set
5996 * @return string|bool
5998 public function getCustomDefaultSort() {
5999 return $this->mDefaultSort
;
6002 private static function getSectionNameFromStrippedText( $text ) {
6003 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6004 $text = Sanitizer
::decodeCharReferences( $text );
6005 $text = self
::normalizeSectionName( $text );
6009 private static function makeAnchor( $sectionName ) {
6010 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
6013 private function makeLegacyAnchor( $sectionName ) {
6014 $fragmentMode = $this->siteConfig
->get( 'FragmentMode' );
6015 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
6016 // ForAttribute() and ForLink() are the same for legacy encoding
6017 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
6019 $id = Sanitizer
::escapeIdForLink( $sectionName );
6026 * Try to guess the section anchor name based on a wikitext fragment
6027 * presumably extracted from a heading, for example "Header" from
6030 * @param string $text
6031 * @return string Anchor (starting with '#')
6033 public function guessSectionNameFromWikiText( $text ) {
6034 # Strip out wikitext links(they break the anchor)
6035 $text = $this->stripSectionName( $text );
6036 $sectionName = self
::getSectionNameFromStrippedText( $text );
6037 return self
::makeAnchor( $sectionName );
6041 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6042 * instead, if possible. For use in redirects, since various versions
6043 * of Microsoft browsers interpret Location: headers as something other
6044 * than UTF-8, resulting in breakage.
6046 * @param string $text The section name
6047 * @return string Anchor (starting with '#')
6049 public function guessLegacySectionNameFromWikiText( $text ) {
6050 # Strip out wikitext links(they break the anchor)
6051 $text = $this->stripSectionName( $text );
6052 $sectionName = self
::getSectionNameFromStrippedText( $text );
6053 return $this->makeLegacyAnchor( $sectionName );
6057 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6058 * @param string $text Section name (plain text)
6059 * @return string Anchor (starting with '#')
6061 public static function guessSectionNameFromStrippedText( $text ) {
6062 $sectionName = self
::getSectionNameFromStrippedText( $text );
6063 return self
::makeAnchor( $sectionName );
6067 * Apply the same normalization as code making links to this section would
6069 * @param string $text
6072 private static function normalizeSectionName( $text ) {
6073 # T90902: ensure the same normalization is applied for IDs as to links
6074 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
6077 $parts = $titleParser->splitTitleString( "#$text" );
6078 } catch ( MalformedTitleException
$ex ) {
6081 return $parts['fragment'];
6085 * Strips a text string of wikitext for use in a section anchor
6087 * Accepts a text string and then removes all wikitext from the
6088 * string and leaves only the resultant text (i.e. the result of
6089 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6090 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6091 * to create valid section anchors by mimicing the output of the
6092 * parser when headings are parsed.
6094 * @param string $text Text string to be stripped of wikitext
6095 * for use in a Section anchor
6096 * @return string Filtered text string
6098 public function stripSectionName( $text ) {
6099 # Strip internal link markup
6100 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6101 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6103 # Strip external link markup
6104 # @todo FIXME: Not tolerant to blank link text
6105 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6106 # on how many empty links there are on the page - need to figure that out.
6107 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6109 # Parse wikitext quotes (italics & bold)
6110 $text = $this->doQuotes( $text );
6113 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6118 * strip/replaceVariables/unstrip for preprocessor regression testing
6120 * @param string $text
6121 * @param Title $title
6122 * @param ParserOptions $options
6123 * @param int $outputType
6127 public function testSrvus( $text, Title
$title, ParserOptions
$options,
6128 $outputType = self
::OT_HTML
6130 $magicScopeVariable = $this->lock();
6131 $this->startParse( $title, $options, $outputType, true );
6133 $text = $this->replaceVariables( $text );
6134 $text = $this->mStripState
->unstripBoth( $text );
6135 $text = Sanitizer
::removeHTMLtags( $text );
6140 * @param string $text
6141 * @param Title $title
6142 * @param ParserOptions $options
6145 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6146 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6150 * @param string $text
6151 * @param Title $title
6152 * @param ParserOptions $options
6155 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6156 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6160 * Call a callback function on all regions of the given text that are not
6161 * inside strip markers, and replace those regions with the return value
6162 * of the callback. For example, with input:
6166 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6167 * two strings will be replaced with the value returned by the callback in
6171 * @param callable $callback
6175 public function markerSkipCallback( $s, $callback ) {
6178 while ( $i < strlen( $s ) ) {
6179 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6180 if ( $markerStart === false ) {
6181 $out .= call_user_func( $callback, substr( $s, $i ) );
6184 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6185 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6186 if ( $markerEnd === false ) {
6187 $out .= substr( $s, $markerStart );
6190 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6191 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6200 * Remove any strip markers found in the given text.
6202 * @param string $text
6205 public function killMarkers( $text ) {
6206 return $this->mStripState
->killMarkers( $text );
6210 * Save the parser state required to convert the given half-parsed text to
6211 * HTML. "Half-parsed" in this context means the output of
6212 * recursiveTagParse() or internalParse(). This output has strip markers
6213 * from replaceVariables (extensionSubstitution() etc.), and link
6214 * placeholders from replaceLinkHolders().
6216 * Returns an array which can be serialized and stored persistently. This
6217 * array can later be loaded into another parser instance with
6218 * unserializeHalfParsedText(). The text can then be safely incorporated into
6219 * the return value of a parser hook.
6221 * @deprecated since 1.31
6222 * @param string $text
6226 public function serializeHalfParsedText( $text ) {
6227 wfDeprecated( __METHOD__
, '1.31' );
6230 'version' => self
::HALF_PARSED_VERSION
,
6231 'stripState' => $this->mStripState
->getSubState( $text ),
6232 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6238 * Load the parser state given in the $data array, which is assumed to
6239 * have been generated by serializeHalfParsedText(). The text contents is
6240 * extracted from the array, and its markers are transformed into markers
6241 * appropriate for the current Parser instance. This transformed text is
6242 * returned, and can be safely included in the return value of a parser
6245 * If the $data array has been stored persistently, the caller should first
6246 * check whether it is still valid, by calling isValidHalfParsedText().
6248 * @deprecated since 1.31
6249 * @param array $data Serialized data
6250 * @throws MWException
6253 public function unserializeHalfParsedText( $data ) {
6254 wfDeprecated( __METHOD__
, '1.31' );
6255 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6256 throw new MWException( __METHOD__
. ': invalid version' );
6259 # First, extract the strip state.
6260 $texts = [ $data['text'] ];
6261 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6263 # Now renumber links
6264 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6266 # Should be good to go.
6271 * Returns true if the given array, presumed to be generated by
6272 * serializeHalfParsedText(), is compatible with the current version of the
6275 * @deprecated since 1.31
6276 * @param array $data
6280 public function isValidHalfParsedText( $data ) {
6281 wfDeprecated( __METHOD__
, '1.31' );
6282 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6286 * Parsed a width param of imagelink like 300px or 200x300px
6288 * @param string $value
6289 * @param bool $parseHeight
6294 public static function parseWidthParam( $value, $parseHeight = true ) {
6295 $parsedWidthParam = [];
6296 if ( $value === '' ) {
6297 return $parsedWidthParam;
6300 # (T15500) In both cases (width/height and width only),
6301 # permit trailing "px" for backward compatibility.
6302 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6303 $width = intval( $m[1] );
6304 $height = intval( $m[2] );
6305 $parsedWidthParam['width'] = $width;
6306 $parsedWidthParam['height'] = $height;
6307 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6308 $width = intval( $value );
6309 $parsedWidthParam['width'] = $width;
6311 return $parsedWidthParam;
6315 * Lock the current instance of the parser.
6317 * This is meant to stop someone from calling the parser
6318 * recursively and messing up all the strip state.
6320 * @throws MWException If parser is in a parse
6321 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6323 protected function lock() {
6324 if ( $this->mInParse
) {
6325 throw new MWException( "Parser state cleared while parsing. "
6326 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6329 // Save the backtrace when locking, so that if some code tries locking again,
6330 // we can print the lock owner's backtrace for easier debugging
6332 $this->mInParse
= $e->getTraceAsString();
6334 $recursiveCheck = new ScopedCallback( function () {
6335 $this->mInParse
= false;
6338 return $recursiveCheck;
6342 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6344 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6345 * or if there is more than one <p/> tag in the input HTML.
6347 * @param string $html
6351 public static function stripOuterParagraph( $html ) {
6353 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '</p>' ) === false ) {
6361 * Return this parser if it is not doing anything, otherwise
6362 * get a fresh parser. You can use this method by doing
6363 * $newParser = $oldParser->getFreshParser(), or more simply
6364 * $oldParser->getFreshParser()->parse( ... );
6365 * if you're unsure if $oldParser is safe to use.
6368 * @return Parser A parser object that is not parsing anything
6370 public function getFreshParser() {
6371 if ( $this->mInParse
) {
6372 return $this->factory
->create();
6379 * Set's up the PHP implementation of OOUI for use in this request
6380 * and instructs OutputPage to enable OOUI for itself.
6384 public function enableOOUI() {
6385 OutputPage
::setupOOUI();
6386 $this->mOutput
->setEnableOOUI( true );