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\MediaWikiServices
;
26 use MediaWiki\Special\SpecialPageFactory
;
27 use Wikimedia\ScopedCallback
;
30 * @defgroup Parser Parser
34 * PHP Parser - Processes wiki markup (which uses a more user-friendly
35 * syntax, such as "[[link]]" for making links), and provides a one-way
36 * transformation of that wiki markup it into (X)HTML output / markup
37 * (which in turn the browser understands, and can display).
39 * There are seven main entry points into the Parser class:
42 * produces HTML output
43 * - Parser::preSaveTransform()
44 * produces altered wiki markup
45 * - Parser::preprocess()
46 * removes HTML comments and expands templates
47 * - Parser::cleanSig() and Parser::cleanSigInSig()
48 * cleans a signature before saving it to preferences
49 * - Parser::getSection()
50 * return the content of a section from an article for section editing
51 * - Parser::replaceSection()
52 * replaces a section by number inside an article
53 * - Parser::getPreloadText()
54 * removes <noinclude> sections and <includeonly> tags
56 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
59 * $wgNamespacesWithSubpages
61 * @par Settings only within ParserOptions:
62 * $wgAllowExternalImages
63 * $wgAllowSpecialInclusion
71 * Update this version number when the ParserOutput format
72 * changes in an incompatible way, so the parser cache
73 * can automatically discard old data.
75 const VERSION
= '1.6.4';
78 * Update this version number when the output of serialiseHalfParsedText()
79 * changes in an incompatible way
81 const HALF_PARSED_VERSION
= 2;
83 # Flags for Parser::setFunctionHook
84 const SFH_NO_HASH
= 1;
85 const SFH_OBJECT_ARGS
= 2;
87 # Constants needed for external link processing
88 # Everything except bracket, space, or control characters
89 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
90 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
91 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
92 # uses to replace invalid HTML characters.
93 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
94 # Simplified expression to match an IPv4 or IPv6 address, or
95 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
96 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
97 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
98 // phpcs:ignore Generic.Files.LineLength
99 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
100 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
102 # Regular expression for a non-newline space
103 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
105 # Flags for preprocessToDom
106 const PTD_FOR_INCLUSION
= 1;
108 # Allowed values for $this->mOutputType
109 # Parameter to startExternalParse().
110 const OT_HTML
= 1; # like parse()
111 const OT_WIKI
= 2; # like preSaveTransform()
112 const OT_PREPROCESS
= 3; # like preprocess()
114 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
117 * @var string Prefix and suffix for temporary replacement strings
118 * for the multipass parser.
120 * \x7f should never appear in input as it's disallowed in XML.
121 * Using it at the front also gives us a little extra robustness
122 * since it shouldn't match when butted up against identifier-like
125 * Must not consist of all title characters, or else it will change
126 * the behavior of <nowiki> in a link.
128 * Must have a character that needs escaping in attributes, otherwise
129 * someone could put a strip marker in an attribute, to get around
130 * escaping quote marks, and break out of the attribute. Thus we add
133 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
134 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
136 # Markers used for wrapping the table of contents
137 const TOC_START
= '<mw:toc>';
138 const TOC_END
= '</mw:toc>';
140 /** @var int Assume that no output will later be saved this many seconds after parsing */
144 public $mTagHooks = [];
145 public $mTransparentTagHooks = [];
146 public $mFunctionHooks = [];
147 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
148 public $mFunctionTagHooks = [];
149 public $mStripList = [];
150 public $mDefaultStripList = [];
151 public $mVarCache = [];
152 public $mImageParams = [];
153 public $mImageParamsMagicArray = [];
154 public $mMarkerIndex = 0;
156 * @var bool Whether firstCallInit still needs to be called
158 public $mFirstCall = true;
160 # Initialised by initialiseVariables()
163 * @var MagicWordArray
168 * @var MagicWordArray
171 # Initialised in constructor
172 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
174 # Initialized in getPreprocessor()
175 /** @var Preprocessor */
176 public $mPreprocessor;
178 # Cleared with clearState():
190 public $mIncludeCount;
192 * @var LinkHolderArray
194 public $mLinkHolders;
197 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
198 public $mDefaultSort;
199 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
200 public $mExpensiveFunctionCount; # number of expensive parser function calls
201 public $mShowToc, $mForceTocPosition;
206 public $mUser; # User object; only used when doing pre-save transform
209 # These are variables reset at least once per parse regardless of $clearState
219 public $mTitle; # Title context, used for self-link rendering and similar things
220 public $mOutputType; # Output type, one of the OT_xxx constants
221 public $ot; # Shortcut alias, see setOutputType()
222 public $mRevisionObject; # The revision object of the specified revision ID
223 public $mRevisionId; # ID to display in {{REVISIONID}} tags
224 public $mRevisionTimestamp; # The timestamp of the specified revision ID
225 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
226 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
227 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
228 public $mInputSize = false; # For {{PAGESIZE}} on current page.
231 * @var string Deprecated accessor for the strip marker prefix.
232 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
234 public $mUniqPrefix = self
::MARKER_PREFIX
;
237 * @var array Array with the language name of each language link (i.e. the
238 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
239 * duplicate language links to the ParserOutput.
241 public $mLangLinkLanguages;
244 * @var MapCacheLRU|null
247 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
249 public $currentRevisionCache;
252 * @var bool|string Recursive call protection.
253 * This variable should be treated as if it were private.
255 public $mInParse = false;
257 /** @var SectionProfiler */
258 protected $mProfiler;
263 protected $mLinkRenderer;
265 /** @var MagicWordFactory */
266 private $magicWordFactory;
271 /** @var ParserFactory */
274 /** @var SpecialPageFactory */
275 private $specialPageFactory;
280 /** @var LinkRendererFactory */
281 private $linkRendererFactory;
283 /** @var NamespaceInfo */
287 * @param array $parserConf See $wgParserConf documentation
288 * @param MagicWordFactory|null $magicWordFactory
289 * @param Language|null $contLang Content language
290 * @param ParserFactory|null $factory
291 * @param string|null $urlProtocols As returned from wfUrlProtocols()
292 * @param SpecialPageFactory|null $spFactory
293 * @param Config|null $siteConfig
294 * @param LinkRendererFactory|null $linkRendererFactory
295 * @param NamespaceInfo|null $nsInfo
297 public function __construct(
298 array $parserConf = [], MagicWordFactory
$magicWordFactory = null,
299 Language
$contLang = null, ParserFactory
$factory = null, $urlProtocols = null,
300 SpecialPageFactory
$spFactory = null, Config
$siteConfig = null,
301 LinkRendererFactory
$linkRendererFactory = null,
302 NamespaceInfo
$nsInfo = null
304 $this->mConf
= $parserConf;
305 $this->mUrlProtocols
= $urlProtocols ??
wfUrlProtocols();
306 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
307 self
::EXT_LINK_ADDR
.
308 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
309 if ( isset( $parserConf['preprocessorClass'] ) ) {
310 $this->mPreprocessorClass
= $parserConf['preprocessorClass'];
311 } elseif ( wfIsHHVM() ) {
312 # Under HHVM Preprocessor_Hash is much faster than Preprocessor_DOM
313 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
314 } elseif ( extension_loaded( 'domxml' ) ) {
315 # PECL extension that conflicts with the core DOM extension (T15770)
316 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
317 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
318 } elseif ( extension_loaded( 'dom' ) ) {
319 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
321 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
323 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
325 $services = MediaWikiServices
::getInstance();
326 $this->magicWordFactory
= $magicWordFactory ??
327 $services->getMagicWordFactory();
329 $this->contLang
= $contLang ??
$services->getContentLanguage();
331 $this->factory
= $factory ??
$services->getParserFactory();
332 $this->specialPageFactory
= $spFactory ??
$services->getSpecialPageFactory();
333 $this->siteConfig
= $siteConfig ??
$services->getMainConfig();
334 $this->linkRendererFactory
=
335 $linkRendererFactory ??
$services->getLinkRendererFactory();
336 $this->nsInfo
= $nsInfo ??
$services->getNamespaceInfo();
340 * Reduce memory usage to reduce the impact of circular references
342 public function __destruct() {
343 if ( isset( $this->mLinkHolders
) ) {
344 unset( $this->mLinkHolders
);
346 foreach ( $this as $name => $value ) {
347 unset( $this->$name );
352 * Allow extensions to clean up when the parser is cloned
354 public function __clone() {
355 $this->mInParse
= false;
357 // T58226: When you create a reference "to" an object field, that
358 // makes the object field itself be a reference too (until the other
359 // reference goes out of scope). When cloning, any field that's a
360 // reference is copied as a reference in the new object. Both of these
361 // are defined PHP5 behaviors, as inconvenient as it is for us when old
362 // hooks from PHP4 days are passing fields by reference.
363 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
364 // Make a non-reference copy of the field, then rebind the field to
365 // reference the new copy.
371 Hooks
::run( 'ParserCloned', [ $this ] );
375 * Do various kinds of initialisation on the first call of the parser
377 public function firstCallInit() {
378 if ( !$this->mFirstCall
) {
381 $this->mFirstCall
= false;
383 CoreParserFunctions
::register( $this );
384 CoreTagHooks
::register( $this );
385 $this->initialiseVariables();
387 // Avoid PHP 7.1 warning from passing $this by reference
389 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
397 public function clearState() {
398 $this->firstCallInit();
399 $this->mOutput
= new ParserOutput
;
400 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
401 $this->mAutonumber
= 0;
402 $this->mIncludeCount
= [];
403 $this->mLinkHolders
= new LinkHolderArray( $this );
405 $this->mRevisionObject
= $this->mRevisionTimestamp
=
406 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
407 $this->mVarCache
= [];
409 $this->mLangLinkLanguages
= [];
410 $this->currentRevisionCache
= null;
412 $this->mStripState
= new StripState( $this );
414 # Clear these on every parse, T6549
415 $this->mTplRedirCache
= $this->mTplDomCache
= [];
417 $this->mShowToc
= true;
418 $this->mForceTocPosition
= false;
419 $this->mIncludeSizes
= [
423 $this->mPPNodeCount
= 0;
424 $this->mGeneratedPPNodeCount
= 0;
425 $this->mHighestExpansionDepth
= 0;
426 $this->mDefaultSort
= false;
427 $this->mHeadings
= [];
428 $this->mDoubleUnderscores
= [];
429 $this->mExpensiveFunctionCount
= 0;
432 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
433 $this->mPreprocessor
= null;
436 $this->mProfiler
= new SectionProfiler();
438 // Avoid PHP 7.1 warning from passing $this by reference
440 Hooks
::run( 'ParserClearState', [ &$parser ] );
444 * Convert wikitext to HTML
445 * Do not call this function recursively.
447 * @param string $text Text we want to parse
448 * @param-taint $text escapes_htmlnoent
449 * @param Title $title
450 * @param ParserOptions $options
451 * @param bool $linestart
452 * @param bool $clearState
453 * @param int|null $revid Number to pass in {{REVISIONID}}
454 * @return ParserOutput A ParserOutput
455 * @return-taint escaped
457 public function parse(
458 $text, Title
$title, ParserOptions
$options,
459 $linestart = true, $clearState = true, $revid = null
462 // We use U+007F DELETE to construct strip markers, so we have to make
463 // sure that this character does not occur in the input text.
464 $text = strtr( $text, "\x7f", "?" );
465 $magicScopeVariable = $this->lock();
467 // Strip U+0000 NULL (T159174)
468 $text = str_replace( "\000", '', $text );
470 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
472 $this->currentRevisionCache
= null;
473 $this->mInputSize
= strlen( $text );
474 if ( $this->mOptions
->getEnableLimitReport() ) {
475 $this->mOutput
->resetParseStartTime();
478 $oldRevisionId = $this->mRevisionId
;
479 $oldRevisionObject = $this->mRevisionObject
;
480 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
481 $oldRevisionUser = $this->mRevisionUser
;
482 $oldRevisionSize = $this->mRevisionSize
;
483 if ( $revid !== null ) {
484 $this->mRevisionId
= $revid;
485 $this->mRevisionObject
= null;
486 $this->mRevisionTimestamp
= null;
487 $this->mRevisionUser
= null;
488 $this->mRevisionSize
= null;
491 // Avoid PHP 7.1 warning from passing $this by reference
493 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
495 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
496 $text = $this->internalParse( $text );
497 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
499 $text = $this->internalParseHalfParsed( $text, true, $linestart );
502 * A converted title will be provided in the output object if title and
503 * content conversion are enabled, the article text does not contain
504 * a conversion-suppressing double-underscore tag, and no
505 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
506 * automatic link conversion.
508 if ( !( $options->getDisableTitleConversion()
509 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
510 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
511 ||
$this->mOutput
->getDisplayTitle() !== false )
513 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
514 if ( $convruletitle ) {
515 $this->mOutput
->setTitleText( $convruletitle );
517 $titleText = $this->getTargetLanguage()->convertTitle( $title );
518 $this->mOutput
->setTitleText( $titleText );
522 # Compute runtime adaptive expiry if set
523 $this->mOutput
->finalizeAdaptiveCacheExpiry();
525 # Warn if too many heavyweight parser functions were used
526 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
527 $this->limitationWarn( 'expensive-parserfunction',
528 $this->mExpensiveFunctionCount
,
529 $this->mOptions
->getExpensiveParserFunctionLimit()
533 # Information on limits, for the benefit of users who try to skirt them
534 if ( $this->mOptions
->getEnableLimitReport() ) {
535 $text .= $this->makeLimitReport();
538 # Wrap non-interface parser output in a <div> so it can be targeted
540 $class = $this->mOptions
->getWrapOutputClass();
541 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
542 $this->mOutput
->addWrapperDivClass( $class );
545 $this->mOutput
->setText( $text );
547 $this->mRevisionId
= $oldRevisionId;
548 $this->mRevisionObject
= $oldRevisionObject;
549 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
550 $this->mRevisionUser
= $oldRevisionUser;
551 $this->mRevisionSize
= $oldRevisionSize;
552 $this->mInputSize
= false;
553 $this->currentRevisionCache
= null;
555 return $this->mOutput
;
559 * Set the limit report data in the current ParserOutput, and return the
560 * limit report HTML comment.
564 protected function makeLimitReport() {
565 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
567 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
568 if ( $cpuTime !== null ) {
569 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
570 sprintf( "%.3f", $cpuTime )
574 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
575 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
576 sprintf( "%.3f", $wallTime )
579 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
580 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
582 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
583 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
585 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
586 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
588 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
589 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
591 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
592 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
594 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
595 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
598 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
599 $this->mOutput
->setLimitReportData( $key, $value );
602 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
604 $limitReport = "NewPP limit report\n";
605 if ( $this->siteConfig
->get( 'ShowHostnames' ) ) {
606 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
608 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
609 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
610 $limitReport .= 'Dynamic content: ' .
611 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
614 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
615 if ( Hooks
::run( 'ParserLimitReportFormat',
616 [ $key, &$value, &$limitReport, false, false ]
618 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
619 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
620 ->inLanguage( 'en' )->useDatabase( false );
621 if ( !$valueMsg->exists() ) {
622 $valueMsg = new RawMessage( '$1' );
624 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
625 $valueMsg->params( $value );
626 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
630 // Since we're not really outputting HTML, decode the entities and
631 // then re-encode the things that need hiding inside HTML comments.
632 $limitReport = htmlspecialchars_decode( $limitReport );
634 // Sanitize for comment. Note '‐' in the replacement is U+2010,
635 // which looks much like the problematic '-'.
636 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
637 $text = "\n<!-- \n$limitReport-->\n";
639 // Add on template profiling data in human/machine readable way
640 $dataByFunc = $this->mProfiler
->getFunctionStats();
641 uasort( $dataByFunc, function ( $a, $b ) {
642 return $b['real'] <=> $a['real']; // descending order
645 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
646 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
647 $item['%real'], $item['real'], $item['calls'],
648 htmlspecialchars( $item['name'] ) );
650 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
651 $text .= implode( "\n", $profileReport ) . "\n-->\n";
653 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
655 // Add other cache related metadata
656 if ( $this->siteConfig
->get( 'ShowHostnames' ) ) {
657 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
659 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
660 $this->mOutput
->getCacheTime() );
661 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
662 $this->mOutput
->getCacheExpiry() );
663 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
664 $this->mOutput
->hasDynamicContent() );
666 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
667 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
668 $this->mTitle
->getPrefixedDBkey() );
674 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
675 * can be called from an extension tag hook.
677 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
678 * instead, which means that lists and links have not been fully parsed yet,
679 * and strip markers are still present.
681 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
683 * Use this function if you're a parser tag hook and you want to parse
684 * wikitext before or after applying additional transformations, and you
685 * intend to *return the result as hook output*, which will cause it to go
686 * through the rest of parsing process automatically.
688 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
689 * $text are not expanded
691 * @param string $text Text extension wants to have parsed
692 * @param-taint $text escapes_htmlnoent
693 * @param bool|PPFrame $frame The frame to use for expanding any template variables
694 * @return string UNSAFE half-parsed HTML
695 * @return-taint escaped
697 public function recursiveTagParse( $text, $frame = false ) {
698 // Avoid PHP 7.1 warning from passing $this by reference
700 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
701 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
702 $text = $this->internalParse( $text, false, $frame );
707 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
708 * point can be called from an extension tag hook.
710 * The output of this function is fully-parsed HTML that is safe for output.
711 * If you're a parser tag hook, you might want to use recursiveTagParse()
714 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
715 * $text are not expanded
719 * @param string $text Text extension wants to have parsed
720 * @param-taint $text escapes_htmlnoent
721 * @param bool|PPFrame $frame The frame to use for expanding any template variables
722 * @return string Fully parsed HTML
723 * @return-taint escaped
725 public function recursiveTagParseFully( $text, $frame = false ) {
726 $text = $this->recursiveTagParse( $text, $frame );
727 $text = $this->internalParseHalfParsed( $text, false );
732 * Expand templates and variables in the text, producing valid, static wikitext.
733 * Also removes comments.
734 * Do not call this function recursively.
735 * @param string $text
736 * @param Title|null $title
737 * @param ParserOptions $options
738 * @param int|null $revid
739 * @param bool|PPFrame $frame
740 * @return mixed|string
742 public function preprocess( $text, Title
$title = null,
743 ParserOptions
$options, $revid = null, $frame = false
745 $magicScopeVariable = $this->lock();
746 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
747 if ( $revid !== null ) {
748 $this->mRevisionId
= $revid;
750 // Avoid PHP 7.1 warning from passing $this by reference
752 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
753 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
754 $text = $this->replaceVariables( $text, $frame );
755 $text = $this->mStripState
->unstripBoth( $text );
760 * Recursive parser entry point that can be called from an extension tag
763 * @param string $text Text to be expanded
764 * @param bool|PPFrame $frame The frame to use for expanding any template variables
768 public function recursivePreprocess( $text, $frame = false ) {
769 $text = $this->replaceVariables( $text, $frame );
770 $text = $this->mStripState
->unstripBoth( $text );
775 * Process the wikitext for the "?preload=" feature. (T7210)
777 * "<noinclude>", "<includeonly>" etc. are parsed as for template
778 * transclusion, comments, templates, arguments, tags hooks and parser
779 * functions are untouched.
781 * @param string $text
782 * @param Title $title
783 * @param ParserOptions $options
784 * @param array $params
787 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
788 $msg = new RawMessage( $text );
789 $text = $msg->params( $params )->plain();
791 # Parser (re)initialisation
792 $magicScopeVariable = $this->lock();
793 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
795 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
796 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
797 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
798 $text = $this->mStripState
->unstripBoth( $text );
803 * Set the current user.
804 * Should only be used when doing pre-save transform.
806 * @param User|null $user User object or null (to reset)
808 public function setUser( $user ) {
809 $this->mUser
= $user;
813 * Set the context title
817 public function setTitle( $t ) {
819 $t = Title
::newFromText( 'NO TITLE' );
822 if ( $t->hasFragment() ) {
823 # Strip the fragment to avoid various odd effects
824 $this->mTitle
= $t->createFragmentTarget( '' );
831 * Accessor for the Title object
835 public function getTitle() {
836 return $this->mTitle
;
840 * Accessor/mutator for the Title object
842 * @param Title|null $x Title object or null to just get the current one
845 public function Title( $x = null ) {
846 return wfSetVar( $this->mTitle
, $x );
850 * Set the output type
852 * @param int $ot New value
854 public function setOutputType( $ot ) {
855 $this->mOutputType
= $ot;
858 'html' => $ot == self
::OT_HTML
,
859 'wiki' => $ot == self
::OT_WIKI
,
860 'pre' => $ot == self
::OT_PREPROCESS
,
861 'plain' => $ot == self
::OT_PLAIN
,
866 * Accessor/mutator for the output type
868 * @param int|null $x New value or null to just get the current one
871 public function OutputType( $x = null ) {
872 return wfSetVar( $this->mOutputType
, $x );
876 * Get the ParserOutput object
878 * @return ParserOutput
880 public function getOutput() {
881 return $this->mOutput
;
885 * Get the ParserOptions object
887 * @return ParserOptions
889 public function getOptions() {
890 return $this->mOptions
;
894 * Accessor/mutator for the ParserOptions object
896 * @param ParserOptions|null $x New value or null to just get the current one
897 * @return ParserOptions Current ParserOptions object
899 public function Options( $x = null ) {
900 return wfSetVar( $this->mOptions
, $x );
906 public function nextLinkID() {
907 return $this->mLinkID++
;
913 public function setLinkID( $id ) {
914 $this->mLinkID
= $id;
918 * Get a language object for use in parser functions such as {{FORMATNUM:}}
921 public function getFunctionLang() {
922 return $this->getTargetLanguage();
926 * Get the target language for the content being parsed. This is usually the
927 * language that the content is in.
931 * @throws MWException
934 public function getTargetLanguage() {
935 $target = $this->mOptions
->getTargetLanguage();
937 if ( $target !== null ) {
939 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
940 return $this->mOptions
->getUserLangObj();
941 } elseif ( is_null( $this->mTitle
) ) {
942 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
945 return $this->mTitle
->getPageLanguage();
949 * Get the language object for language conversion
950 * @deprecated since 1.32, just use getTargetLanguage()
951 * @return Language|null
953 public function getConverterLanguage() {
954 return $this->getTargetLanguage();
958 * Get a User object either from $this->mUser, if set, or from the
959 * ParserOptions object otherwise
963 public function getUser() {
964 if ( !is_null( $this->mUser
) ) {
967 return $this->mOptions
->getUser();
971 * Get a preprocessor object
973 * @return Preprocessor
975 public function getPreprocessor() {
976 if ( !isset( $this->mPreprocessor
) ) {
977 $class = $this->mPreprocessorClass
;
978 $this->mPreprocessor
= new $class( $this );
980 return $this->mPreprocessor
;
984 * Get a LinkRenderer instance to make links with
987 * @return LinkRenderer
989 public function getLinkRenderer() {
990 // XXX We make the LinkRenderer with current options and then cache it forever
991 if ( !$this->mLinkRenderer
) {
992 $this->mLinkRenderer
= $this->linkRendererFactory
->create();
993 $this->mLinkRenderer
->setStubThreshold(
994 $this->getOptions()->getStubThreshold()
998 return $this->mLinkRenderer
;
1002 * Get the MagicWordFactory that this Parser is using
1005 * @return MagicWordFactory
1007 public function getMagicWordFactory() {
1008 return $this->magicWordFactory
;
1012 * Get the content language that this Parser is using
1017 public function getContentLanguage() {
1018 return $this->contLang
;
1022 * Replaces all occurrences of HTML-style comments and the given tags
1023 * in the text with a random marker and returns the next text. The output
1024 * parameter $matches will be an associative array filled with data in
1031 * [ 'param' => 'x' ],
1032 * '<element param="x">tag content</element>' ]
1035 * @param array $elements List of element names. Comments are always extracted.
1036 * @param string $text Source text string.
1037 * @param array &$matches Out parameter, Array: extracted tags
1038 * @return string Stripped text
1040 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1045 $taglist = implode( '|', $elements );
1046 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
1048 while ( $text != '' ) {
1049 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1051 if ( count( $p ) < 5 ) {
1054 if ( count( $p ) > 5 ) {
1062 list( , $element, $attributes, $close, $inside ) = $p;
1065 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1066 $stripped .= $marker;
1068 if ( $close === '/>' ) {
1069 # Empty element tag, <tag />
1074 if ( $element === '!--' ) {
1077 $end = "/(<\\/$element\\s*>)/i";
1079 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1081 if ( count( $q ) < 3 ) {
1082 # No end tag -- let it run out to the end of the text.
1086 list( , $tail, $text ) = $q;
1090 $matches[$marker] = [ $element,
1092 Sanitizer
::decodeTagAttributes( $attributes ),
1093 "<$element$attributes$close$content$tail" ];
1099 * Get a list of strippable XML-like elements
1103 public function getStripList() {
1104 return $this->mStripList
;
1108 * Add an item to the strip state
1109 * Returns the unique tag which must be inserted into the stripped text
1110 * The tag will be replaced with the original text in unstrip()
1112 * @param string $text
1116 public function insertStripItem( $text ) {
1117 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1118 $this->mMarkerIndex++
;
1119 $this->mStripState
->addGeneral( $marker, $text );
1124 * parse the wiki syntax used to render tables
1127 * @param string $text
1130 public function doTableStuff( $text ) {
1131 $lines = StringUtils
::explode( "\n", $text );
1133 $td_history = []; # Is currently a td tag open?
1134 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1135 $tr_history = []; # Is currently a tr tag open?
1136 $tr_attributes = []; # history of tr attributes
1137 $has_opened_tr = []; # Did this table open a <tr> element?
1138 $indent_level = 0; # indent level of the table
1140 foreach ( $lines as $outLine ) {
1141 $line = trim( $outLine );
1143 if ( $line === '' ) { # empty line, go to next line
1144 $out .= $outLine . "\n";
1148 $first_character = $line[0];
1149 $first_two = substr( $line, 0, 2 );
1152 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1153 # First check if we are starting a new table
1154 $indent_level = strlen( $matches[1] );
1156 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1157 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1159 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1160 array_push( $td_history, false );
1161 array_push( $last_tag_history, '' );
1162 array_push( $tr_history, false );
1163 array_push( $tr_attributes, '' );
1164 array_push( $has_opened_tr, false );
1165 } elseif ( count( $td_history ) == 0 ) {
1166 # Don't do any of the following
1167 $out .= $outLine . "\n";
1169 } elseif ( $first_two === '|}' ) {
1170 # We are ending a table
1171 $line = '</table>' . substr( $line, 2 );
1172 $last_tag = array_pop( $last_tag_history );
1174 if ( !array_pop( $has_opened_tr ) ) {
1175 $line = "<tr><td></td></tr>{$line}";
1178 if ( array_pop( $tr_history ) ) {
1179 $line = "</tr>{$line}";
1182 if ( array_pop( $td_history ) ) {
1183 $line = "</{$last_tag}>{$line}";
1185 array_pop( $tr_attributes );
1186 if ( $indent_level > 0 ) {
1187 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1191 } elseif ( $first_two === '|-' ) {
1192 # Now we have a table row
1193 $line = preg_replace( '#^\|-+#', '', $line );
1195 # Whats after the tag is now only attributes
1196 $attributes = $this->mStripState
->unstripBoth( $line );
1197 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1198 array_pop( $tr_attributes );
1199 array_push( $tr_attributes, $attributes );
1202 $last_tag = array_pop( $last_tag_history );
1203 array_pop( $has_opened_tr );
1204 array_push( $has_opened_tr, true );
1206 if ( array_pop( $tr_history ) ) {
1210 if ( array_pop( $td_history ) ) {
1211 $line = "</{$last_tag}>{$line}";
1215 array_push( $tr_history, false );
1216 array_push( $td_history, false );
1217 array_push( $last_tag_history, '' );
1218 } elseif ( $first_character === '|'
1219 ||
$first_character === '!'
1220 ||
$first_two === '|+'
1222 # This might be cell elements, td, th or captions
1223 if ( $first_two === '|+' ) {
1224 $first_character = '+';
1225 $line = substr( $line, 2 );
1227 $line = substr( $line, 1 );
1230 // Implies both are valid for table headings.
1231 if ( $first_character === '!' ) {
1232 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1235 # Split up multiple cells on the same line.
1236 # FIXME : This can result in improper nesting of tags processed
1237 # by earlier parser steps.
1238 $cells = explode( '||', $line );
1242 # Loop through each table cell
1243 foreach ( $cells as $cell ) {
1245 if ( $first_character !== '+' ) {
1246 $tr_after = array_pop( $tr_attributes );
1247 if ( !array_pop( $tr_history ) ) {
1248 $previous = "<tr{$tr_after}>\n";
1250 array_push( $tr_history, true );
1251 array_push( $tr_attributes, '' );
1252 array_pop( $has_opened_tr );
1253 array_push( $has_opened_tr, true );
1256 $last_tag = array_pop( $last_tag_history );
1258 if ( array_pop( $td_history ) ) {
1259 $previous = "</{$last_tag}>\n{$previous}";
1262 if ( $first_character === '|' ) {
1264 } elseif ( $first_character === '!' ) {
1266 } elseif ( $first_character === '+' ) {
1267 $last_tag = 'caption';
1272 array_push( $last_tag_history, $last_tag );
1274 # A cell could contain both parameters and data
1275 $cell_data = explode( '|', $cell, 2 );
1277 # T2553: Note that a '|' inside an invalid link should not
1278 # be mistaken as delimiting cell parameters
1279 # Bug T153140: Neither should language converter markup.
1280 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1281 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1282 } elseif ( count( $cell_data ) == 1 ) {
1283 // Whitespace in cells is trimmed
1284 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1286 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1287 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1288 // Whitespace in cells is trimmed
1289 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1293 array_push( $td_history, true );
1296 $out .= $outLine . "\n";
1299 # Closing open td, tr && table
1300 while ( count( $td_history ) > 0 ) {
1301 if ( array_pop( $td_history ) ) {
1304 if ( array_pop( $tr_history ) ) {
1307 if ( !array_pop( $has_opened_tr ) ) {
1308 $out .= "<tr><td></td></tr>\n";
1311 $out .= "</table>\n";
1314 # Remove trailing line-ending (b/c)
1315 if ( substr( $out, -1 ) === "\n" ) {
1316 $out = substr( $out, 0, -1 );
1319 # special case: don't return empty table
1320 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1328 * Helper function for parse() that transforms wiki markup into half-parsed
1329 * HTML. Only called for $mOutputType == self::OT_HTML.
1333 * @param string $text The text to parse
1334 * @param-taint $text escapes_html
1335 * @param bool $isMain Whether this is being called from the main parse() function
1336 * @param PPFrame|bool $frame A pre-processor frame
1340 public function internalParse( $text, $isMain = true, $frame = false ) {
1343 // Avoid PHP 7.1 warning from passing $this by reference
1346 # Hook to suspend the parser in this state
1347 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1351 # if $frame is provided, then use $frame for replacing any variables
1353 # use frame depth to infer how include/noinclude tags should be handled
1354 # depth=0 means this is the top-level document; otherwise it's an included document
1355 if ( !$frame->depth
) {
1358 $flag = self
::PTD_FOR_INCLUSION
;
1360 $dom = $this->preprocessToDom( $text, $flag );
1361 $text = $frame->expand( $dom );
1363 # if $frame is not provided, then use old-style replaceVariables
1364 $text = $this->replaceVariables( $text );
1367 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1368 $text = Sanitizer
::removeHTMLtags(
1370 [ $this, 'attributeStripCallback' ],
1372 array_keys( $this->mTransparentTagHooks
),
1374 [ $this, 'addTrackingCategory' ]
1376 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1378 # Tables need to come after variable replacement for things to work
1379 # properly; putting them before other transformations should keep
1380 # exciting things like link expansions from showing up in surprising
1382 $text = $this->doTableStuff( $text );
1384 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1386 $text = $this->doDoubleUnderscore( $text );
1388 $text = $this->doHeadings( $text );
1389 $text = $this->replaceInternalLinks( $text );
1390 $text = $this->doAllQuotes( $text );
1391 $text = $this->replaceExternalLinks( $text );
1393 # replaceInternalLinks may sometimes leave behind
1394 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1395 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1397 $text = $this->doMagicLinks( $text );
1398 $text = $this->formatHeadings( $text, $origText, $isMain );
1404 * Helper function for parse() that transforms half-parsed HTML into fully
1407 * @param string $text
1408 * @param bool $isMain
1409 * @param bool $linestart
1412 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1413 $text = $this->mStripState
->unstripGeneral( $text );
1415 // Avoid PHP 7.1 warning from passing $this by reference
1419 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1422 # Clean up special characters, only run once, next-to-last before doBlockLevels
1423 $text = Sanitizer
::armorFrenchSpaces( $text );
1425 $text = $this->doBlockLevels( $text, $linestart );
1427 $this->replaceLinkHolders( $text );
1430 * The input doesn't get language converted if
1432 * b) Content isn't converted
1433 * c) It's a conversion table
1434 * d) it is an interface message (which is in the user language)
1436 if ( !( $this->mOptions
->getDisableContentConversion()
1437 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1438 && !$this->mOptions
->getInterfaceMessage()
1440 # The position of the convert() call should not be changed. it
1441 # assumes that the links are all replaced and the only thing left
1442 # is the <nowiki> mark.
1443 $text = $this->getTargetLanguage()->convert( $text );
1446 $text = $this->mStripState
->unstripNoWiki( $text );
1449 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1452 $text = $this->replaceTransparentTags( $text );
1453 $text = $this->mStripState
->unstripGeneral( $text );
1455 $text = Sanitizer
::normalizeCharReferences( $text );
1457 if ( MWTidy
::isEnabled() ) {
1458 if ( $this->mOptions
->getTidy() ) {
1459 $text = MWTidy
::tidy( $text );
1462 # attempt to sanitize at least some nesting problems
1463 # (T4702 and quite a few others)
1464 # This code path is buggy and deprecated!
1465 wfDeprecated( 'disabling tidy', '1.33' );
1467 # ''Something [http://www.cool.com cool''] -->
1468 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1469 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1470 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1471 # fix up an anchor inside another anchor, only
1472 # at least for a single single nested link (T5695)
1473 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1474 '\\1\\2</a>\\3</a>\\1\\4</a>',
1475 # fix div inside inline elements- doBlockLevels won't wrap a line which
1476 # contains a div, so fix it up here; replace
1477 # div with escaped text
1478 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1479 '\\1\\3<div\\5>\\6</div>\\8\\9',
1480 # remove empty italic or bold tag pairs, some
1481 # introduced by rules above
1482 '/<([bi])><\/\\1>/' => '',
1485 $text = preg_replace(
1486 array_keys( $tidyregs ),
1487 array_values( $tidyregs ),
1492 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1499 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1500 * magic external links.
1505 * @param string $text
1509 public function doMagicLinks( $text ) {
1510 $prots = wfUrlProtocolsWithoutProtRel();
1511 $urlChar = self
::EXT_LINK_URL_CLASS
;
1512 $addr = self
::EXT_LINK_ADDR
;
1513 $space = self
::SPACE_NOT_NL
; # non-newline space
1514 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1515 $spaces = "$space++"; # possessive match of 1 or more spaces
1516 $text = preg_replace_callback(
1518 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1519 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1520 (\b # m[3]: Free external links
1522 ($addr$urlChar*) # m[4]: Post-protocol path
1524 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1526 \bISBN $spaces ( # m[6]: ISBN, capture number
1527 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1528 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1529 [0-9Xx] # check digit
1531 )!xu", [ $this, 'magicLinkCallback' ], $text );
1536 * @throws MWException
1538 * @return string HTML
1540 public function magicLinkCallback( $m ) {
1541 if ( isset( $m[1] ) && $m[1] !== '' ) {
1544 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1547 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1548 # Free external link
1549 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1550 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1552 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1553 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1558 $cssClass = 'mw-magiclink-rfc';
1559 $trackingCat = 'magiclink-tracking-rfc';
1561 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1562 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1566 $urlmsg = 'pubmedurl';
1567 $cssClass = 'mw-magiclink-pmid';
1568 $trackingCat = 'magiclink-tracking-pmid';
1571 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1572 substr( $m[0], 0, 20 ) . '"' );
1574 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1575 $this->addTrackingCategory( $trackingCat );
1576 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1577 } elseif ( isset( $m[6] ) && $m[6] !== ''
1578 && $this->mOptions
->getMagicISBNLinks()
1582 $space = self
::SPACE_NOT_NL
; # non-newline space
1583 $isbn = preg_replace( "/$space/", ' ', $isbn );
1584 $num = strtr( $isbn, [
1589 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1590 return $this->getLinkRenderer()->makeKnownLink(
1591 SpecialPage
::getTitleFor( 'Booksources', $num ),
1594 'class' => 'internal mw-magiclink-isbn',
1595 'title' => false // suppress title attribute
1604 * Make a free external link, given a user-supplied URL
1606 * @param string $url
1607 * @param int $numPostProto
1608 * The number of characters after the protocol.
1609 * @return string HTML
1612 public function makeFreeExternalLink( $url, $numPostProto ) {
1615 # The characters '<' and '>' (which were escaped by
1616 # removeHTMLtags()) should not be included in
1617 # URLs, per RFC 2396.
1618 # Make terminate a URL as well (bug T84937)
1621 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1626 $trail = substr( $url, $m2[0][1] ) . $trail;
1627 $url = substr( $url, 0, $m2[0][1] );
1630 # Move trailing punctuation to $trail
1632 # If there is no left bracket, then consider right brackets fair game too
1633 if ( strpos( $url, '(' ) === false ) {
1637 $urlRev = strrev( $url );
1638 $numSepChars = strspn( $urlRev, $sep );
1639 # Don't break a trailing HTML entity by moving the ; into $trail
1640 # This is in hot code, so use substr_compare to avoid having to
1641 # create a new string object for the comparison
1642 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1643 # more optimization: instead of running preg_match with a $
1644 # anchor, which can be slow, do the match on the reversed
1645 # string starting at the desired offset.
1646 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1647 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1651 if ( $numSepChars ) {
1652 $trail = substr( $url, -$numSepChars ) . $trail;
1653 $url = substr( $url, 0, -$numSepChars );
1656 # Verify that we still have a real URL after trail removal, and
1657 # not just lone protocol
1658 if ( strlen( $trail ) >= $numPostProto ) {
1659 return $url . $trail;
1662 $url = Sanitizer
::cleanUrl( $url );
1664 # Is this an external image?
1665 $text = $this->maybeMakeExternalImage( $url );
1666 if ( $text === false ) {
1667 # Not an image, make a link
1668 $text = Linker
::makeExternalLink( $url,
1669 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1671 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1672 # Register it in the output object...
1673 $this->mOutput
->addExternalLink( $url );
1675 return $text . $trail;
1679 * Parse headers and return html
1683 * @param string $text
1687 public function doHeadings( $text ) {
1688 for ( $i = 6; $i >= 1; --$i ) {
1689 $h = str_repeat( '=', $i );
1690 // Trim non-newline whitespace from headings
1691 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1692 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1698 * Replace single quotes with HTML markup
1701 * @param string $text
1703 * @return string The altered text
1705 public function doAllQuotes( $text ) {
1707 $lines = StringUtils
::explode( "\n", $text );
1708 foreach ( $lines as $line ) {
1709 $outtext .= $this->doQuotes( $line ) . "\n";
1711 $outtext = substr( $outtext, 0, -1 );
1716 * Helper function for doAllQuotes()
1718 * @param string $text
1722 public function doQuotes( $text ) {
1723 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1724 $countarr = count( $arr );
1725 if ( $countarr == 1 ) {
1729 // First, do some preliminary work. This may shift some apostrophes from
1730 // being mark-up to being text. It also counts the number of occurrences
1731 // of bold and italics mark-ups.
1734 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1735 $thislen = strlen( $arr[$i] );
1736 // If there are ever four apostrophes, assume the first is supposed to
1737 // be text, and the remaining three constitute mark-up for bold text.
1738 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1739 if ( $thislen == 4 ) {
1740 $arr[$i - 1] .= "'";
1743 } elseif ( $thislen > 5 ) {
1744 // If there are more than 5 apostrophes in a row, assume they're all
1745 // text except for the last 5.
1746 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1747 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1751 // Count the number of occurrences of bold and italics mark-ups.
1752 if ( $thislen == 2 ) {
1754 } elseif ( $thislen == 3 ) {
1756 } elseif ( $thislen == 5 ) {
1762 // If there is an odd number of both bold and italics, it is likely
1763 // that one of the bold ones was meant to be an apostrophe followed
1764 // by italics. Which one we cannot know for certain, but it is more
1765 // likely to be one that has a single-letter word before it.
1766 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1767 $firstsingleletterword = -1;
1768 $firstmultiletterword = -1;
1770 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1771 if ( strlen( $arr[$i] ) == 3 ) {
1772 $x1 = substr( $arr[$i - 1], -1 );
1773 $x2 = substr( $arr[$i - 1], -2, 1 );
1774 if ( $x1 === ' ' ) {
1775 if ( $firstspace == -1 ) {
1778 } elseif ( $x2 === ' ' ) {
1779 $firstsingleletterword = $i;
1780 // if $firstsingleletterword is set, we don't
1781 // look at the other options, so we can bail early.
1783 } elseif ( $firstmultiletterword == -1 ) {
1784 $firstmultiletterword = $i;
1789 // If there is a single-letter word, use it!
1790 if ( $firstsingleletterword > -1 ) {
1791 $arr[$firstsingleletterword] = "''";
1792 $arr[$firstsingleletterword - 1] .= "'";
1793 } elseif ( $firstmultiletterword > -1 ) {
1794 // If not, but there's a multi-letter word, use that one.
1795 $arr[$firstmultiletterword] = "''";
1796 $arr[$firstmultiletterword - 1] .= "'";
1797 } elseif ( $firstspace > -1 ) {
1798 // ... otherwise use the first one that has neither.
1799 // (notice that it is possible for all three to be -1 if, for example,
1800 // there is only one pentuple-apostrophe in the line)
1801 $arr[$firstspace] = "''";
1802 $arr[$firstspace - 1] .= "'";
1806 // Now let's actually convert our apostrophic mush to HTML!
1811 foreach ( $arr as $r ) {
1812 if ( ( $i %
2 ) == 0 ) {
1813 if ( $state === 'both' ) {
1819 $thislen = strlen( $r );
1820 if ( $thislen == 2 ) {
1821 if ( $state === 'i' ) {
1824 } elseif ( $state === 'bi' ) {
1827 } elseif ( $state === 'ib' ) {
1828 $output .= '</b></i><b>';
1830 } elseif ( $state === 'both' ) {
1831 $output .= '<b><i>' . $buffer . '</i>';
1833 } else { // $state can be 'b' or ''
1837 } elseif ( $thislen == 3 ) {
1838 if ( $state === 'b' ) {
1841 } elseif ( $state === 'bi' ) {
1842 $output .= '</i></b><i>';
1844 } elseif ( $state === 'ib' ) {
1847 } elseif ( $state === 'both' ) {
1848 $output .= '<i><b>' . $buffer . '</b>';
1850 } else { // $state can be 'i' or ''
1854 } elseif ( $thislen == 5 ) {
1855 if ( $state === 'b' ) {
1856 $output .= '</b><i>';
1858 } elseif ( $state === 'i' ) {
1859 $output .= '</i><b>';
1861 } elseif ( $state === 'bi' ) {
1862 $output .= '</i></b>';
1864 } elseif ( $state === 'ib' ) {
1865 $output .= '</b></i>';
1867 } elseif ( $state === 'both' ) {
1868 $output .= '<i><b>' . $buffer . '</b></i>';
1870 } else { // ($state == '')
1878 // Now close all remaining tags. Notice that the order is important.
1879 if ( $state === 'b' ||
$state === 'ib' ) {
1882 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1885 if ( $state === 'bi' ) {
1888 // There might be lonely ''''', so make sure we have a buffer
1889 if ( $state === 'both' && $buffer ) {
1890 $output .= '<b><i>' . $buffer . '</i></b>';
1896 * Replace external links (REL)
1898 * Note: this is all very hackish and the order of execution matters a lot.
1899 * Make sure to run tests/parser/parserTests.php if you change this code.
1903 * @param string $text
1905 * @throws MWException
1908 public function replaceExternalLinks( $text ) {
1909 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1910 if ( $bits === false ) {
1911 throw new MWException( "PCRE needs to be compiled with "
1912 . "--enable-unicode-properties in order for MediaWiki to function" );
1914 $s = array_shift( $bits );
1917 while ( $i < count( $bits ) ) {
1920 $text = $bits[$i++
];
1921 $trail = $bits[$i++
];
1923 # The characters '<' and '>' (which were escaped by
1924 # removeHTMLtags()) should not be included in
1925 # URLs, per RFC 2396.
1927 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1928 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1929 $url = substr( $url, 0, $m2[0][1] );
1932 # If the link text is an image URL, replace it with an <img> tag
1933 # This happened by accident in the original parser, but some people used it extensively
1934 $img = $this->maybeMakeExternalImage( $text );
1935 if ( $img !== false ) {
1941 # Set linktype for CSS
1944 # No link text, e.g. [http://domain.tld/some.link]
1945 if ( $text == '' ) {
1947 $langObj = $this->getTargetLanguage();
1948 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1949 $linktype = 'autonumber';
1951 # Have link text, e.g. [http://domain.tld/some.link text]s
1953 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1956 // Excluding protocol-relative URLs may avoid many false positives.
1957 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1958 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1961 $url = Sanitizer
::cleanUrl( $url );
1963 # Use the encoded URL
1964 # This means that users can paste URLs directly into the text
1965 # Funny characters like ö aren't valid in URLs anyway
1966 # This was changed in August 2004
1967 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1968 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1970 # Register link in the output object.
1971 $this->mOutput
->addExternalLink( $url );
1978 * Get the rel attribute for a particular external link.
1981 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1982 * nofollow if appropriate
1983 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1984 * @return string|null Rel attribute for $url
1986 public static function getExternalLinkRel( $url = false, $title = null ) {
1987 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1988 $ns = $title ?
$title->getNamespace() : false;
1989 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1990 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1998 * Get an associative array of additional HTML attributes appropriate for a
1999 * particular external link. This currently may include rel => nofollow
2000 * (depending on configuration, namespace, and the URL's domain) and/or a
2001 * target attribute (depending on configuration).
2003 * @param string $url URL to extract the domain from for rel =>
2004 * nofollow if appropriate
2005 * @return array Associative array of HTML attributes
2007 public function getExternalLinkAttribs( $url ) {
2009 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
2011 $target = $this->mOptions
->getExternalLinkTarget();
2013 $attribs['target'] = $target;
2014 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
2015 // T133507. New windows can navigate parent cross-origin.
2016 // Including noreferrer due to lacking browser
2017 // support of noopener. Eventually noreferrer should be removed.
2018 if ( $rel !== '' ) {
2021 $rel .= 'noreferrer noopener';
2024 $attribs['rel'] = $rel;
2029 * Replace unusual escape codes in a URL with their equivalent characters
2031 * This generally follows the syntax defined in RFC 3986, with special
2032 * consideration for HTTP query strings.
2034 * @param string $url
2037 public static function normalizeLinkUrl( $url ) {
2038 # Test for RFC 3986 IPv6 syntax
2039 $scheme = '[a-z][a-z0-9+.-]*:';
2040 $userinfo = '(?:[a-z0-9\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*';
2041 $ipv6Host = '\\[((?:[0-9a-f:]|%3[0-A]|%[46][1-6])+)\\]';
2042 if ( preg_match( "<^(?:{$scheme})?//(?:{$userinfo}@)?{$ipv6Host}(?:[:/?#].*|)$>i", $url, $m ) &&
2043 IP
::isValid( rawurldecode( $m[1] ) )
2045 $isIPv6 = rawurldecode( $m[1] );
2050 # Make sure unsafe characters are encoded
2051 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2053 return rawurlencode( $m[0] );
2059 $end = strlen( $url );
2061 # Fragment part - 'fragment'
2062 $start = strpos( $url, '#' );
2063 if ( $start !== false && $start < $end ) {
2064 $ret = self
::normalizeUrlComponent(
2065 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2069 # Query part - 'query' minus &=+;
2070 $start = strpos( $url, '?' );
2071 if ( $start !== false && $start < $end ) {
2072 $ret = self
::normalizeUrlComponent(
2073 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2077 # Scheme and path part - 'pchar'
2078 # (we assume no userinfo or encoded colons in the host)
2079 $ret = self
::normalizeUrlComponent(
2080 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2083 if ( $isIPv6 !== false ) {
2084 $ipv6Host = "%5B({$isIPv6})%5D";
2085 $ret = preg_replace(
2086 "<^((?:{$scheme})?//(?:{$userinfo}@)?){$ipv6Host}(?=[:/?#]|$)>i",
2095 private static function normalizeUrlComponent( $component, $unsafe ) {
2096 $callback = function ( $matches ) use ( $unsafe ) {
2097 $char = urldecode( $matches[0] );
2098 $ord = ord( $char );
2099 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2103 # Leave it escaped, but use uppercase for a-f
2104 return strtoupper( $matches[0] );
2107 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2111 * make an image if it's allowed, either through the global
2112 * option, through the exception, or through the on-wiki whitelist
2114 * @param string $url
2118 private function maybeMakeExternalImage( $url ) {
2119 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2120 $imagesexception = !empty( $imagesfrom );
2122 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2123 if ( $imagesexception && is_array( $imagesfrom ) ) {
2124 $imagematch = false;
2125 foreach ( $imagesfrom as $match ) {
2126 if ( strpos( $url, $match ) === 0 ) {
2131 } elseif ( $imagesexception ) {
2132 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2134 $imagematch = false;
2137 if ( $this->mOptions
->getAllowExternalImages()
2138 ||
( $imagesexception && $imagematch )
2140 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2142 $text = Linker
::makeExternalImage( $url );
2145 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2146 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2148 $whitelist = explode(
2150 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2153 foreach ( $whitelist as $entry ) {
2154 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2155 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2158 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2159 # Image matches a whitelist entry
2160 $text = Linker
::makeExternalImage( $url );
2169 * Process [[ ]] wikilinks
2173 * @return string Processed text
2177 public function replaceInternalLinks( $s ) {
2178 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2183 * Process [[ ]] wikilinks (RIL)
2185 * @throws MWException
2186 * @return LinkHolderArray
2190 public function replaceInternalLinks2( &$s ) {
2191 static $tc = false, $e1, $e1_img;
2192 # the % is needed to support urlencoded titles as well
2194 $tc = Title
::legalChars() . '#%';
2195 # Match a link having the form [[namespace:link|alternate]]trail
2196 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2197 # Match cases where there is no "]]", which might still be images
2198 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2201 $holders = new LinkHolderArray( $this );
2203 # split the entire text string on occurrences of [[
2204 $a = StringUtils
::explode( '[[', ' ' . $s );
2205 # get the first element (all text up to first [[), and remove the space we added
2208 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2209 $s = substr( $s, 1 );
2211 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2213 if ( $useLinkPrefixExtension ) {
2214 # Match the end of a line for a word that's not followed by whitespace,
2215 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2216 $charset = $this->contLang
->linkPrefixCharset();
2217 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2220 if ( is_null( $this->mTitle
) ) {
2221 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2223 $nottalk = !$this->mTitle
->isTalkPage();
2225 if ( $useLinkPrefixExtension ) {
2227 if ( preg_match( $e2, $s, $m ) ) {
2228 $first_prefix = $m[2];
2230 $first_prefix = false;
2236 $useSubpages = $this->areSubpagesAllowed();
2238 # Loop for each link
2239 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2240 # Check for excessive memory usage
2241 if ( $holders->isBig() ) {
2243 # Do the existence check, replace the link holders and clear the array
2244 $holders->replace( $s );
2248 if ( $useLinkPrefixExtension ) {
2249 if ( preg_match( $e2, $s, $m ) ) {
2250 list( , $s, $prefix ) = $m;
2255 if ( $first_prefix ) {
2256 $prefix = $first_prefix;
2257 $first_prefix = false;
2261 $might_be_img = false;
2263 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2265 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2266 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2267 # the real problem is with the $e1 regex
2269 # Still some problems for cases where the ] is meant to be outside punctuation,
2270 # and no image is in sight. See T4095.
2272 && substr( $m[3], 0, 1 ) === ']'
2273 && strpos( $text, '[' ) !== false
2275 $text .= ']'; # so that replaceExternalLinks($text) works later
2276 $m[3] = substr( $m[3], 1 );
2278 # fix up urlencoded title texts
2279 if ( strpos( $m[1], '%' ) !== false ) {
2280 # Should anchors '#' also be rejected?
2281 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2284 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2285 # Invalid, but might be an image with a link in its caption
2286 $might_be_img = true;
2288 if ( strpos( $m[1], '%' ) !== false ) {
2289 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2292 } else { # Invalid form; output directly
2293 $s .= $prefix . '[[' . $line;
2297 $origLink = ltrim( $m[1], ' ' );
2299 # Don't allow internal links to pages containing
2300 # PROTO: where PROTO is a valid URL protocol; these
2301 # should be external links.
2302 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2303 $s .= $prefix . '[[' . $line;
2307 # Make subpage if necessary
2308 if ( $useSubpages ) {
2309 $link = $this->maybeDoSubpageLink( $origLink, $text );
2314 // \x7f isn't a default legal title char, so most likely strip
2315 // markers will force us into the "invalid form" path above. But,
2316 // just in case, let's assert that xmlish tags aren't valid in
2317 // the title position.
2318 $unstrip = $this->mStripState
->killMarkers( $link );
2319 $noMarkers = ( $unstrip === $link );
2321 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2322 if ( $nt === null ) {
2323 $s .= $prefix . '[[' . $line;
2327 $ns = $nt->getNamespace();
2328 $iw = $nt->getInterwiki();
2330 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2332 if ( $might_be_img ) { # if this is actually an invalid link
2333 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2336 # look at the next 'line' to see if we can close it there
2338 $next_line = $a->current();
2339 if ( $next_line === false ||
$next_line === null ) {
2342 $m = explode( ']]', $next_line, 3 );
2343 if ( count( $m ) == 3 ) {
2344 # the first ]] closes the inner link, the second the image
2346 $text .= "[[{$m[0]}]]{$m[1]}";
2349 } elseif ( count( $m ) == 2 ) {
2350 # if there's exactly one ]] that's fine, we'll keep looking
2351 $text .= "[[{$m[0]}]]{$m[1]}";
2353 # if $next_line is invalid too, we need look no further
2354 $text .= '[[' . $next_line;
2359 # we couldn't find the end of this imageLink, so output it raw
2360 # but don't ignore what might be perfectly normal links in the text we've examined
2361 $holders->merge( $this->replaceInternalLinks2( $text ) );
2362 $s .= "{$prefix}[[$link|$text";
2363 # note: no $trail, because without an end, there *is* no trail
2366 } else { # it's not an image, so output it raw
2367 $s .= "{$prefix}[[$link|$text";
2368 # note: no $trail, because without an end, there *is* no trail
2373 $wasblank = ( $text == '' );
2377 # Strip off leading ':'
2378 $text = substr( $text, 1 );
2381 # T6598 madness. Handle the quotes only if they come from the alternate part
2382 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2383 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2384 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2385 $text = $this->doQuotes( $text );
2388 # Link not escaped by : , create the various objects
2389 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2392 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2393 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2394 in_array( $iw, $this->siteConfig
->get( 'ExtraInterlanguageLinkPrefixes' ) )
2397 # T26502: filter duplicates
2398 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2399 $this->mLangLinkLanguages
[$iw] = true;
2400 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2404 * Strip the whitespace interwiki links produce, see T10897
2406 $s = rtrim( $s . $prefix ) . $trail; # T175416
2410 if ( $ns == NS_FILE
) {
2411 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2413 # if no parameters were passed, $text
2414 # becomes something like "File:Foo.png",
2415 # which we don't want to pass on to the
2419 # recursively parse links inside the image caption
2420 # actually, this will parse them in any other parameters, too,
2421 # but it might be hard to fix that, and it doesn't matter ATM
2422 $text = $this->replaceExternalLinks( $text );
2423 $holders->merge( $this->replaceInternalLinks2( $text ) );
2425 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2426 $s .= $prefix . $this->armorLinks(
2427 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2430 } elseif ( $ns == NS_CATEGORY
) {
2432 * Strip the whitespace Category links produce, see T2087
2434 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2437 $sortkey = $this->getDefaultSort();
2441 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2442 $sortkey = str_replace( "\n", '', $sortkey );
2443 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2444 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2450 # Self-link checking. For some languages, variants of the title are checked in
2451 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2452 # for linking to a different variant.
2453 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2454 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2458 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2459 # @todo FIXME: Should do batch file existence checks, see comment below
2460 if ( $ns == NS_MEDIA
) {
2461 # Give extensions a chance to select the file revision for us
2464 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2465 [ $this, $nt, &$options, &$descQuery ] );
2466 # Fetch and register the file (file title may be different via hooks)
2467 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2468 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2469 $s .= $prefix . $this->armorLinks(
2470 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2474 # Some titles, such as valid special pages or files in foreign repos, should
2475 # be shown as bluelinks even though they're not included in the page table
2476 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2477 # batch file existence checks for NS_FILE and NS_MEDIA
2478 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2479 $this->mOutput
->addLink( $nt );
2480 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2482 # Links will be added to the output link list after checking
2483 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2490 * Render a forced-blue link inline; protect against double expansion of
2491 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2492 * Since this little disaster has to split off the trail text to avoid
2493 * breaking URLs in the following text without breaking trails on the
2494 * wiki links, it's been made into a horrible function.
2497 * @param string $text
2498 * @param string $trail
2499 * @param string $prefix
2500 * @return string HTML-wikitext mix oh yuck
2502 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2503 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2505 if ( $text == '' ) {
2506 $text = htmlspecialchars( $nt->getPrefixedText() );
2509 $link = $this->getLinkRenderer()->makeKnownLink(
2510 $nt, new HtmlArmor( "$prefix$text$inside" )
2513 return $this->armorLinks( $link ) . $trail;
2517 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2518 * going to go through further parsing steps before inline URL expansion.
2520 * Not needed quite as much as it used to be since free links are a bit
2521 * more sensible these days. But bracketed links are still an issue.
2523 * @param string $text More-or-less HTML
2524 * @return string Less-or-more HTML with NOPARSE bits
2526 public function armorLinks( $text ) {
2527 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2528 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2532 * Return true if subpage links should be expanded on this page.
2535 public function areSubpagesAllowed() {
2536 # Some namespaces don't allow subpages
2537 return $this->nsInfo
->hasSubpages( $this->mTitle
->getNamespace() );
2541 * Handle link to subpage if necessary
2543 * @param string $target The source of the link
2544 * @param string &$text The link text, modified as necessary
2545 * @return string The full name of the link
2548 public function maybeDoSubpageLink( $target, &$text ) {
2549 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2553 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2555 * @param string $text
2556 * @param bool $linestart Whether or not this is at the start of a line.
2558 * @return string The lists rendered as HTML
2560 public function doBlockLevels( $text, $linestart ) {
2561 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2565 * Return value of a magic variable (like PAGENAME)
2569 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2570 * @param bool|PPFrame $frame
2572 * @throws MWException
2575 public function getVariableValue( $index, $frame = false ) {
2576 if ( is_null( $this->mTitle
) ) {
2577 // If no title set, bad things are going to happen
2578 // later. Title should always be set since this
2579 // should only be called in the middle of a parse
2580 // operation (but the unit-tests do funky stuff)
2581 throw new MWException( __METHOD__
. ' Should only be '
2582 . ' called while parsing (no title set)' );
2585 // Avoid PHP 7.1 warning from passing $this by reference
2589 * Some of these require message or data lookups and can be
2590 * expensive to check many times.
2592 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] )
2593 && isset( $this->mVarCache
[$index] )
2595 return $this->mVarCache
[$index];
2598 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2599 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2601 // In miser mode, disable words that always cause double-parses on page save (T137900)
2602 static $slowRevWords = [ 'revisionid' => true ]; // @TODO: 'revisiontimestamp'
2604 isset( $slowRevWords[$index] ) &&
2605 $this->siteConfig
->get( 'MiserMode' ) &&
2606 !$this->mOptions
->getInterfaceMessage() &&
2607 // @TODO: disallow this word on all namespaces
2608 $this->nsInfo
->isContent( $this->mTitle
->getNamespace() )
2610 if ( $this->mRevisionId ||
$this->mOptions
->getSpeculativeRevId() ) {
2613 $this->mOutput
->setFlag( 'vary-revision-exists' );
2619 $pageLang = $this->getFunctionLang();
2625 case 'currentmonth':
2626 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2628 case 'currentmonth1':
2629 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2631 case 'currentmonthname':
2632 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2634 case 'currentmonthnamegen':
2635 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2637 case 'currentmonthabbrev':
2638 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2641 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2644 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2647 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2650 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2652 case 'localmonthname':
2653 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2655 case 'localmonthnamegen':
2656 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2658 case 'localmonthabbrev':
2659 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2662 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2665 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2668 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2671 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2673 case 'fullpagename':
2674 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2676 case 'fullpagenamee':
2677 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2680 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2682 case 'subpagenamee':
2683 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2685 case 'rootpagename':
2686 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2688 case 'rootpagenamee':
2689 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2692 $this->mTitle
->getRootText()
2695 case 'basepagename':
2696 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2698 case 'basepagenamee':
2699 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2702 $this->mTitle
->getBaseText()
2705 case 'talkpagename':
2706 if ( $this->mTitle
->canHaveTalkPage() ) {
2707 $talkPage = $this->mTitle
->getTalkPage();
2708 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2713 case 'talkpagenamee':
2714 if ( $this->mTitle
->canHaveTalkPage() ) {
2715 $talkPage = $this->mTitle
->getTalkPage();
2716 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2721 case 'subjectpagename':
2722 $subjPage = $this->mTitle
->getSubjectPage();
2723 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2725 case 'subjectpagenamee':
2726 $subjPage = $this->mTitle
->getSubjectPage();
2727 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2729 case 'pageid': // requested in T25427
2730 $pageid = $this->getTitle()->getArticleID();
2731 if ( $pageid == 0 ) {
2732 # 0 means the page doesn't exist in the database,
2733 # which means the user is previewing a new page.
2734 # The vary-revision flag must be set, because the magic word
2735 # will have a different value once the page is saved.
2736 $this->mOutput
->setFlag( 'vary-revision' );
2737 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2739 $value = $pageid ?
: null;
2742 # Let the edit saving system know we should parse the page
2743 # *after* a revision ID has been assigned.
2744 $this->mOutput
->setFlag( 'vary-revision-id' );
2745 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2746 $value = $this->mRevisionId
;
2749 $rev = $this->getRevisionObject();
2751 $value = $rev->getId();
2756 $value = $this->mOptions
->getSpeculativeRevId();
2758 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2763 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2765 case 'revisionday2':
2766 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2768 case 'revisionmonth':
2769 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2771 case 'revisionmonth1':
2772 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2774 case 'revisionyear':
2775 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2777 case 'revisiontimestamp':
2778 # Let the edit saving system know we should parse the page
2779 # *after* a revision ID has been assigned. This is for null edits.
2780 $this->mOutput
->setFlag( 'vary-revision' );
2781 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2782 $value = $this->getRevisionTimestamp();
2784 case 'revisionuser':
2785 # Let the edit saving system know we should parse the page
2786 # *after* a revision ID has been assigned for null edits.
2787 $this->mOutput
->setFlag( 'vary-user' );
2788 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2789 $value = $this->getRevisionUser();
2791 case 'revisionsize':
2792 $value = $this->getRevisionSize();
2795 $value = str_replace( '_', ' ',
2796 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2799 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2801 case 'namespacenumber':
2802 $value = $this->mTitle
->getNamespace();
2805 $value = $this->mTitle
->canHaveTalkPage()
2806 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2810 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2812 case 'subjectspace':
2813 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2815 case 'subjectspacee':
2816 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2818 case 'currentdayname':
2819 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2822 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2825 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2828 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2831 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2832 # int to remove the padding
2833 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2836 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2838 case 'localdayname':
2839 $value = $pageLang->getWeekdayName(
2840 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2844 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2847 $value = $pageLang->time(
2848 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2854 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2857 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2858 # int to remove the padding
2859 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2862 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2864 case 'numberofarticles':
2865 $value = $pageLang->formatNum( SiteStats
::articles() );
2867 case 'numberoffiles':
2868 $value = $pageLang->formatNum( SiteStats
::images() );
2870 case 'numberofusers':
2871 $value = $pageLang->formatNum( SiteStats
::users() );
2873 case 'numberofactiveusers':
2874 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2876 case 'numberofpages':
2877 $value = $pageLang->formatNum( SiteStats
::pages() );
2879 case 'numberofadmins':
2880 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2882 case 'numberofedits':
2883 $value = $pageLang->formatNum( SiteStats
::edits() );
2885 case 'currenttimestamp':
2886 $value = wfTimestamp( TS_MW
, $ts );
2888 case 'localtimestamp':
2889 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2891 case 'currentversion':
2892 $value = SpecialVersion
::getVersion();
2895 return $this->siteConfig
->get( 'ArticlePath' );
2897 return $this->siteConfig
->get( 'Sitename' );
2899 return $this->siteConfig
->get( 'Server' );
2901 return $this->siteConfig
->get( 'ServerName' );
2903 return $this->siteConfig
->get( 'ScriptPath' );
2905 return $this->siteConfig
->get( 'StylePath' );
2906 case 'directionmark':
2907 return $pageLang->getDirMark();
2908 case 'contentlanguage':
2909 return $this->siteConfig
->get( 'LanguageCode' );
2910 case 'pagelanguage':
2911 $value = $pageLang->getCode();
2913 case 'cascadingsources':
2914 $value = CoreParserFunctions
::cascadingsources( $this );
2919 'ParserGetVariableValueSwitch',
2920 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2927 $this->mVarCache
[$index] = $value;
2936 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2937 * @param string $variable Parser variable name
2940 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2941 # Get the timezone-adjusted timestamp to be used for this revision
2942 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2943 # Possibly set vary-revision if there is not yet an associated revision
2944 if ( !$this->getRevisionObject() ) {
2945 # Get the timezone-adjusted timestamp $mtts seconds in the future
2947 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2952 if ( $resNow !== $resThen ) {
2953 # Let the edit saving system know we should parse the page
2954 # *after* a revision ID has been assigned. This is for null edits.
2955 $this->mOutput
->setFlag( 'vary-revision' );
2956 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2964 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2968 public function initialiseVariables() {
2969 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2970 $substIDs = $this->magicWordFactory
->getSubstIDs();
2972 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2973 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2977 * Preprocess some wikitext and return the document tree.
2978 * This is the ghost of replace_variables().
2980 * @param string $text The text to parse
2981 * @param int $flags Bitwise combination of:
2982 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2983 * included. Default is to assume a direct page view.
2985 * The generated DOM tree must depend only on the input text and the flags.
2986 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2988 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2989 * change in the DOM tree for a given text, must be passed through the section identifier
2990 * in the section edit link and thus back to extractSections().
2992 * The output of this function is currently only cached in process memory, but a persistent
2993 * cache may be implemented at a later date which takes further advantage of these strict
2994 * dependency requirements.
2998 public function preprocessToDom( $text, $flags = 0 ) {
2999 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3004 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3010 public static function splitWhitespace( $s ) {
3011 $ltrimmed = ltrim( $s );
3012 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3013 $trimmed = rtrim( $ltrimmed );
3014 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3016 $w2 = substr( $ltrimmed, -$diff );
3020 return [ $w1, $trimmed, $w2 ];
3024 * Replace magic variables, templates, and template arguments
3025 * with the appropriate text. Templates are substituted recursively,
3026 * taking care to avoid infinite loops.
3028 * Note that the substitution depends on value of $mOutputType:
3029 * self::OT_WIKI: only {{subst:}} templates
3030 * self::OT_PREPROCESS: templates but not extension tags
3031 * self::OT_HTML: all templates and extension tags
3033 * @param string $text The text to transform
3034 * @param bool|PPFrame $frame Object describing the arguments passed to the
3035 * template. Arguments may also be provided as an associative array, as
3036 * was the usual case before MW1.12. Providing arguments this way may be
3037 * useful for extensions wishing to perform variable replacement
3039 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3040 * double-brace expansion.
3043 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3044 # Is there any text? Also, Prevent too big inclusions!
3045 $textSize = strlen( $text );
3046 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3050 if ( $frame === false ) {
3051 $frame = $this->getPreprocessor()->newFrame();
3052 } elseif ( !( $frame instanceof PPFrame
) ) {
3053 wfDebug( __METHOD__
. " called using plain parameters instead of "
3054 . "a PPFrame instance. Creating custom frame.\n" );
3055 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3058 $dom = $this->preprocessToDom( $text );
3059 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3060 $text = $frame->expand( $dom, $flags );
3066 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3068 * @param array $args
3072 public static function createAssocArgs( $args ) {
3075 foreach ( $args as $arg ) {
3076 $eqpos = strpos( $arg, '=' );
3077 if ( $eqpos === false ) {
3078 $assocArgs[$index++
] = $arg;
3080 $name = trim( substr( $arg, 0, $eqpos ) );
3081 $value = trim( substr( $arg, $eqpos +
1 ) );
3082 if ( $value === false ) {
3085 if ( $name !== false ) {
3086 $assocArgs[$name] = $value;
3095 * Warn the user when a parser limitation is reached
3096 * Will warn at most once the user per limitation type
3098 * The results are shown during preview and run through the Parser (See EditPage.php)
3100 * @param string $limitationType Should be one of:
3101 * 'expensive-parserfunction' (corresponding messages:
3102 * 'expensive-parserfunction-warning',
3103 * 'expensive-parserfunction-category')
3104 * 'post-expand-template-argument' (corresponding messages:
3105 * 'post-expand-template-argument-warning',
3106 * 'post-expand-template-argument-category')
3107 * 'post-expand-template-inclusion' (corresponding messages:
3108 * 'post-expand-template-inclusion-warning',
3109 * 'post-expand-template-inclusion-category')
3110 * 'node-count-exceeded' (corresponding messages:
3111 * 'node-count-exceeded-warning',
3112 * 'node-count-exceeded-category')
3113 * 'expansion-depth-exceeded' (corresponding messages:
3114 * 'expansion-depth-exceeded-warning',
3115 * 'expansion-depth-exceeded-category')
3116 * @param string|int|null $current Current value
3117 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3118 * exceeded, provide the values (optional)
3120 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3121 # does no harm if $current and $max are present but are unnecessary for the message
3122 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3123 # only during preview, and that would split the parser cache unnecessarily.
3124 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3126 $this->mOutput
->addWarning( $warning );
3127 $this->addTrackingCategory( "$limitationType-category" );
3131 * Return the text of a template, after recursively
3132 * replacing any variables or templates within the template.
3134 * @param array $piece The parts of the template
3135 * $piece['title']: the title, i.e. the part before the |
3136 * $piece['parts']: the parameter array
3137 * $piece['lineStart']: whether the brace was at the start of a line
3138 * @param PPFrame $frame The current frame, contains template arguments
3140 * @return string The text of the template
3142 public function braceSubstitution( $piece, $frame ) {
3145 // $text has been filled
3147 // wiki markup in $text should be escaped
3149 // $text is HTML, armour it against wikitext transformation
3151 // Force interwiki transclusion to be done in raw mode not rendered
3152 $forceRawInterwiki = false;
3153 // $text is a DOM node needing expansion in a child frame
3154 $isChildObj = false;
3155 // $text is a DOM node needing expansion in the current frame
3156 $isLocalObj = false;
3158 # Title object, where $text came from
3161 # $part1 is the bit before the first |, and must contain only title characters.
3162 # Various prefixes will be stripped from it later.
3163 $titleWithSpaces = $frame->expand( $piece['title'] );
3164 $part1 = trim( $titleWithSpaces );
3167 # Original title text preserved for various purposes
3168 $originalTitle = $part1;
3170 # $args is a list of argument nodes, starting from index 0, not including $part1
3171 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3172 # below won't work b/c this $args isn't an object
3173 $args = ( $piece['parts'] == null ) ?
[] : $piece['parts'];
3175 $profileSection = null; // profile templates
3179 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3181 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3182 # Decide whether to expand template or keep wikitext as-is.
3183 if ( $this->ot
['wiki'] ) {
3184 if ( $substMatch === false ) {
3185 $literal = true; # literal when in PST with no prefix
3187 $literal = false; # expand when in PST with subst: or safesubst:
3190 if ( $substMatch == 'subst' ) {
3191 $literal = true; # literal when not in PST with plain subst:
3193 $literal = false; # expand when not in PST with safesubst: or no prefix
3197 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3204 if ( !$found && $args->getLength() == 0 ) {
3205 $id = $this->mVariables
->matchStartToEnd( $part1 );
3206 if ( $id !== false ) {
3207 $text = $this->getVariableValue( $id, $frame );
3208 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3209 $this->mOutput
->updateCacheExpiry(
3210 $this->magicWordFactory
->getCacheTTL( $id ) );
3216 # MSG, MSGNW and RAW
3219 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3220 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3223 # Remove obsolete MSG:
3224 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3225 $mwMsg->matchStartAndRemove( $part1 );
3229 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3230 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3231 $forceRawInterwiki = true;
3237 $colonPos = strpos( $part1, ':' );
3238 if ( $colonPos !== false ) {
3239 $func = substr( $part1, 0, $colonPos );
3240 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3241 $argsLength = $args->getLength();
3242 for ( $i = 0; $i < $argsLength; $i++
) {
3243 $funcArgs[] = $args->item( $i );
3246 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3248 // Extract any forwarded flags
3249 if ( isset( $result['title'] ) ) {
3250 $title = $result['title'];
3252 if ( isset( $result['found'] ) ) {
3253 $found = $result['found'];
3255 if ( array_key_exists( 'text', $result ) ) {
3257 $text = $result['text'];
3259 if ( isset( $result['nowiki'] ) ) {
3260 $nowiki = $result['nowiki'];
3262 if ( isset( $result['isHTML'] ) ) {
3263 $isHTML = $result['isHTML'];
3265 if ( isset( $result['forceRawInterwiki'] ) ) {
3266 $forceRawInterwiki = $result['forceRawInterwiki'];
3268 if ( isset( $result['isChildObj'] ) ) {
3269 $isChildObj = $result['isChildObj'];
3271 if ( isset( $result['isLocalObj'] ) ) {
3272 $isLocalObj = $result['isLocalObj'];
3277 # Finish mangling title and then check for loops.
3278 # Set $title to a Title object and $titleText to the PDBK
3281 # Split the title into page and subpage
3283 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3284 if ( $part1 !== $relative ) {
3286 $ns = $this->mTitle
->getNamespace();
3288 $title = Title
::newFromText( $part1, $ns );
3290 $titleText = $title->getPrefixedText();
3291 # Check for language variants if the template is not found
3292 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3293 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3295 # Do recursion depth check
3296 $limit = $this->mOptions
->getMaxTemplateDepth();
3297 if ( $frame->depth
>= $limit ) {
3299 $text = '<span class="error">'
3300 . wfMessage( 'parser-template-recursion-depth-warning' )
3301 ->numParams( $limit )->inContentLanguage()->text()
3307 # Load from database
3308 if ( !$found && $title ) {
3309 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3310 if ( !$title->isExternal() ) {
3311 if ( $title->isSpecialPage()
3312 && $this->mOptions
->getAllowSpecialInclusion()
3313 && $this->ot
['html']
3315 $specialPage = $this->specialPageFactory
->getPage( $title->getDBkey() );
3316 // Pass the template arguments as URL parameters.
3317 // "uselang" will have no effect since the Language object
3318 // is forced to the one defined in ParserOptions.
3320 $argsLength = $args->getLength();
3321 for ( $i = 0; $i < $argsLength; $i++
) {
3322 $bits = $args->item( $i )->splitArg();
3323 if ( strval( $bits['index'] ) === '' ) {
3324 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3325 $value = trim( $frame->expand( $bits['value'] ) );
3326 $pageArgs[$name] = $value;
3330 // Create a new context to execute the special page
3331 $context = new RequestContext
;
3332 $context->setTitle( $title );
3333 $context->setRequest( new FauxRequest( $pageArgs ) );
3334 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3335 $context->setUser( $this->getUser() );
3337 // If this page is cached, then we better not be per user.
3338 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3340 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3341 $ret = $this->specialPageFactory
->capturePath( $title, $context, $this->getLinkRenderer() );
3343 $text = $context->getOutput()->getHTML();
3344 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3347 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3348 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3349 $specialPage->maxIncludeCacheTime()
3353 } elseif ( $this->nsInfo
->isNonincludable( $title->getNamespace() ) ) {
3354 $found = false; # access denied
3355 wfDebug( __METHOD__
. ": template inclusion denied for " .
3356 $title->getPrefixedDBkey() . "\n" );
3358 list( $text, $title ) = $this->getTemplateDom( $title );
3359 if ( $text !== false ) {
3365 # If the title is valid but undisplayable, make a link to it
3366 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3367 $text = "[[:$titleText]]";
3370 } elseif ( $title->isTrans() ) {
3371 # Interwiki transclusion
3372 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3373 $text = $this->interwikiTransclude( $title, 'render' );
3376 $text = $this->interwikiTransclude( $title, 'raw' );
3377 # Preprocess it like a template
3378 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3384 # Do infinite loop check
3385 # This has to be done after redirect resolution to avoid infinite loops via redirects
3386 if ( !$frame->loopCheck( $title ) ) {
3388 $text = '<span class="error">'
3389 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3391 $this->addTrackingCategory( 'template-loop-category' );
3392 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3393 wfEscapeWikiText( $titleText ) )->text() );
3394 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3398 # If we haven't found text to substitute by now, we're done
3399 # Recover the source wikitext and return it
3401 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3402 if ( $profileSection ) {
3403 $this->mProfiler
->scopedProfileOut( $profileSection );
3405 return [ 'object' => $text ];
3408 # Expand DOM-style return values in a child frame
3409 if ( $isChildObj ) {
3410 # Clean up argument array
3411 $newFrame = $frame->newChild( $args, $title );
3414 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3415 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3416 # Expansion is eligible for the empty-frame cache
3417 $text = $newFrame->cachedExpand( $titleText, $text );
3419 # Uncached expansion
3420 $text = $newFrame->expand( $text );
3423 if ( $isLocalObj && $nowiki ) {
3424 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3425 $isLocalObj = false;
3428 if ( $profileSection ) {
3429 $this->mProfiler
->scopedProfileOut( $profileSection );
3432 # Replace raw HTML by a placeholder
3434 $text = $this->insertStripItem( $text );
3435 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3436 # Escape nowiki-style return values
3437 $text = wfEscapeWikiText( $text );
3438 } elseif ( is_string( $text )
3439 && !$piece['lineStart']
3440 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3442 # T2529: if the template begins with a table or block-level
3443 # element, it should be treated as beginning a new line.
3444 # This behavior is somewhat controversial.
3445 $text = "\n" . $text;
3448 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3449 # Error, oversize inclusion
3450 if ( $titleText !== false ) {
3451 # Make a working, properly escaped link if possible (T25588)
3452 $text = "[[:$titleText]]";
3454 # This will probably not be a working link, but at least it may
3455 # provide some hint of where the problem is
3456 preg_replace( '/^:/', '', $originalTitle );
3457 $text = "[[:$originalTitle]]";
3459 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3460 . 'post-expand include size too large -->' );
3461 $this->limitationWarn( 'post-expand-template-inclusion' );
3464 if ( $isLocalObj ) {
3465 $ret = [ 'object' => $text ];
3467 $ret = [ 'text' => $text ];
3474 * Call a parser function and return an array with text and flags.
3476 * The returned array will always contain a boolean 'found', indicating
3477 * whether the parser function was found or not. It may also contain the
3479 * text: string|object, resulting wikitext or PP DOM object
3480 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3481 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3482 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3483 * nowiki: bool, wiki markup in $text should be escaped
3486 * @param PPFrame $frame The current frame, contains template arguments
3487 * @param string $function Function name
3488 * @param array $args Arguments to the function
3489 * @throws MWException
3492 public function callParserFunction( $frame, $function, array $args = [] ) {
3493 # Case sensitive functions
3494 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3495 $function = $this->mFunctionSynonyms
[1][$function];
3497 # Case insensitive functions
3498 $function = $this->contLang
->lc( $function );
3499 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3500 $function = $this->mFunctionSynonyms
[0][$function];
3502 return [ 'found' => false ];
3506 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3508 // Avoid PHP 7.1 warning from passing $this by reference
3511 $allArgs = [ &$parser ];
3512 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3513 # Convert arguments to PPNodes and collect for appending to $allArgs
3515 foreach ( $args as $k => $v ) {
3516 if ( $v instanceof PPNode ||
$k === 0 ) {
3519 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3523 # Add a frame parameter, and pass the arguments as an array
3524 $allArgs[] = $frame;
3525 $allArgs[] = $funcArgs;
3527 # Convert arguments to plain text and append to $allArgs
3528 foreach ( $args as $k => $v ) {
3529 if ( $v instanceof PPNode
) {
3530 $allArgs[] = trim( $frame->expand( $v ) );
3531 } elseif ( is_int( $k ) && $k >= 0 ) {
3532 $allArgs[] = trim( $v );
3534 $allArgs[] = trim( "$k=$v" );
3539 $result = $callback( ...$allArgs );
3541 # The interface for function hooks allows them to return a wikitext
3542 # string or an array containing the string and any flags. This mungs
3543 # things around to match what this method should return.
3544 if ( !is_array( $result ) ) {
3550 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3551 $result['text'] = $result[0];
3553 unset( $result[0] );
3560 $preprocessFlags = 0;
3561 if ( isset( $result['noparse'] ) ) {
3562 $noparse = $result['noparse'];
3564 if ( isset( $result['preprocessFlags'] ) ) {
3565 $preprocessFlags = $result['preprocessFlags'];
3569 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3570 $result['isChildObj'] = true;
3577 * Get the semi-parsed DOM representation of a template with a given title,
3578 * and its redirect destination title. Cached.
3580 * @param Title $title
3584 public function getTemplateDom( $title ) {
3585 $cacheTitle = $title;
3586 $titleText = $title->getPrefixedDBkey();
3588 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3589 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3590 $title = Title
::makeTitle( $ns, $dbk );
3591 $titleText = $title->getPrefixedDBkey();
3593 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3594 return [ $this->mTplDomCache
[$titleText], $title ];
3597 # Cache miss, go to the database
3598 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3600 if ( $text === false ) {
3601 $this->mTplDomCache
[$titleText] = false;
3602 return [ false, $title ];
3605 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3606 $this->mTplDomCache
[$titleText] = $dom;
3608 if ( !$title->equals( $cacheTitle ) ) {
3609 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3610 [ $title->getNamespace(), $title->getDBkey() ];
3613 return [ $dom, $title ];
3617 * Fetch the current revision of a given title. Note that the revision
3618 * (and even the title) may not exist in the database, so everything
3619 * contributing to the output of the parser should use this method
3620 * where possible, rather than getting the revisions themselves. This
3621 * method also caches its results, so using it benefits performance.
3624 * @param Title $title
3627 public function fetchCurrentRevisionOfTitle( $title ) {
3628 $cacheKey = $title->getPrefixedDBkey();
3629 if ( !$this->currentRevisionCache
) {
3630 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3632 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3633 $this->currentRevisionCache
->set( $cacheKey,
3634 // Defaults to Parser::statelessFetchRevision()
3635 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3638 return $this->currentRevisionCache
->get( $cacheKey );
3642 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3643 * without passing them on to it.
3646 * @param Title $title
3647 * @param Parser|bool $parser
3648 * @return Revision|bool False if missing
3650 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3651 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3657 * Fetch the unparsed text of a template and register a reference to it.
3658 * @param Title $title
3659 * @return array ( string or false, Title )
3661 public function fetchTemplateAndTitle( $title ) {
3662 // Defaults to Parser::statelessFetchTemplate()
3663 $templateCb = $this->mOptions
->getTemplateCallback();
3664 $stuff = call_user_func( $templateCb, $title, $this );
3665 // We use U+007F DELETE to distinguish strip markers from regular text.
3666 $text = $stuff['text'];
3667 if ( is_string( $stuff['text'] ) ) {
3668 $text = strtr( $text, "\x7f", "?" );
3670 $finalTitle = $stuff['finalTitle'] ??
$title;
3671 if ( isset( $stuff['deps'] ) ) {
3672 foreach ( $stuff['deps'] as $dep ) {
3673 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3674 if ( $dep['title']->equals( $this->getTitle() ) ) {
3675 // If we transclude ourselves, the final result
3676 // will change based on the new version of the page
3677 $this->mOutput
->setFlag( 'vary-revision' );
3681 return [ $text, $finalTitle ];
3685 * Fetch the unparsed text of a template and register a reference to it.
3686 * @param Title $title
3687 * @return string|bool
3689 public function fetchTemplate( $title ) {
3690 return $this->fetchTemplateAndTitle( $title )[0];
3694 * Static function to get a template
3695 * Can be overridden via ParserOptions::setTemplateCallback().
3697 * @param Title $title
3698 * @param bool|Parser $parser
3702 public static function statelessFetchTemplate( $title, $parser = false ) {
3703 $text = $skip = false;
3704 $finalTitle = $title;
3707 # Loop to fetch the article, with up to 1 redirect
3708 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3709 # Give extensions a chance to select the revision instead
3710 $id = false; # Assume current
3711 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3712 [ $parser, $title, &$skip, &$id ] );
3718 'page_id' => $title->getArticleID(),
3725 $rev = Revision
::newFromId( $id );
3726 } elseif ( $parser ) {
3727 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3729 $rev = Revision
::newFromTitle( $title );
3731 $rev_id = $rev ?
$rev->getId() : 0;
3732 # If there is no current revision, there is no page
3733 if ( $id === false && !$rev ) {
3734 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3735 $linkCache->addBadLinkObj( $title );
3740 'page_id' => $title->getArticleID(),
3741 'rev_id' => $rev_id ];
3742 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3743 # We fetched a rev from a different title; register it too...
3745 'title' => $rev->getTitle(),
3746 'page_id' => $rev->getPage(),
3747 'rev_id' => $rev_id ];
3751 $content = $rev->getContent();
3752 $text = $content ?
$content->getWikitextForTransclusion() : null;
3754 Hooks
::run( 'ParserFetchTemplate',
3755 [ $parser, $title, $rev, &$text, &$deps ] );
3757 if ( $text === false ||
$text === null ) {
3761 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3762 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3763 lcfirst( $title->getText() ) )->inContentLanguage();
3764 if ( !$message->exists() ) {
3768 $content = $message->content();
3769 $text = $message->plain();
3777 $finalTitle = $title;
3778 $title = $content->getRedirectTarget();
3782 'finalTitle' => $finalTitle,
3787 * Fetch a file and its title and register a reference to it.
3788 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3789 * @param Title $title
3790 * @param array $options Array of options to RepoGroup::findFile
3792 * @deprecated since 1.32, use fetchFileAndTitle instead
3794 public function fetchFile( $title, $options = [] ) {
3795 wfDeprecated( __METHOD__
, '1.32' );
3796 return $this->fetchFileAndTitle( $title, $options )[0];
3800 * Fetch a file and its title and register a reference to it.
3801 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3802 * @param Title $title
3803 * @param array $options Array of options to RepoGroup::findFile
3804 * @return array ( File or false, Title of file )
3806 public function fetchFileAndTitle( $title, $options = [] ) {
3807 $file = $this->fetchFileNoRegister( $title, $options );
3809 $time = $file ?
$file->getTimestamp() : false;
3810 $sha1 = $file ?
$file->getSha1() : false;
3811 # Register the file as a dependency...
3812 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3813 if ( $file && !$title->equals( $file->getTitle() ) ) {
3814 # Update fetched file title
3815 $title = $file->getTitle();
3816 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3818 return [ $file, $title ];
3822 * Helper function for fetchFileAndTitle.
3824 * Also useful if you need to fetch a file but not use it yet,
3825 * for example to get the file's handler.
3827 * @param Title $title
3828 * @param array $options Array of options to RepoGroup::findFile
3831 protected function fetchFileNoRegister( $title, $options = [] ) {
3832 if ( isset( $options['broken'] ) ) {
3833 $file = false; // broken thumbnail forced by hook
3834 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3835 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3836 } else { // get by (name,timestamp)
3837 $file = wfFindFile( $title, $options );
3843 * Transclude an interwiki link.
3845 * @param Title $title
3846 * @param string $action Usually one of (raw, render)
3850 public function interwikiTransclude( $title, $action ) {
3851 if ( !$this->siteConfig
->get( 'EnableScaryTranscluding' ) ) {
3852 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3855 $url = $title->getFullURL( [ 'action' => $action ] );
3856 if ( strlen( $url ) > 1024 ) {
3857 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3860 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3862 $fname = __METHOD__
;
3863 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3865 $data = $cache->getWithSetCallback(
3866 $cache->makeGlobalKey(
3867 'interwiki-transclude',
3868 ( $wikiId !== false ) ?
$wikiId : 'external',
3871 $this->siteConfig
->get( 'TranscludeCacheExpiry' ),
3872 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3873 $req = MWHttpRequest
::factory( $url, [], $fname );
3875 $status = $req->execute(); // Status object
3876 if ( !$status->isOK() ) {
3877 $ttl = $cache::TTL_UNCACHEABLE
;
3878 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3879 $ttl = min( $cache::TTL_LAGGED
, $ttl );
3883 'text' => $status->isOK() ?
$req->getContent() : null,
3884 'code' => $req->getStatus()
3888 'checkKeys' => ( $wikiId !== false )
3889 ?
[ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
3891 'pcGroup' => 'interwiki-transclude:5',
3892 'pcTTL' => $cache::TTL_PROC_LONG
3896 if ( is_string( $data['text'] ) ) {
3897 $text = $data['text'];
3898 } elseif ( $data['code'] != 200 ) {
3899 // Though we failed to fetch the content, this status is useless.
3900 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
3901 ->params( $url, $data['code'] )->inContentLanguage()->text();
3903 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3910 * Triple brace replacement -- used for template arguments
3913 * @param array $piece
3914 * @param PPFrame $frame
3918 public function argSubstitution( $piece, $frame ) {
3920 $parts = $piece['parts'];
3921 $nameWithSpaces = $frame->expand( $piece['title'] );
3922 $argName = trim( $nameWithSpaces );
3924 $text = $frame->getArgument( $argName );
3925 if ( $text === false && $parts->getLength() > 0
3926 && ( $this->ot
['html']
3928 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3931 # No match in frame, use the supplied default
3932 $object = $parts->item( 0 )->getChildren();
3934 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3935 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3936 $this->limitationWarn( 'post-expand-template-argument' );
3939 if ( $text === false && $object === false ) {
3941 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3943 if ( $error !== false ) {
3946 if ( $object !== false ) {
3947 $ret = [ 'object' => $object ];
3949 $ret = [ 'text' => $text ];
3956 * Return the text to be used for a given extension tag.
3957 * This is the ghost of strip().
3959 * @param array $params Associative array of parameters:
3960 * name PPNode for the tag name
3961 * attr PPNode for unparsed text where tag attributes are thought to be
3962 * attributes Optional associative array of parsed attributes
3963 * inner Contents of extension element
3964 * noClose Original text did not have a close tag
3965 * @param PPFrame $frame
3967 * @throws MWException
3970 public function extensionSubstitution( $params, $frame ) {
3971 static $errorStr = '<span class="error">';
3972 static $errorLen = 20;
3974 $name = $frame->expand( $params['name'] );
3975 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3976 // Probably expansion depth or node count exceeded. Just punt the
3981 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3982 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3987 // We can't safely check if the expansion for $content resulted in an
3988 // error, because the content could happen to be the error string
3990 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3992 $marker = self
::MARKER_PREFIX
. "-$name-"
3993 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3995 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3996 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3997 if ( $isFunctionTag ) {
3998 $markerType = 'none';
4000 $markerType = 'general';
4002 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4003 $name = strtolower( $name );
4004 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4005 if ( isset( $params['attributes'] ) ) {
4006 $attributes +
= $params['attributes'];
4009 if ( isset( $this->mTagHooks
[$name] ) ) {
4010 $output = call_user_func_array( $this->mTagHooks
[$name],
4011 [ $content, $attributes, $this, $frame ] );
4012 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4013 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4015 // Avoid PHP 7.1 warning from passing $this by reference
4017 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
4019 $output = '<span class="error">Invalid tag extension name: ' .
4020 htmlspecialchars( $name ) . '</span>';
4023 if ( is_array( $output ) ) {
4026 $output = $flags[0];
4027 if ( isset( $flags['markerType'] ) ) {
4028 $markerType = $flags['markerType'];
4032 if ( is_null( $attrText ) ) {
4035 if ( isset( $params['attributes'] ) ) {
4036 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4037 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4038 htmlspecialchars( $attrValue ) . '"';
4041 if ( $content === null ) {
4042 $output = "<$name$attrText/>";
4044 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4045 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4049 $output = "<$name$attrText>$content$close";
4053 if ( $markerType === 'none' ) {
4055 } elseif ( $markerType === 'nowiki' ) {
4056 $this->mStripState
->addNoWiki( $marker, $output );
4057 } elseif ( $markerType === 'general' ) {
4058 $this->mStripState
->addGeneral( $marker, $output );
4060 throw new MWException( __METHOD__
. ': invalid marker type' );
4066 * Increment an include size counter
4068 * @param string $type The type of expansion
4069 * @param int $size The size of the text
4070 * @return bool False if this inclusion would take it over the maximum, true otherwise
4072 public function incrementIncludeSize( $type, $size ) {
4073 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4076 $this->mIncludeSizes
[$type] +
= $size;
4082 * Increment the expensive function count
4084 * @return bool False if the limit has been exceeded
4086 public function incrementExpensiveFunctionCount() {
4087 $this->mExpensiveFunctionCount++
;
4088 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4092 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4093 * Fills $this->mDoubleUnderscores, returns the modified text
4095 * @param string $text
4099 public function doDoubleUnderscore( $text ) {
4100 # The position of __TOC__ needs to be recorded
4101 $mw = $this->magicWordFactory
->get( 'toc' );
4102 if ( $mw->match( $text ) ) {
4103 $this->mShowToc
= true;
4104 $this->mForceTocPosition
= true;
4106 # Set a placeholder. At the end we'll fill it in with the TOC.
4107 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4109 # Only keep the first one.
4110 $text = $mw->replace( '', $text );
4113 # Now match and remove the rest of them
4114 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4115 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4117 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4118 $this->mOutput
->mNoGallery
= true;
4120 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4121 $this->mShowToc
= false;
4123 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4124 && $this->mTitle
->getNamespace() == NS_CATEGORY
4126 $this->addTrackingCategory( 'hidden-category-category' );
4128 # (T10068) Allow control over whether robots index a page.
4129 # __INDEX__ always overrides __NOINDEX__, see T16899
4130 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4131 $this->mOutput
->setIndexPolicy( 'noindex' );
4132 $this->addTrackingCategory( 'noindex-category' );
4134 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4135 $this->mOutput
->setIndexPolicy( 'index' );
4136 $this->addTrackingCategory( 'index-category' );
4139 # Cache all double underscores in the database
4140 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4141 $this->mOutput
->setProperty( $key, '' );
4148 * @see ParserOutput::addTrackingCategory()
4149 * @param string $msg Message key
4150 * @return bool Whether the addition was successful
4152 public function addTrackingCategory( $msg ) {
4153 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4157 * This function accomplishes several tasks:
4158 * 1) Auto-number headings if that option is enabled
4159 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4160 * 3) Add a Table of contents on the top for users who have enabled the option
4161 * 4) Auto-anchor headings
4163 * It loops through all headlines, collects the necessary data, then splits up the
4164 * string and re-inserts the newly formatted headlines.
4166 * @param string $text
4167 * @param string $origText Original, untouched wikitext
4168 * @param bool $isMain
4169 * @return mixed|string
4172 public function formatHeadings( $text, $origText, $isMain = true ) {
4173 # Inhibit editsection links if requested in the page
4174 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4175 $maybeShowEditLink = false;
4177 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4180 # Get all headlines for numbering them and adding funky stuff like [edit]
4181 # links - this is for later, but we need the number of headlines right now
4182 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4183 # be trimmed here since whitespace in HTML headings is significant.
4185 $numMatches = preg_match_all(
4186 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4191 # if there are fewer than 4 headlines in the article, do not show TOC
4192 # unless it's been explicitly enabled.
4193 $enoughToc = $this->mShowToc
&&
4194 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4196 # Allow user to stipulate that a page should have a "new section"
4197 # link added via __NEWSECTIONLINK__
4198 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4199 $this->mOutput
->setNewSection( true );
4202 # Allow user to remove the "new section"
4203 # link via __NONEWSECTIONLINK__
4204 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4205 $this->mOutput
->hideNewSection( true );
4208 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4209 # override above conditions and always show TOC above first header
4210 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4211 $this->mShowToc
= true;
4219 # Ugh .. the TOC should have neat indentation levels which can be
4220 # passed to the skin functions. These are determined here
4224 $sublevelCount = [];
4230 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4231 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4232 $oldType = $this->mOutputType
;
4233 $this->setOutputType( self
::OT_WIKI
);
4234 $frame = $this->getPreprocessor()->newFrame();
4235 $root = $this->preprocessToDom( $origText );
4236 $node = $root->getFirstChild();
4241 $headlines = $numMatches !== false ?
$matches[3] : [];
4243 $maxTocLevel = $this->siteConfig
->get( 'MaxTocLevel' );
4244 foreach ( $headlines as $headline ) {
4245 $isTemplate = false;
4247 $sectionIndex = false;
4249 $markerMatches = [];
4250 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4251 $serial = $markerMatches[1];
4252 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4253 $isTemplate = ( $titleText != $baseTitleText );
4254 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4258 $prevlevel = $level;
4260 $level = $matches[1][$headlineCount];
4262 if ( $level > $prevlevel ) {
4263 # Increase TOC level
4265 $sublevelCount[$toclevel] = 0;
4266 if ( $toclevel < $maxTocLevel ) {
4267 $prevtoclevel = $toclevel;
4268 $toc .= Linker
::tocIndent();
4271 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4272 # Decrease TOC level, find level to jump to
4274 for ( $i = $toclevel; $i > 0; $i-- ) {
4275 if ( $levelCount[$i] == $level ) {
4276 # Found last matching level
4279 } elseif ( $levelCount[$i] < $level ) {
4280 # Found first matching level below current level
4288 if ( $toclevel < $maxTocLevel ) {
4289 if ( $prevtoclevel < $maxTocLevel ) {
4290 # Unindent only if the previous toc level was shown :p
4291 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4292 $prevtoclevel = $toclevel;
4294 $toc .= Linker
::tocLineEnd();
4298 # No change in level, end TOC line
4299 if ( $toclevel < $maxTocLevel ) {
4300 $toc .= Linker
::tocLineEnd();
4304 $levelCount[$toclevel] = $level;
4306 # count number of headlines for each level
4307 $sublevelCount[$toclevel]++
;
4309 for ( $i = 1; $i <= $toclevel; $i++
) {
4310 if ( !empty( $sublevelCount[$i] ) ) {
4314 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4319 # The safe header is a version of the header text safe to use for links
4321 # Remove link placeholders by the link text.
4322 # <!--LINK number-->
4324 # link text with suffix
4325 # Do this before unstrip since link text can contain strip markers
4326 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4328 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4329 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4331 # Remove any <style> or <script> tags (T198618)
4332 $safeHeadline = preg_replace(
4333 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4338 # Strip out HTML (first regex removes any tag not allowed)
4340 # * <sup> and <sub> (T10393)
4344 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4345 # * <s> and <strike> (T35715)
4346 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4347 # to allow setting directionality in toc items.
4348 $tocline = preg_replace(
4350 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4351 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4357 # Strip '<span></span>', which is the result from the above if
4358 # <span id="foo"></span> is used to produce an additional anchor
4360 $tocline = str_replace( '<span></span>', '', $tocline );
4362 $tocline = trim( $tocline );
4364 # For the anchor, strip out HTML-y stuff period
4365 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4366 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4368 # Save headline for section edit hint before it's escaped
4369 $headlineHint = $safeHeadline;
4371 # Decode HTML entities
4372 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4374 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4376 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4377 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4378 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4379 if ( $fallbackHeadline === $safeHeadline ) {
4380 # No reason to have both (in fact, we can't)
4381 $fallbackHeadline = false;
4384 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4385 # @todo FIXME: We may be changing them depending on the current locale.
4386 $arrayKey = strtolower( $safeHeadline );
4387 if ( $fallbackHeadline === false ) {
4388 $fallbackArrayKey = false;
4390 $fallbackArrayKey = strtolower( $fallbackHeadline );
4393 # Create the anchor for linking from the TOC to the section
4394 $anchor = $safeHeadline;
4395 $fallbackAnchor = $fallbackHeadline;
4396 if ( isset( $refers[$arrayKey] ) ) {
4397 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4398 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4400 $linkAnchor .= "_$i";
4401 $refers["${arrayKey}_$i"] = true;
4403 $refers[$arrayKey] = true;
4405 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4406 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4407 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4408 $fallbackAnchor .= "_$i";
4409 $refers["${fallbackArrayKey}_$i"] = true;
4411 $refers[$fallbackArrayKey] = true;
4414 # Don't number the heading if it is the only one (looks silly)
4415 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4416 # the two are different if the line contains a link
4417 $headline = Html
::element(
4419 [ 'class' => 'mw-headline-number' ],
4421 ) . ' ' . $headline;
4424 if ( $enoughToc && ( !isset( $maxTocLevel ) ||
$toclevel < $maxTocLevel ) ) {
4425 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4426 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4429 # Add the section to the section tree
4430 # Find the DOM node for this header
4431 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4432 while ( $node && !$noOffset ) {
4433 if ( $node->getName() === 'h' ) {
4434 $bits = $node->splitHeading();
4435 if ( $bits['i'] == $sectionIndex ) {
4439 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4440 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4441 $node = $node->getNextSibling();
4444 'toclevel' => $toclevel,
4447 'number' => $numbering,
4448 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4449 'fromtitle' => $titleText,
4450 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4451 'anchor' => $anchor,
4454 # give headline the correct <h#> tag
4455 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4456 // Output edit section links as markers with styles that can be customized by skins
4457 if ( $isTemplate ) {
4458 # Put a T flag in the section identifier, to indicate to extractSections()
4459 # that sections inside <includeonly> should be counted.
4460 $editsectionPage = $titleText;
4461 $editsectionSection = "T-$sectionIndex";
4462 $editsectionContent = null;
4464 $editsectionPage = $this->mTitle
->getPrefixedText();
4465 $editsectionSection = $sectionIndex;
4466 $editsectionContent = $headlineHint;
4468 // We use a bit of pesudo-xml for editsection markers. The
4469 // language converter is run later on. Using a UNIQ style marker
4470 // leads to the converter screwing up the tokens when it
4471 // converts stuff. And trying to insert strip tags fails too. At
4472 // this point all real inputted tags have already been escaped,
4473 // so we don't have to worry about a user trying to input one of
4474 // these markers directly. We use a page and section attribute
4475 // to stop the language converter from converting these
4476 // important bits of data, but put the headline hint inside a
4477 // content block because the language converter is supposed to
4478 // be able to convert that piece of data.
4479 // Gets replaced with html in ParserOutput::getText
4480 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4481 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4482 if ( $editsectionContent !== null ) {
4483 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4490 $head[$headlineCount] = Linker
::makeHeadline( $level,
4491 $matches['attrib'][$headlineCount], $anchor, $headline,
4492 $editlink, $fallbackAnchor );
4497 $this->setOutputType( $oldType );
4499 # Never ever show TOC if no headers
4500 if ( $numVisible < 1 ) {
4505 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4506 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4508 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4509 $this->mOutput
->setTOCHTML( $toc );
4510 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4514 $this->mOutput
->setSections( $tocraw );
4517 # split up and insert constructed headlines
4518 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4521 // build an array of document sections
4523 foreach ( $blocks as $block ) {
4524 // $head is zero-based, sections aren't.
4525 if ( empty( $head[$i - 1] ) ) {
4526 $sections[$i] = $block;
4528 $sections[$i] = $head[$i - 1] . $block;
4532 * Send a hook, one per section.
4533 * The idea here is to be able to make section-level DIVs, but to do so in a
4534 * lower-impact, more correct way than r50769
4537 * $section : the section number
4538 * &$sectionContent : ref to the content of the section
4539 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4541 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4546 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4547 // append the TOC at the beginning
4548 // Top anchor now in skin
4549 $sections[0] .= $toc . "\n";
4552 $full .= implode( '', $sections );
4554 if ( $this->mForceTocPosition
) {
4555 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4562 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4563 * conversion, substituting signatures, {{subst:}} templates, etc.
4565 * @param string $text The text to transform
4566 * @param Title $title The Title object for the current article
4567 * @param User $user The User object describing the current user
4568 * @param ParserOptions $options Parsing options
4569 * @param bool $clearState Whether to clear the parser state first
4570 * @return string The altered wiki markup
4572 public function preSaveTransform( $text, Title
$title, User
$user,
4573 ParserOptions
$options, $clearState = true
4575 if ( $clearState ) {
4576 $magicScopeVariable = $this->lock();
4578 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4579 $this->setUser( $user );
4581 // Strip U+0000 NULL (T159174)
4582 $text = str_replace( "\000", '', $text );
4584 // We still normalize line endings for backwards-compatibility
4585 // with other code that just calls PST, but this should already
4586 // be handled in TextContent subclasses
4587 $text = TextContent
::normalizeLineEndings( $text );
4589 if ( $options->getPreSaveTransform() ) {
4590 $text = $this->pstPass2( $text, $user );
4592 $text = $this->mStripState
->unstripBoth( $text );
4594 $this->setUser( null ); # Reset
4600 * Pre-save transform helper function
4602 * @param string $text
4607 private function pstPass2( $text, $user ) {
4608 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4609 # $this->contLang here in order to give everyone the same signature and use the default one
4610 # rather than the one selected in each user's preferences. (see also T14815)
4611 $ts = $this->mOptions
->getTimestamp();
4612 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4613 $ts = $timestamp->format( 'YmdHis' );
4614 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4616 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4618 # Variable replacement
4619 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4620 $text = $this->replaceVariables( $text );
4622 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4623 # which may corrupt this parser instance via its wfMessage()->text() call-
4626 if ( strpos( $text, '~~~' ) !== false ) {
4627 $sigText = $this->getUserSig( $user );
4628 $text = strtr( $text, [
4630 '~~~~' => "$sigText $d",
4633 # The main two signature forms used above are time-sensitive
4634 $this->mOutput
->setFlag( 'user-signature' );
4637 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4638 $tc = '[' . Title
::legalChars() . ']';
4639 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4641 // [[ns:page (context)|]]
4642 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4643 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4644 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4645 // [[ns:page (context), context|]] (using either single or double-width comma)
4646 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4647 // [[|page]] (reverse pipe trick: add context from page title)
4648 $p2 = "/\[\[\\|($tc+)]]/";
4650 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4651 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4652 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4653 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4655 $t = $this->mTitle
->getText();
4657 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4658 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4659 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4660 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4662 # if there's no context, don't bother duplicating the title
4663 $text = preg_replace( $p2, '[[\\1]]', $text );
4670 * Fetch the user's signature text, if any, and normalize to
4671 * validated, ready-to-insert wikitext.
4672 * If you have pre-fetched the nickname or the fancySig option, you can
4673 * specify them here to save a database query.
4674 * Do not reuse this parser instance after calling getUserSig(),
4675 * as it may have changed if it's the $wgParser.
4677 * @param User &$user
4678 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4679 * @param bool|null $fancySig whether the nicknname is the complete signature
4680 * or null to use default value
4683 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4684 $username = $user->getName();
4686 # If not given, retrieve from the user object.
4687 if ( $nickname === false ) {
4688 $nickname = $user->getOption( 'nickname' );
4691 if ( is_null( $fancySig ) ) {
4692 $fancySig = $user->getBoolOption( 'fancysig' );
4695 $nickname = $nickname == null ?
$username : $nickname;
4697 if ( mb_strlen( $nickname ) > $this->siteConfig
->get( 'MaxSigChars' ) ) {
4698 $nickname = $username;
4699 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4700 } elseif ( $fancySig !== false ) {
4701 # Sig. might contain markup; validate this
4702 if ( $this->validateSig( $nickname ) !== false ) {
4703 # Validated; clean up (if needed) and return it
4704 return $this->cleanSig( $nickname, true );
4706 # Failed to validate; fall back to the default
4707 $nickname = $username;
4708 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4712 # Make sure nickname doesnt get a sig in a sig
4713 $nickname = self
::cleanSigInSig( $nickname );
4715 # If we're still here, make it a link to the user page
4716 $userText = wfEscapeWikiText( $username );
4717 $nickText = wfEscapeWikiText( $nickname );
4718 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4720 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4721 ->title( $this->getTitle() )->text();
4725 * Check that the user's signature contains no bad XML
4727 * @param string $text
4728 * @return string|bool An expanded string, or false if invalid.
4730 public function validateSig( $text ) {
4731 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4735 * Clean up signature text
4737 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4738 * 2) Substitute all transclusions
4740 * @param string $text
4741 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4742 * @return string Signature text
4744 public function cleanSig( $text, $parsing = false ) {
4747 $magicScopeVariable = $this->lock();
4748 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4751 # Option to disable this feature
4752 if ( !$this->mOptions
->getCleanSignatures() ) {
4756 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4757 # => Move this logic to braceSubstitution()
4758 $substWord = $this->magicWordFactory
->get( 'subst' );
4759 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4760 $substText = '{{' . $substWord->getSynonym( 0 );
4762 $text = preg_replace( $substRegex, $substText, $text );
4763 $text = self
::cleanSigInSig( $text );
4764 $dom = $this->preprocessToDom( $text );
4765 $frame = $this->getPreprocessor()->newFrame();
4766 $text = $frame->expand( $dom );
4769 $text = $this->mStripState
->unstripBoth( $text );
4776 * Strip 3, 4 or 5 tildes out of signatures.
4778 * @param string $text
4779 * @return string Signature text with /~{3,5}/ removed
4781 public static function cleanSigInSig( $text ) {
4782 $text = preg_replace( '/~{3,5}/', '', $text );
4787 * Set up some variables which are usually set up in parse()
4788 * so that an external function can call some class members with confidence
4790 * @param Title|null $title
4791 * @param ParserOptions $options
4792 * @param int $outputType
4793 * @param bool $clearState
4795 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4796 $outputType, $clearState = true
4798 $this->startParse( $title, $options, $outputType, $clearState );
4802 * @param Title|null $title
4803 * @param ParserOptions $options
4804 * @param int $outputType
4805 * @param bool $clearState
4807 private function startParse( Title
$title = null, ParserOptions
$options,
4808 $outputType, $clearState = true
4810 $this->setTitle( $title );
4811 $this->mOptions
= $options;
4812 $this->setOutputType( $outputType );
4813 if ( $clearState ) {
4814 $this->clearState();
4819 * Wrapper for preprocess()
4821 * @param string $text The text to preprocess
4822 * @param ParserOptions $options
4823 * @param Title|null $title Title object or null to use $wgTitle
4826 public function transformMsg( $text, $options, $title = null ) {
4827 static $executing = false;
4829 # Guard against infinite recursion
4840 $text = $this->preprocess( $text, $title, $options );
4847 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4848 * The callback should have the following form:
4849 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4851 * Transform and return $text. Use $parser for any required context, e.g. use
4852 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4854 * Hooks may return extended information by returning an array, of which the
4855 * first numbered element (index 0) must be the return string, and all other
4856 * entries are extracted into local variables within an internal function
4857 * in the Parser class.
4859 * This interface (introduced r61913) appears to be undocumented, but
4860 * 'markerType' is used by some core tag hooks to override which strip
4861 * array their results are placed in. **Use great caution if attempting
4862 * this interface, as it is not documented and injudicious use could smash
4863 * private variables.**
4865 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4866 * @param callable $callback The callback function (and object) to use for the tag
4867 * @throws MWException
4868 * @return callable|null The old value of the mTagHooks array associated with the hook
4870 public function setHook( $tag, callable
$callback ) {
4871 $tag = strtolower( $tag );
4872 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4873 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4875 $oldVal = $this->mTagHooks
[$tag] ??
null;
4876 $this->mTagHooks
[$tag] = $callback;
4877 if ( !in_array( $tag, $this->mStripList
) ) {
4878 $this->mStripList
[] = $tag;
4885 * As setHook(), but letting the contents be parsed.
4887 * Transparent tag hooks are like regular XML-style tag hooks, except they
4888 * operate late in the transformation sequence, on HTML instead of wikitext.
4890 * This is probably obsoleted by things dealing with parser frames?
4891 * The only extension currently using it is geoserver.
4894 * @todo better document or deprecate this
4896 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4897 * @param callable $callback The callback function (and object) to use for the tag
4898 * @throws MWException
4899 * @return callable|null The old value of the mTagHooks array associated with the hook
4901 public function setTransparentTagHook( $tag, callable
$callback ) {
4902 $tag = strtolower( $tag );
4903 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4904 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4906 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4907 $this->mTransparentTagHooks
[$tag] = $callback;
4913 * Remove all tag hooks
4915 public function clearTagHooks() {
4916 $this->mTagHooks
= [];
4917 $this->mFunctionTagHooks
= [];
4918 $this->mStripList
= $this->mDefaultStripList
;
4922 * Create a function, e.g. {{sum:1|2|3}}
4923 * The callback function should have the form:
4924 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4926 * Or with Parser::SFH_OBJECT_ARGS:
4927 * function myParserFunction( $parser, $frame, $args ) { ... }
4929 * The callback may either return the text result of the function, or an array with the text
4930 * in element 0, and a number of flags in the other elements. The names of the flags are
4931 * specified in the keys. Valid flags are:
4932 * found The text returned is valid, stop processing the template. This
4934 * nowiki Wiki markup in the return value should be escaped
4935 * isHTML The returned text is HTML, armour it against wikitext transformation
4937 * @param string $id The magic word ID
4938 * @param callable $callback The callback function (and object) to use
4939 * @param int $flags A combination of the following flags:
4940 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4942 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4943 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4944 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4945 * the arguments, and to control the way they are expanded.
4947 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4948 * arguments, for instance:
4949 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4951 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4952 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4953 * working if/when this is changed.
4955 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4958 * Please read the documentation in includes/parser/Preprocessor.php for more information
4959 * about the methods available in PPFrame and PPNode.
4961 * @throws MWException
4962 * @return string|callable The old callback function for this name, if any
4964 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4965 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4966 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4968 # Add to function cache
4969 $mw = $this->magicWordFactory
->get( $id );
4971 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4974 $synonyms = $mw->getSynonyms();
4975 $sensitive = intval( $mw->isCaseSensitive() );
4977 foreach ( $synonyms as $syn ) {
4979 if ( !$sensitive ) {
4980 $syn = $this->contLang
->lc( $syn );
4983 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4986 # Remove trailing colon
4987 if ( substr( $syn, -1, 1 ) === ':' ) {
4988 $syn = substr( $syn, 0, -1 );
4990 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4996 * Get all registered function hook identifiers
5000 public function getFunctionHooks() {
5001 $this->firstCallInit();
5002 return array_keys( $this->mFunctionHooks
);
5006 * Create a tag function, e.g. "<test>some stuff</test>".
5007 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5008 * Unlike parser functions, their content is not preprocessed.
5009 * @param string $tag
5010 * @param callable $callback
5012 * @throws MWException
5015 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
5016 $tag = strtolower( $tag );
5017 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5018 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5020 $old = $this->mFunctionTagHooks
[$tag] ??
null;
5021 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
5023 if ( !in_array( $tag, $this->mStripList
) ) {
5024 $this->mStripList
[] = $tag;
5031 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5032 * Placeholders created in Linker::link()
5034 * @param string &$text
5035 * @param int $options
5037 public function replaceLinkHolders( &$text, $options = 0 ) {
5038 $this->mLinkHolders
->replace( $text );
5042 * Replace "<!--LINK-->" link placeholders with plain text of links
5043 * (not HTML-formatted).
5045 * @param string $text
5048 public function replaceLinkHoldersText( $text ) {
5049 return $this->mLinkHolders
->replaceText( $text );
5053 * Renders an image gallery from a text with one line per image.
5054 * text labels may be given by using |-style alternative text. E.g.
5055 * Image:one.jpg|The number "1"
5056 * Image:tree.jpg|A tree
5057 * given as text will return the HTML of a gallery with two images,
5058 * labeled 'The number "1"' and
5061 * @param string $text
5062 * @param array $params
5063 * @return string HTML
5065 public function renderImageGallery( $text, $params ) {
5067 if ( isset( $params['mode'] ) ) {
5068 $mode = $params['mode'];
5072 $ig = ImageGalleryBase
::factory( $mode );
5073 } catch ( Exception
$e ) {
5074 // If invalid type set, fallback to default.
5075 $ig = ImageGalleryBase
::factory( false );
5078 $ig->setContextTitle( $this->mTitle
);
5079 $ig->setShowBytes( false );
5080 $ig->setShowDimensions( false );
5081 $ig->setShowFilename( false );
5082 $ig->setParser( $this );
5083 $ig->setHideBadImages();
5084 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5086 if ( isset( $params['showfilename'] ) ) {
5087 $ig->setShowFilename( true );
5089 $ig->setShowFilename( false );
5091 if ( isset( $params['caption'] ) ) {
5092 // NOTE: We aren't passing a frame here or below. Frame info
5093 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5094 // See T107332#4030581
5095 $caption = $this->recursiveTagParse( $params['caption'] );
5096 $ig->setCaptionHtml( $caption );
5098 if ( isset( $params['perrow'] ) ) {
5099 $ig->setPerRow( $params['perrow'] );
5101 if ( isset( $params['widths'] ) ) {
5102 $ig->setWidths( $params['widths'] );
5104 if ( isset( $params['heights'] ) ) {
5105 $ig->setHeights( $params['heights'] );
5107 $ig->setAdditionalOptions( $params );
5109 // Avoid PHP 7.1 warning from passing $this by reference
5111 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5113 $lines = StringUtils
::explode( "\n", $text );
5114 foreach ( $lines as $line ) {
5115 # match lines like these:
5116 # Image:someimage.jpg|This is some image
5118 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5120 if ( count( $matches ) == 0 ) {
5124 if ( strpos( $matches[0], '%' ) !== false ) {
5125 $matches[1] = rawurldecode( $matches[1] );
5127 $title = Title
::newFromText( $matches[1], NS_FILE
);
5128 if ( is_null( $title ) ) {
5129 # Bogus title. Ignore these so we don't bomb out later.
5133 # We need to get what handler the file uses, to figure out parameters.
5134 # Note, a hook can overide the file name, and chose an entirely different
5135 # file (which potentially could be of a different type and have different handler).
5138 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5139 [ $this, $title, &$options, &$descQuery ] );
5140 # Don't register it now, as TraditionalImageGallery does that later.
5141 $file = $this->fetchFileNoRegister( $title, $options );
5142 $handler = $file ?
$file->getHandler() : false;
5145 'img_alt' => 'gallery-internal-alt',
5146 'img_link' => 'gallery-internal-link',
5149 $paramMap +
= $handler->getParamMap();
5150 // We don't want people to specify per-image widths.
5151 // Additionally the width parameter would need special casing anyhow.
5152 unset( $paramMap['img_width'] );
5155 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5160 $handlerOptions = [];
5161 if ( isset( $matches[3] ) ) {
5162 // look for an |alt= definition while trying not to break existing
5163 // captions with multiple pipes (|) in it, until a more sensible grammar
5164 // is defined for images in galleries
5166 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5167 // splitting on '|' is a bit odd, and different from makeImage.
5168 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5169 // Protect LanguageConverter markup
5170 $parameterMatches = StringUtils
::delimiterExplode(
5171 '-{', '}-', '|', $matches[3], true /* nested */
5174 foreach ( $parameterMatches as $parameterMatch ) {
5175 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5177 $paramName = $paramMap[$magicName];
5179 switch ( $paramName ) {
5180 case 'gallery-internal-alt':
5181 $alt = $this->stripAltText( $match, false );
5183 case 'gallery-internal-link':
5184 $linkValue = $this->stripAltText( $match, false );
5185 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5186 // Result of LanguageConverter::markNoConversion
5187 // invoked on an external link.
5188 $linkValue = substr( $linkValue, 4, -2 );
5190 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5191 if ( $type === 'link-url' ) {
5193 $this->mOutput
->addExternalLink( $target );
5194 } elseif ( $type === 'link-title' ) {
5195 $link = $target->getLinkURL();
5196 $this->mOutput
->addLink( $target );
5200 // Must be a handler specific parameter.
5201 if ( $handler->validateParam( $paramName, $match ) ) {
5202 $handlerOptions[$paramName] = $match;
5204 // Guess not, consider it as caption.
5205 wfDebug( "$parameterMatch failed parameter validation\n" );
5206 $label = $parameterMatch;
5212 $label = $parameterMatch;
5217 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5219 $html = $ig->toHTML();
5220 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5225 * @param MediaHandler $handler
5228 public function getImageParams( $handler ) {
5230 $handlerClass = get_class( $handler );
5234 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5235 # Initialise static lists
5236 static $internalParamNames = [
5237 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5238 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5239 'bottom', 'text-bottom' ],
5240 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5241 'upright', 'border', 'link', 'alt', 'class' ],
5243 static $internalParamMap;
5244 if ( !$internalParamMap ) {
5245 $internalParamMap = [];
5246 foreach ( $internalParamNames as $type => $names ) {
5247 foreach ( $names as $name ) {
5248 // For grep: img_left, img_right, img_center, img_none,
5249 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5250 // img_bottom, img_text_bottom,
5251 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5252 // img_border, img_link, img_alt, img_class
5253 $magicName = str_replace( '-', '_', "img_$name" );
5254 $internalParamMap[$magicName] = [ $type, $name ];
5259 # Add handler params
5260 $paramMap = $internalParamMap;
5262 $handlerParamMap = $handler->getParamMap();
5263 foreach ( $handlerParamMap as $magic => $paramName ) {
5264 $paramMap[$magic] = [ 'handler', $paramName ];
5267 $this->mImageParams
[$handlerClass] = $paramMap;
5268 $this->mImageParamsMagicArray
[$handlerClass] =
5269 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5271 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5275 * Parse image options text and use it to make an image
5277 * @param Title $title
5278 * @param string $options
5279 * @param LinkHolderArray|bool $holders
5280 * @return string HTML
5282 public function makeImage( $title, $options, $holders = false ) {
5283 # Check if the options text is of the form "options|alt text"
5285 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5286 # * left no resizing, just left align. label is used for alt= only
5287 # * right same, but right aligned
5288 # * none same, but not aligned
5289 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5290 # * center center the image
5291 # * frame Keep original image size, no magnify-button.
5292 # * framed Same as "frame"
5293 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5294 # * upright reduce width for upright images, rounded to full __0 px
5295 # * border draw a 1px border around the image
5296 # * alt Text for HTML alt attribute (defaults to empty)
5297 # * class Set a class for img node
5298 # * link Set the target of the image link. Can be external, interwiki, or local
5299 # vertical-align values (no % or length right now):
5309 # Protect LanguageConverter markup when splitting into parts
5310 $parts = StringUtils
::delimiterExplode(
5311 '-{', '}-', '|', $options, true /* allow nesting */
5314 # Give extensions a chance to select the file revision for us
5317 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5318 [ $this, $title, &$options, &$descQuery ] );
5319 # Fetch and register the file (file title may be different via hooks)
5320 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5323 $handler = $file ?
$file->getHandler() : false;
5325 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5328 $this->addTrackingCategory( 'broken-file-category' );
5331 # Process the input parameters
5333 $params = [ 'frame' => [], 'handler' => [],
5334 'horizAlign' => [], 'vertAlign' => [] ];
5335 $seenformat = false;
5336 foreach ( $parts as $part ) {
5337 $part = trim( $part );
5338 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5340 if ( isset( $paramMap[$magicName] ) ) {
5341 list( $type, $paramName ) = $paramMap[$magicName];
5343 # Special case; width and height come in one variable together
5344 if ( $type === 'handler' && $paramName === 'width' ) {
5345 $parsedWidthParam = self
::parseWidthParam( $value );
5346 if ( isset( $parsedWidthParam['width'] ) ) {
5347 $width = $parsedWidthParam['width'];
5348 if ( $handler->validateParam( 'width', $width ) ) {
5349 $params[$type]['width'] = $width;
5353 if ( isset( $parsedWidthParam['height'] ) ) {
5354 $height = $parsedWidthParam['height'];
5355 if ( $handler->validateParam( 'height', $height ) ) {
5356 $params[$type]['height'] = $height;
5360 # else no validation -- T15436
5362 if ( $type === 'handler' ) {
5363 # Validate handler parameter
5364 $validated = $handler->validateParam( $paramName, $value );
5366 # Validate internal parameters
5367 switch ( $paramName ) {
5371 # @todo FIXME: Possibly check validity here for
5372 # manualthumb? downstream behavior seems odd with
5373 # missing manual thumbs.
5375 $value = $this->stripAltText( $value, $holders );
5378 list( $paramName, $value ) =
5379 $this->parseLinkParameter(
5380 $this->stripAltText( $value, $holders )
5384 if ( $paramName === 'no-link' ) {
5387 if ( ( $paramName === 'link-url' ) && $this->mOptions
->getExternalLinkTarget() ) {
5388 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5395 // use first appearing option, discard others.
5396 $validated = !$seenformat;
5400 # Most other things appear to be empty or numeric...
5401 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5406 $params[$type][$paramName] = $value;
5410 if ( !$validated ) {
5415 # Process alignment parameters
5416 if ( $params['horizAlign'] ) {
5417 $params['frame']['align'] = key( $params['horizAlign'] );
5419 if ( $params['vertAlign'] ) {
5420 $params['frame']['valign'] = key( $params['vertAlign'] );
5423 $params['frame']['caption'] = $caption;
5425 # Will the image be presented in a frame, with the caption below?
5426 $imageIsFramed = isset( $params['frame']['frame'] )
5427 ||
isset( $params['frame']['framed'] )
5428 ||
isset( $params['frame']['thumbnail'] )
5429 ||
isset( $params['frame']['manualthumb'] );
5431 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5432 # came to also set the caption, ordinary text after the image -- which
5433 # makes no sense, because that just repeats the text multiple times in
5434 # screen readers. It *also* came to set the title attribute.
5435 # Now that we have an alt attribute, we should not set the alt text to
5436 # equal the caption: that's worse than useless, it just repeats the
5437 # text. This is the framed/thumbnail case. If there's no caption, we
5438 # use the unnamed parameter for alt text as well, just for the time be-
5439 # ing, if the unnamed param is set and the alt param is not.
5440 # For the future, we need to figure out if we want to tweak this more,
5441 # e.g., introducing a title= parameter for the title; ignoring the un-
5442 # named parameter entirely for images without a caption; adding an ex-
5443 # plicit caption= parameter and preserving the old magic unnamed para-
5445 if ( $imageIsFramed ) { # Framed image
5446 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5447 # No caption or alt text, add the filename as the alt text so
5448 # that screen readers at least get some description of the image
5449 $params['frame']['alt'] = $title->getText();
5451 # Do not set $params['frame']['title'] because tooltips don't make sense
5453 } else { # Inline image
5454 if ( !isset( $params['frame']['alt'] ) ) {
5455 # No alt text, use the "caption" for the alt text
5456 if ( $caption !== '' ) {
5457 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5459 # No caption, fall back to using the filename for the
5461 $params['frame']['alt'] = $title->getText();
5464 # Use the "caption" for the tooltip text
5465 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5467 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5469 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5471 # Linker does the rest
5472 $time = $options['time'] ??
false;
5473 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5474 $time, $descQuery, $this->mOptions
->getThumbSize() );
5476 # Give the handler a chance to modify the parser object
5478 $handler->parserTransformHook( $this, $file );
5485 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5487 * Adds an entry to appropriate link tables.
5490 * @param string $value
5491 * @return array of `[ type, target ]`, where:
5492 * - `type` is one of:
5493 * - `null`: Given value is not a valid link target, use default
5494 * - `'no-link'`: Given value is empty, do not generate a link
5495 * - `'link-url'`: Given value is a valid external link
5496 * - `'link-title'`: Given value is a valid internal link
5498 * - When `type` is `null` or `'no-link'`: `false`
5499 * - When `type` is `'link-url'`: URL string corresponding to given value
5500 * - When `type` is `'link-title'`: Title object corresponding to given value
5502 public function parseLinkParameter( $value ) {
5503 $chars = self
::EXT_LINK_URL_CLASS
;
5504 $addr = self
::EXT_LINK_ADDR
;
5505 $prots = $this->mUrlProtocols
;
5508 if ( $value === '' ) {
5510 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5511 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5512 $this->mOutput
->addExternalLink( $value );
5517 $linkTitle = Title
::newFromText( $value );
5519 $this->mOutput
->addLink( $linkTitle );
5520 $type = 'link-title';
5521 $target = $linkTitle;
5524 return [ $type, $target ];
5528 * @param string $caption
5529 * @param LinkHolderArray|bool $holders
5530 * @return mixed|string
5532 protected function stripAltText( $caption, $holders ) {
5533 # Strip bad stuff out of the title (tooltip). We can't just use
5534 # replaceLinkHoldersText() here, because if this function is called
5535 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5537 $tooltip = $holders->replaceText( $caption );
5539 $tooltip = $this->replaceLinkHoldersText( $caption );
5542 # make sure there are no placeholders in thumbnail attributes
5543 # that are later expanded to html- so expand them now and
5545 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5546 # Compatibility hack! In HTML certain entity references not terminated
5547 # by a semicolon are decoded (but not if we're in an attribute; that's
5548 # how link URLs get away without properly escaping & in queries).
5549 # But wikitext has always required semicolon-termination of entities,
5550 # so encode & where needed to avoid decode of semicolon-less entities.
5552 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5553 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5554 $tooltip = preg_replace( "/
5555 & # 1. entity prefix
5556 (?= # 2. followed by:
5557 (?: # a. one of the legacy semicolon-less named entities
5558 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5559 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5560 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5561 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5562 U(?:acute|circ|grave|uml)|Yacute|
5563 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5564 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5565 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5566 frac(?:1(?:2|4)|34)|
5567 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5568 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5569 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5570 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5571 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5572 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5573 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5574 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5575 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5577 (?:[^;]|$)) # b. and not followed by a semicolon
5578 # S = study, for efficiency
5579 /Sx", '&', $tooltip );
5580 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5586 * Set a flag in the output object indicating that the content is dynamic and
5587 * shouldn't be cached.
5588 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5590 public function disableCache() {
5591 wfDebug( "Parser output marked as uncacheable.\n" );
5592 if ( !$this->mOutput
) {
5593 throw new MWException( __METHOD__
.
5594 " can only be called when actually parsing something" );
5596 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5600 * Callback from the Sanitizer for expanding items found in HTML attribute
5601 * values, so they can be safely tested and escaped.
5603 * @param string &$text
5604 * @param bool|PPFrame $frame
5607 public function attributeStripCallback( &$text, $frame = false ) {
5608 $text = $this->replaceVariables( $text, $frame );
5609 $text = $this->mStripState
->unstripBoth( $text );
5618 public function getTags() {
5619 $this->firstCallInit();
5621 array_keys( $this->mTransparentTagHooks
),
5622 array_keys( $this->mTagHooks
),
5623 array_keys( $this->mFunctionTagHooks
)
5631 public function getFunctionSynonyms() {
5632 $this->firstCallInit();
5633 return $this->mFunctionSynonyms
;
5640 public function getUrlProtocols() {
5641 return $this->mUrlProtocols
;
5645 * Replace transparent tags in $text with the values given by the callbacks.
5647 * Transparent tag hooks are like regular XML-style tag hooks, except they
5648 * operate late in the transformation sequence, on HTML instead of wikitext.
5650 * @param string $text
5654 public function replaceTransparentTags( $text ) {
5656 $elements = array_keys( $this->mTransparentTagHooks
);
5657 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5660 foreach ( $matches as $marker => $data ) {
5661 list( $element, $content, $params, $tag ) = $data;
5662 $tagName = strtolower( $element );
5663 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5664 $output = call_user_func_array(
5665 $this->mTransparentTagHooks
[$tagName],
5666 [ $content, $params, $this ]
5671 $replacements[$marker] = $output;
5673 return strtr( $text, $replacements );
5677 * Break wikitext input into sections, and either pull or replace
5678 * some particular section's text.
5680 * External callers should use the getSection and replaceSection methods.
5682 * @param string $text Page wikitext
5683 * @param string|int $sectionId A section identifier string of the form:
5684 * "<flag1> - <flag2> - ... - <section number>"
5686 * Currently the only recognised flag is "T", which means the target section number
5687 * was derived during a template inclusion parse, in other words this is a template
5688 * section edit link. If no flags are given, it was an ordinary section edit link.
5689 * This flag is required to avoid a section numbering mismatch when a section is
5690 * enclosed by "<includeonly>" (T8563).
5692 * The section number 0 pulls the text before the first heading; other numbers will
5693 * pull the given section along with its lower-level subsections. If the section is
5694 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5696 * Section 0 is always considered to exist, even if it only contains the empty
5697 * string. If $text is the empty string and section 0 is replaced, $newText is
5700 * @param string $mode One of "get" or "replace"
5701 * @param string $newText Replacement text for section data.
5702 * @return string For "get", the extracted section text.
5703 * for "replace", the whole page with the section replaced.
5705 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5706 global $wgTitle; # not generally used but removes an ugly failure mode
5708 $magicScopeVariable = $this->lock();
5709 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5711 $frame = $this->getPreprocessor()->newFrame();
5713 # Process section extraction flags
5715 $sectionParts = explode( '-', $sectionId );
5716 $sectionIndex = array_pop( $sectionParts );
5717 foreach ( $sectionParts as $part ) {
5718 if ( $part === 'T' ) {
5719 $flags |
= self
::PTD_FOR_INCLUSION
;
5723 # Check for empty input
5724 if ( strval( $text ) === '' ) {
5725 # Only sections 0 and T-0 exist in an empty document
5726 if ( $sectionIndex == 0 ) {
5727 if ( $mode === 'get' ) {
5733 if ( $mode === 'get' ) {
5741 # Preprocess the text
5742 $root = $this->preprocessToDom( $text, $flags );
5744 # <h> nodes indicate section breaks
5745 # They can only occur at the top level, so we can find them by iterating the root's children
5746 $node = $root->getFirstChild();
5748 # Find the target section
5749 if ( $sectionIndex == 0 ) {
5750 # Section zero doesn't nest, level=big
5751 $targetLevel = 1000;
5754 if ( $node->getName() === 'h' ) {
5755 $bits = $node->splitHeading();
5756 if ( $bits['i'] == $sectionIndex ) {
5757 $targetLevel = $bits['level'];
5761 if ( $mode === 'replace' ) {
5762 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5764 $node = $node->getNextSibling();
5770 if ( $mode === 'get' ) {
5777 # Find the end of the section, including nested sections
5779 if ( $node->getName() === 'h' ) {
5780 $bits = $node->splitHeading();
5781 $curLevel = $bits['level'];
5782 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5786 if ( $mode === 'get' ) {
5787 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5789 $node = $node->getNextSibling();
5792 # Write out the remainder (in replace mode only)
5793 if ( $mode === 'replace' ) {
5794 # Output the replacement text
5795 # Add two newlines on -- trailing whitespace in $newText is conventionally
5796 # stripped by the editor, so we need both newlines to restore the paragraph gap
5797 # Only add trailing whitespace if there is newText
5798 if ( $newText != "" ) {
5799 $outText .= $newText . "\n\n";
5803 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5804 $node = $node->getNextSibling();
5808 if ( is_string( $outText ) ) {
5809 # Re-insert stripped tags
5810 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5817 * This function returns the text of a section, specified by a number ($section).
5818 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5819 * the first section before any such heading (section 0).
5821 * If a section contains subsections, these are also returned.
5823 * @param string $text Text to look in
5824 * @param string|int $sectionId Section identifier as a number or string
5825 * (e.g. 0, 1 or 'T-1').
5826 * @param string $defaultText Default to return if section is not found
5828 * @return string Text of the requested section
5830 public function getSection( $text, $sectionId, $defaultText = '' ) {
5831 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5835 * This function returns $oldtext after the content of the section
5836 * specified by $section has been replaced with $text. If the target
5837 * section does not exist, $oldtext is returned unchanged.
5839 * @param string $oldText Former text of the article
5840 * @param string|int $sectionId Section identifier as a number or string
5841 * (e.g. 0, 1 or 'T-1').
5842 * @param string $newText Replacing text
5844 * @return string Modified text
5846 public function replaceSection( $oldText, $sectionId, $newText ) {
5847 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5851 * Get the ID of the revision we are parsing
5855 public function getRevisionId() {
5856 return $this->mRevisionId
;
5860 * Get the revision object for $this->mRevisionId
5862 * @return Revision|null Either a Revision object or null
5863 * @since 1.23 (public since 1.23)
5865 public function getRevisionObject() {
5866 if ( !is_null( $this->mRevisionObject
) ) {
5867 return $this->mRevisionObject
;
5870 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5871 // This is useful when parsing revision that has not yet been saved.
5872 // However, if we get back a saved revision even though we are in
5873 // preview mode, we'll have to ignore it, see below.
5874 // NOTE: This callback may be used to inject an OLD revision that was
5875 // already loaded, so "current" is a bit of a misnomer. We can't just
5876 // skip it if mRevisionId is set.
5877 $rev = call_user_func(
5878 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5881 if ( $this->mRevisionId
=== null && $rev && $rev->getId() ) {
5882 // We are in preview mode (mRevisionId is null), and the current revision callback
5883 // returned an existing revision. Ignore it and return null, it's probably the page's
5884 // current revision, which is not what we want here. Note that we do want to call the
5885 // callback to allow the unsaved revision to be injected here, e.g. for
5886 // self-transclusion previews.
5890 // If the parse is for a new revision, then the callback should have
5891 // already been set to force the object and should match mRevisionId.
5892 // If not, try to fetch by mRevisionId for sanity.
5893 if ( $this->mRevisionId
&& $rev && $rev->getId() != $this->mRevisionId
) {
5894 $rev = Revision
::newFromId( $this->mRevisionId
);
5897 $this->mRevisionObject
= $rev;
5899 return $this->mRevisionObject
;
5903 * Get the timestamp associated with the current revision, adjusted for
5904 * the default server-local timestamp
5907 public function getRevisionTimestamp() {
5908 if ( is_null( $this->mRevisionTimestamp
) ) {
5909 $revObject = $this->getRevisionObject();
5910 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5912 # The cryptic '' timezone parameter tells to use the site-default
5913 # timezone offset instead of the user settings.
5914 # Since this value will be saved into the parser cache, served
5915 # to other users, and potentially even used inside links and such,
5916 # it needs to be consistent for all visitors.
5917 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
5919 return $this->mRevisionTimestamp
;
5923 * Get the name of the user that edited the last revision
5925 * @return string User name
5927 public function getRevisionUser() {
5928 if ( is_null( $this->mRevisionUser
) ) {
5929 $revObject = $this->getRevisionObject();
5931 # if this template is subst: the revision id will be blank,
5932 # so just use the current user's name
5934 $this->mRevisionUser
= $revObject->getUserText();
5935 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5936 $this->mRevisionUser
= $this->getUser()->getName();
5939 return $this->mRevisionUser
;
5943 * Get the size of the revision
5945 * @return int|null Revision size
5947 public function getRevisionSize() {
5948 if ( is_null( $this->mRevisionSize
) ) {
5949 $revObject = $this->getRevisionObject();
5951 # if this variable is subst: the revision id will be blank,
5952 # so just use the parser input size, because the own substituation
5953 # will change the size.
5955 $this->mRevisionSize
= $revObject->getSize();
5957 $this->mRevisionSize
= $this->mInputSize
;
5960 return $this->mRevisionSize
;
5964 * Mutator for $mDefaultSort
5966 * @param string $sort New value
5968 public function setDefaultSort( $sort ) {
5969 $this->mDefaultSort
= $sort;
5970 $this->mOutput
->setProperty( 'defaultsort', $sort );
5974 * Accessor for $mDefaultSort
5975 * Will use the empty string if none is set.
5977 * This value is treated as a prefix, so the
5978 * empty string is equivalent to sorting by
5983 public function getDefaultSort() {
5984 if ( $this->mDefaultSort
!== false ) {
5985 return $this->mDefaultSort
;
5992 * Accessor for $mDefaultSort
5993 * Unlike getDefaultSort(), will return false if none is set
5995 * @return string|bool
5997 public function getCustomDefaultSort() {
5998 return $this->mDefaultSort
;
6001 private static function getSectionNameFromStrippedText( $text ) {
6002 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6003 $text = Sanitizer
::decodeCharReferences( $text );
6004 $text = self
::normalizeSectionName( $text );
6008 private static function makeAnchor( $sectionName ) {
6009 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
6012 private function makeLegacyAnchor( $sectionName ) {
6013 $fragmentMode = $this->siteConfig
->get( 'FragmentMode' );
6014 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
6015 // ForAttribute() and ForLink() are the same for legacy encoding
6016 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
6018 $id = Sanitizer
::escapeIdForLink( $sectionName );
6025 * Try to guess the section anchor name based on a wikitext fragment
6026 * presumably extracted from a heading, for example "Header" from
6029 * @param string $text
6030 * @return string Anchor (starting with '#')
6032 public function guessSectionNameFromWikiText( $text ) {
6033 # Strip out wikitext links(they break the anchor)
6034 $text = $this->stripSectionName( $text );
6035 $sectionName = self
::getSectionNameFromStrippedText( $text );
6036 return self
::makeAnchor( $sectionName );
6040 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6041 * instead, if possible. For use in redirects, since various versions
6042 * of Microsoft browsers interpret Location: headers as something other
6043 * than UTF-8, resulting in breakage.
6045 * @param string $text The section name
6046 * @return string Anchor (starting with '#')
6048 public function guessLegacySectionNameFromWikiText( $text ) {
6049 # Strip out wikitext links(they break the anchor)
6050 $text = $this->stripSectionName( $text );
6051 $sectionName = self
::getSectionNameFromStrippedText( $text );
6052 return $this->makeLegacyAnchor( $sectionName );
6056 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6057 * @param string $text Section name (plain text)
6058 * @return string Anchor (starting with '#')
6060 public static function guessSectionNameFromStrippedText( $text ) {
6061 $sectionName = self
::getSectionNameFromStrippedText( $text );
6062 return self
::makeAnchor( $sectionName );
6066 * Apply the same normalization as code making links to this section would
6068 * @param string $text
6071 private static function normalizeSectionName( $text ) {
6072 # T90902: ensure the same normalization is applied for IDs as to links
6073 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
6076 $parts = $titleParser->splitTitleString( "#$text" );
6077 } catch ( MalformedTitleException
$ex ) {
6080 return $parts['fragment'];
6084 * Strips a text string of wikitext for use in a section anchor
6086 * Accepts a text string and then removes all wikitext from the
6087 * string and leaves only the resultant text (i.e. the result of
6088 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6089 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6090 * to create valid section anchors by mimicing the output of the
6091 * parser when headings are parsed.
6093 * @param string $text Text string to be stripped of wikitext
6094 * for use in a Section anchor
6095 * @return string Filtered text string
6097 public function stripSectionName( $text ) {
6098 # Strip internal link markup
6099 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6100 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6102 # Strip external link markup
6103 # @todo FIXME: Not tolerant to blank link text
6104 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6105 # on how many empty links there are on the page - need to figure that out.
6106 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6108 # Parse wikitext quotes (italics & bold)
6109 $text = $this->doQuotes( $text );
6112 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6117 * strip/replaceVariables/unstrip for preprocessor regression testing
6119 * @param string $text
6120 * @param Title $title
6121 * @param ParserOptions $options
6122 * @param int $outputType
6126 public function testSrvus( $text, Title
$title, ParserOptions
$options,
6127 $outputType = self
::OT_HTML
6129 $magicScopeVariable = $this->lock();
6130 $this->startParse( $title, $options, $outputType, true );
6132 $text = $this->replaceVariables( $text );
6133 $text = $this->mStripState
->unstripBoth( $text );
6134 $text = Sanitizer
::removeHTMLtags( $text );
6139 * @param string $text
6140 * @param Title $title
6141 * @param ParserOptions $options
6144 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6145 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6149 * @param string $text
6150 * @param Title $title
6151 * @param ParserOptions $options
6154 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6155 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6159 * Call a callback function on all regions of the given text that are not
6160 * inside strip markers, and replace those regions with the return value
6161 * of the callback. For example, with input:
6165 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6166 * two strings will be replaced with the value returned by the callback in
6170 * @param callable $callback
6174 public function markerSkipCallback( $s, $callback ) {
6177 while ( $i < strlen( $s ) ) {
6178 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6179 if ( $markerStart === false ) {
6180 $out .= call_user_func( $callback, substr( $s, $i ) );
6183 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6184 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6185 if ( $markerEnd === false ) {
6186 $out .= substr( $s, $markerStart );
6189 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6190 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6199 * Remove any strip markers found in the given text.
6201 * @param string $text
6204 public function killMarkers( $text ) {
6205 return $this->mStripState
->killMarkers( $text );
6209 * Save the parser state required to convert the given half-parsed text to
6210 * HTML. "Half-parsed" in this context means the output of
6211 * recursiveTagParse() or internalParse(). This output has strip markers
6212 * from replaceVariables (extensionSubstitution() etc.), and link
6213 * placeholders from replaceLinkHolders().
6215 * Returns an array which can be serialized and stored persistently. This
6216 * array can later be loaded into another parser instance with
6217 * unserializeHalfParsedText(). The text can then be safely incorporated into
6218 * the return value of a parser hook.
6220 * @deprecated since 1.31
6221 * @param string $text
6225 public function serializeHalfParsedText( $text ) {
6226 wfDeprecated( __METHOD__
, '1.31' );
6229 'version' => self
::HALF_PARSED_VERSION
,
6230 'stripState' => $this->mStripState
->getSubState( $text ),
6231 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6237 * Load the parser state given in the $data array, which is assumed to
6238 * have been generated by serializeHalfParsedText(). The text contents is
6239 * extracted from the array, and its markers are transformed into markers
6240 * appropriate for the current Parser instance. This transformed text is
6241 * returned, and can be safely included in the return value of a parser
6244 * If the $data array has been stored persistently, the caller should first
6245 * check whether it is still valid, by calling isValidHalfParsedText().
6247 * @deprecated since 1.31
6248 * @param array $data Serialized data
6249 * @throws MWException
6252 public function unserializeHalfParsedText( $data ) {
6253 wfDeprecated( __METHOD__
, '1.31' );
6254 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6255 throw new MWException( __METHOD__
. ': invalid version' );
6258 # First, extract the strip state.
6259 $texts = [ $data['text'] ];
6260 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6262 # Now renumber links
6263 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6265 # Should be good to go.
6270 * Returns true if the given array, presumed to be generated by
6271 * serializeHalfParsedText(), is compatible with the current version of the
6274 * @deprecated since 1.31
6275 * @param array $data
6279 public function isValidHalfParsedText( $data ) {
6280 wfDeprecated( __METHOD__
, '1.31' );
6281 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6285 * Parsed a width param of imagelink like 300px or 200x300px
6287 * @param string $value
6288 * @param bool $parseHeight
6293 public static function parseWidthParam( $value, $parseHeight = true ) {
6294 $parsedWidthParam = [];
6295 if ( $value === '' ) {
6296 return $parsedWidthParam;
6299 # (T15500) In both cases (width/height and width only),
6300 # permit trailing "px" for backward compatibility.
6301 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6302 $width = intval( $m[1] );
6303 $height = intval( $m[2] );
6304 $parsedWidthParam['width'] = $width;
6305 $parsedWidthParam['height'] = $height;
6306 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6307 $width = intval( $value );
6308 $parsedWidthParam['width'] = $width;
6310 return $parsedWidthParam;
6314 * Lock the current instance of the parser.
6316 * This is meant to stop someone from calling the parser
6317 * recursively and messing up all the strip state.
6319 * @throws MWException If parser is in a parse
6320 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6322 protected function lock() {
6323 if ( $this->mInParse
) {
6324 throw new MWException( "Parser state cleared while parsing. "
6325 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6328 // Save the backtrace when locking, so that if some code tries locking again,
6329 // we can print the lock owner's backtrace for easier debugging
6331 $this->mInParse
= $e->getTraceAsString();
6333 $recursiveCheck = new ScopedCallback( function () {
6334 $this->mInParse
= false;
6337 return $recursiveCheck;
6341 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6343 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6344 * or if there is more than one <p/> tag in the input HTML.
6346 * @param string $html
6350 public static function stripOuterParagraph( $html ) {
6352 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '</p>' ) === false ) {
6360 * Return this parser if it is not doing anything, otherwise
6361 * get a fresh parser. You can use this method by doing
6362 * $myParser = $wgParser->getFreshParser(), or more simply
6363 * $wgParser->getFreshParser()->parse( ... );
6364 * if you're unsure if $wgParser is safe to use.
6367 * @return Parser A parser object that is not parsing anything
6369 public function getFreshParser() {
6370 if ( $this->mInParse
) {
6371 return $this->factory
->create();
6378 * Set's up the PHP implementation of OOUI for use in this request
6379 * and instructs OutputPage to enable OOUI for itself.
6383 public function enableOOUI() {
6384 OutputPage
::setupOOUI();
6385 $this->mOutput
->setEnableOOUI( true );