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 return $this->mRevisionId ?
'-' : '';
2613 $pageLang = $this->getFunctionLang();
2619 case 'currentmonth':
2620 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2622 case 'currentmonth1':
2623 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2625 case 'currentmonthname':
2626 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2628 case 'currentmonthnamegen':
2629 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2631 case 'currentmonthabbrev':
2632 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2635 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2638 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2641 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2644 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2646 case 'localmonthname':
2647 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2649 case 'localmonthnamegen':
2650 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2652 case 'localmonthabbrev':
2653 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2656 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2659 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2662 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2665 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2667 case 'fullpagename':
2668 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2670 case 'fullpagenamee':
2671 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2674 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2676 case 'subpagenamee':
2677 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2679 case 'rootpagename':
2680 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2682 case 'rootpagenamee':
2683 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2686 $this->mTitle
->getRootText()
2689 case 'basepagename':
2690 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2692 case 'basepagenamee':
2693 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2696 $this->mTitle
->getBaseText()
2699 case 'talkpagename':
2700 if ( $this->mTitle
->canHaveTalkPage() ) {
2701 $talkPage = $this->mTitle
->getTalkPage();
2702 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2707 case 'talkpagenamee':
2708 if ( $this->mTitle
->canHaveTalkPage() ) {
2709 $talkPage = $this->mTitle
->getTalkPage();
2710 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2715 case 'subjectpagename':
2716 $subjPage = $this->mTitle
->getSubjectPage();
2717 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2719 case 'subjectpagenamee':
2720 $subjPage = $this->mTitle
->getSubjectPage();
2721 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2723 case 'pageid': // requested in T25427
2724 $pageid = $this->getTitle()->getArticleID();
2725 if ( $pageid == 0 ) {
2726 # 0 means the page doesn't exist in the database,
2727 # which means the user is previewing a new page.
2728 # The vary-revision flag must be set, because the magic word
2729 # will have a different value once the page is saved.
2730 $this->mOutput
->setFlag( 'vary-revision' );
2731 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2733 $value = $pageid ?
: null;
2736 # Let the edit saving system know we should parse the page
2737 # *after* a revision ID has been assigned.
2738 $this->mOutput
->setFlag( 'vary-revision-id' );
2739 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2740 $value = $this->mRevisionId
;
2743 $rev = $this->getRevisionObject();
2745 $value = $rev->getId();
2750 $value = $this->mOptions
->getSpeculativeRevId();
2752 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2757 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2759 case 'revisionday2':
2760 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2762 case 'revisionmonth':
2763 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2765 case 'revisionmonth1':
2766 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2768 case 'revisionyear':
2769 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2771 case 'revisiontimestamp':
2772 # Let the edit saving system know we should parse the page
2773 # *after* a revision ID has been assigned. This is for null edits.
2774 $this->mOutput
->setFlag( 'vary-revision' );
2775 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2776 $value = $this->getRevisionTimestamp();
2778 case 'revisionuser':
2779 # Let the edit saving system know we should parse the page
2780 # *after* a revision ID has been assigned for null edits.
2781 $this->mOutput
->setFlag( 'vary-user' );
2782 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2783 $value = $this->getRevisionUser();
2785 case 'revisionsize':
2786 $value = $this->getRevisionSize();
2789 $value = str_replace( '_', ' ',
2790 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2793 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2795 case 'namespacenumber':
2796 $value = $this->mTitle
->getNamespace();
2799 $value = $this->mTitle
->canHaveTalkPage()
2800 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2804 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2806 case 'subjectspace':
2807 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2809 case 'subjectspacee':
2810 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2812 case 'currentdayname':
2813 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2816 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2819 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2822 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2825 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2826 # int to remove the padding
2827 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2830 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2832 case 'localdayname':
2833 $value = $pageLang->getWeekdayName(
2834 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2838 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2841 $value = $pageLang->time(
2842 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2848 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2851 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2852 # int to remove the padding
2853 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2856 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2858 case 'numberofarticles':
2859 $value = $pageLang->formatNum( SiteStats
::articles() );
2861 case 'numberoffiles':
2862 $value = $pageLang->formatNum( SiteStats
::images() );
2864 case 'numberofusers':
2865 $value = $pageLang->formatNum( SiteStats
::users() );
2867 case 'numberofactiveusers':
2868 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2870 case 'numberofpages':
2871 $value = $pageLang->formatNum( SiteStats
::pages() );
2873 case 'numberofadmins':
2874 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2876 case 'numberofedits':
2877 $value = $pageLang->formatNum( SiteStats
::edits() );
2879 case 'currenttimestamp':
2880 $value = wfTimestamp( TS_MW
, $ts );
2882 case 'localtimestamp':
2883 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2885 case 'currentversion':
2886 $value = SpecialVersion
::getVersion();
2889 return $this->siteConfig
->get( 'ArticlePath' );
2891 return $this->siteConfig
->get( 'Sitename' );
2893 return $this->siteConfig
->get( 'Server' );
2895 return $this->siteConfig
->get( 'ServerName' );
2897 return $this->siteConfig
->get( 'ScriptPath' );
2899 return $this->siteConfig
->get( 'StylePath' );
2900 case 'directionmark':
2901 return $pageLang->getDirMark();
2902 case 'contentlanguage':
2903 return $this->siteConfig
->get( 'LanguageCode' );
2904 case 'pagelanguage':
2905 $value = $pageLang->getCode();
2907 case 'cascadingsources':
2908 $value = CoreParserFunctions
::cascadingsources( $this );
2913 'ParserGetVariableValueSwitch',
2914 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2921 $this->mVarCache
[$index] = $value;
2930 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2931 * @param string $variable Parser variable name
2934 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2935 # Get the timezone-adjusted timestamp to be used for this revision
2936 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2937 # Possibly set vary-revision if there is not yet an associated revision
2938 if ( !$this->getRevisionObject() ) {
2939 # Get the timezone-adjusted timestamp $mtts seconds in the future
2941 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
2946 if ( $resNow !== $resThen ) {
2947 # Let the edit saving system know we should parse the page
2948 # *after* a revision ID has been assigned. This is for null edits.
2949 $this->mOutput
->setFlag( 'vary-revision' );
2950 wfDebug( __METHOD__
. ": $variable used, setting vary-revision...\n" );
2958 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2962 public function initialiseVariables() {
2963 $variableIDs = $this->magicWordFactory
->getVariableIDs();
2964 $substIDs = $this->magicWordFactory
->getSubstIDs();
2966 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
2967 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
2971 * Preprocess some wikitext and return the document tree.
2972 * This is the ghost of replace_variables().
2974 * @param string $text The text to parse
2975 * @param int $flags Bitwise combination of:
2976 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2977 * included. Default is to assume a direct page view.
2979 * The generated DOM tree must depend only on the input text and the flags.
2980 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2982 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2983 * change in the DOM tree for a given text, must be passed through the section identifier
2984 * in the section edit link and thus back to extractSections().
2986 * The output of this function is currently only cached in process memory, but a persistent
2987 * cache may be implemented at a later date which takes further advantage of these strict
2988 * dependency requirements.
2992 public function preprocessToDom( $text, $flags = 0 ) {
2993 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2998 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3004 public static function splitWhitespace( $s ) {
3005 $ltrimmed = ltrim( $s );
3006 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3007 $trimmed = rtrim( $ltrimmed );
3008 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3010 $w2 = substr( $ltrimmed, -$diff );
3014 return [ $w1, $trimmed, $w2 ];
3018 * Replace magic variables, templates, and template arguments
3019 * with the appropriate text. Templates are substituted recursively,
3020 * taking care to avoid infinite loops.
3022 * Note that the substitution depends on value of $mOutputType:
3023 * self::OT_WIKI: only {{subst:}} templates
3024 * self::OT_PREPROCESS: templates but not extension tags
3025 * self::OT_HTML: all templates and extension tags
3027 * @param string $text The text to transform
3028 * @param bool|PPFrame $frame Object describing the arguments passed to the
3029 * template. Arguments may also be provided as an associative array, as
3030 * was the usual case before MW1.12. Providing arguments this way may be
3031 * useful for extensions wishing to perform variable replacement
3033 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3034 * double-brace expansion.
3037 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3038 # Is there any text? Also, Prevent too big inclusions!
3039 $textSize = strlen( $text );
3040 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3044 if ( $frame === false ) {
3045 $frame = $this->getPreprocessor()->newFrame();
3046 } elseif ( !( $frame instanceof PPFrame
) ) {
3047 wfDebug( __METHOD__
. " called using plain parameters instead of "
3048 . "a PPFrame instance. Creating custom frame.\n" );
3049 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3052 $dom = $this->preprocessToDom( $text );
3053 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3054 $text = $frame->expand( $dom, $flags );
3060 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3062 * @param array $args
3066 public static function createAssocArgs( $args ) {
3069 foreach ( $args as $arg ) {
3070 $eqpos = strpos( $arg, '=' );
3071 if ( $eqpos === false ) {
3072 $assocArgs[$index++
] = $arg;
3074 $name = trim( substr( $arg, 0, $eqpos ) );
3075 $value = trim( substr( $arg, $eqpos +
1 ) );
3076 if ( $value === false ) {
3079 if ( $name !== false ) {
3080 $assocArgs[$name] = $value;
3089 * Warn the user when a parser limitation is reached
3090 * Will warn at most once the user per limitation type
3092 * The results are shown during preview and run through the Parser (See EditPage.php)
3094 * @param string $limitationType Should be one of:
3095 * 'expensive-parserfunction' (corresponding messages:
3096 * 'expensive-parserfunction-warning',
3097 * 'expensive-parserfunction-category')
3098 * 'post-expand-template-argument' (corresponding messages:
3099 * 'post-expand-template-argument-warning',
3100 * 'post-expand-template-argument-category')
3101 * 'post-expand-template-inclusion' (corresponding messages:
3102 * 'post-expand-template-inclusion-warning',
3103 * 'post-expand-template-inclusion-category')
3104 * 'node-count-exceeded' (corresponding messages:
3105 * 'node-count-exceeded-warning',
3106 * 'node-count-exceeded-category')
3107 * 'expansion-depth-exceeded' (corresponding messages:
3108 * 'expansion-depth-exceeded-warning',
3109 * 'expansion-depth-exceeded-category')
3110 * @param string|int|null $current Current value
3111 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3112 * exceeded, provide the values (optional)
3114 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3115 # does no harm if $current and $max are present but are unnecessary for the message
3116 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3117 # only during preview, and that would split the parser cache unnecessarily.
3118 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3120 $this->mOutput
->addWarning( $warning );
3121 $this->addTrackingCategory( "$limitationType-category" );
3125 * Return the text of a template, after recursively
3126 * replacing any variables or templates within the template.
3128 * @param array $piece The parts of the template
3129 * $piece['title']: the title, i.e. the part before the |
3130 * $piece['parts']: the parameter array
3131 * $piece['lineStart']: whether the brace was at the start of a line
3132 * @param PPFrame $frame The current frame, contains template arguments
3134 * @return string The text of the template
3136 public function braceSubstitution( $piece, $frame ) {
3139 // $text has been filled
3141 // wiki markup in $text should be escaped
3143 // $text is HTML, armour it against wikitext transformation
3145 // Force interwiki transclusion to be done in raw mode not rendered
3146 $forceRawInterwiki = false;
3147 // $text is a DOM node needing expansion in a child frame
3148 $isChildObj = false;
3149 // $text is a DOM node needing expansion in the current frame
3150 $isLocalObj = false;
3152 # Title object, where $text came from
3155 # $part1 is the bit before the first |, and must contain only title characters.
3156 # Various prefixes will be stripped from it later.
3157 $titleWithSpaces = $frame->expand( $piece['title'] );
3158 $part1 = trim( $titleWithSpaces );
3161 # Original title text preserved for various purposes
3162 $originalTitle = $part1;
3164 # $args is a list of argument nodes, starting from index 0, not including $part1
3165 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3166 # below won't work b/c this $args isn't an object
3167 $args = ( $piece['parts'] == null ) ?
[] : $piece['parts'];
3169 $profileSection = null; // profile templates
3173 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3175 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3176 # Decide whether to expand template or keep wikitext as-is.
3177 if ( $this->ot
['wiki'] ) {
3178 if ( $substMatch === false ) {
3179 $literal = true; # literal when in PST with no prefix
3181 $literal = false; # expand when in PST with subst: or safesubst:
3184 if ( $substMatch == 'subst' ) {
3185 $literal = true; # literal when not in PST with plain subst:
3187 $literal = false; # expand when not in PST with safesubst: or no prefix
3191 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3198 if ( !$found && $args->getLength() == 0 ) {
3199 $id = $this->mVariables
->matchStartToEnd( $part1 );
3200 if ( $id !== false ) {
3201 $text = $this->getVariableValue( $id, $frame );
3202 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3203 $this->mOutput
->updateCacheExpiry(
3204 $this->magicWordFactory
->getCacheTTL( $id ) );
3210 # MSG, MSGNW and RAW
3213 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3214 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3217 # Remove obsolete MSG:
3218 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3219 $mwMsg->matchStartAndRemove( $part1 );
3223 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3224 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3225 $forceRawInterwiki = true;
3231 $colonPos = strpos( $part1, ':' );
3232 if ( $colonPos !== false ) {
3233 $func = substr( $part1, 0, $colonPos );
3234 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3235 $argsLength = $args->getLength();
3236 for ( $i = 0; $i < $argsLength; $i++
) {
3237 $funcArgs[] = $args->item( $i );
3240 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3242 // Extract any forwarded flags
3243 if ( isset( $result['title'] ) ) {
3244 $title = $result['title'];
3246 if ( isset( $result['found'] ) ) {
3247 $found = $result['found'];
3249 if ( array_key_exists( 'text', $result ) ) {
3251 $text = $result['text'];
3253 if ( isset( $result['nowiki'] ) ) {
3254 $nowiki = $result['nowiki'];
3256 if ( isset( $result['isHTML'] ) ) {
3257 $isHTML = $result['isHTML'];
3259 if ( isset( $result['forceRawInterwiki'] ) ) {
3260 $forceRawInterwiki = $result['forceRawInterwiki'];
3262 if ( isset( $result['isChildObj'] ) ) {
3263 $isChildObj = $result['isChildObj'];
3265 if ( isset( $result['isLocalObj'] ) ) {
3266 $isLocalObj = $result['isLocalObj'];
3271 # Finish mangling title and then check for loops.
3272 # Set $title to a Title object and $titleText to the PDBK
3275 # Split the title into page and subpage
3277 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3278 if ( $part1 !== $relative ) {
3280 $ns = $this->mTitle
->getNamespace();
3282 $title = Title
::newFromText( $part1, $ns );
3284 $titleText = $title->getPrefixedText();
3285 # Check for language variants if the template is not found
3286 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3287 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3289 # Do recursion depth check
3290 $limit = $this->mOptions
->getMaxTemplateDepth();
3291 if ( $frame->depth
>= $limit ) {
3293 $text = '<span class="error">'
3294 . wfMessage( 'parser-template-recursion-depth-warning' )
3295 ->numParams( $limit )->inContentLanguage()->text()
3301 # Load from database
3302 if ( !$found && $title ) {
3303 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3304 if ( !$title->isExternal() ) {
3305 if ( $title->isSpecialPage()
3306 && $this->mOptions
->getAllowSpecialInclusion()
3307 && $this->ot
['html']
3309 $specialPage = $this->specialPageFactory
->getPage( $title->getDBkey() );
3310 // Pass the template arguments as URL parameters.
3311 // "uselang" will have no effect since the Language object
3312 // is forced to the one defined in ParserOptions.
3314 $argsLength = $args->getLength();
3315 for ( $i = 0; $i < $argsLength; $i++
) {
3316 $bits = $args->item( $i )->splitArg();
3317 if ( strval( $bits['index'] ) === '' ) {
3318 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3319 $value = trim( $frame->expand( $bits['value'] ) );
3320 $pageArgs[$name] = $value;
3324 // Create a new context to execute the special page
3325 $context = new RequestContext
;
3326 $context->setTitle( $title );
3327 $context->setRequest( new FauxRequest( $pageArgs ) );
3328 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3329 $context->setUser( $this->getUser() );
3331 // If this page is cached, then we better not be per user.
3332 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3334 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3335 $ret = $this->specialPageFactory
->capturePath( $title, $context, $this->getLinkRenderer() );
3337 $text = $context->getOutput()->getHTML();
3338 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3341 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3342 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3343 $specialPage->maxIncludeCacheTime()
3347 } elseif ( $this->nsInfo
->isNonincludable( $title->getNamespace() ) ) {
3348 $found = false; # access denied
3349 wfDebug( __METHOD__
. ": template inclusion denied for " .
3350 $title->getPrefixedDBkey() . "\n" );
3352 list( $text, $title ) = $this->getTemplateDom( $title );
3353 if ( $text !== false ) {
3359 # If the title is valid but undisplayable, make a link to it
3360 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3361 $text = "[[:$titleText]]";
3364 } elseif ( $title->isTrans() ) {
3365 # Interwiki transclusion
3366 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3367 $text = $this->interwikiTransclude( $title, 'render' );
3370 $text = $this->interwikiTransclude( $title, 'raw' );
3371 # Preprocess it like a template
3372 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3378 # Do infinite loop check
3379 # This has to be done after redirect resolution to avoid infinite loops via redirects
3380 if ( !$frame->loopCheck( $title ) ) {
3382 $text = '<span class="error">'
3383 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3385 $this->addTrackingCategory( 'template-loop-category' );
3386 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3387 wfEscapeWikiText( $titleText ) )->text() );
3388 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3392 # If we haven't found text to substitute by now, we're done
3393 # Recover the source wikitext and return it
3395 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3396 if ( $profileSection ) {
3397 $this->mProfiler
->scopedProfileOut( $profileSection );
3399 return [ 'object' => $text ];
3402 # Expand DOM-style return values in a child frame
3403 if ( $isChildObj ) {
3404 # Clean up argument array
3405 $newFrame = $frame->newChild( $args, $title );
3408 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3409 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3410 # Expansion is eligible for the empty-frame cache
3411 $text = $newFrame->cachedExpand( $titleText, $text );
3413 # Uncached expansion
3414 $text = $newFrame->expand( $text );
3417 if ( $isLocalObj && $nowiki ) {
3418 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3419 $isLocalObj = false;
3422 if ( $profileSection ) {
3423 $this->mProfiler
->scopedProfileOut( $profileSection );
3426 # Replace raw HTML by a placeholder
3428 $text = $this->insertStripItem( $text );
3429 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3430 # Escape nowiki-style return values
3431 $text = wfEscapeWikiText( $text );
3432 } elseif ( is_string( $text )
3433 && !$piece['lineStart']
3434 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3436 # T2529: if the template begins with a table or block-level
3437 # element, it should be treated as beginning a new line.
3438 # This behavior is somewhat controversial.
3439 $text = "\n" . $text;
3442 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3443 # Error, oversize inclusion
3444 if ( $titleText !== false ) {
3445 # Make a working, properly escaped link if possible (T25588)
3446 $text = "[[:$titleText]]";
3448 # This will probably not be a working link, but at least it may
3449 # provide some hint of where the problem is
3450 preg_replace( '/^:/', '', $originalTitle );
3451 $text = "[[:$originalTitle]]";
3453 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3454 . 'post-expand include size too large -->' );
3455 $this->limitationWarn( 'post-expand-template-inclusion' );
3458 if ( $isLocalObj ) {
3459 $ret = [ 'object' => $text ];
3461 $ret = [ 'text' => $text ];
3468 * Call a parser function and return an array with text and flags.
3470 * The returned array will always contain a boolean 'found', indicating
3471 * whether the parser function was found or not. It may also contain the
3473 * text: string|object, resulting wikitext or PP DOM object
3474 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3475 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3476 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3477 * nowiki: bool, wiki markup in $text should be escaped
3480 * @param PPFrame $frame The current frame, contains template arguments
3481 * @param string $function Function name
3482 * @param array $args Arguments to the function
3483 * @throws MWException
3486 public function callParserFunction( $frame, $function, array $args = [] ) {
3487 # Case sensitive functions
3488 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3489 $function = $this->mFunctionSynonyms
[1][$function];
3491 # Case insensitive functions
3492 $function = $this->contLang
->lc( $function );
3493 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3494 $function = $this->mFunctionSynonyms
[0][$function];
3496 return [ 'found' => false ];
3500 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3502 // Avoid PHP 7.1 warning from passing $this by reference
3505 $allArgs = [ &$parser ];
3506 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3507 # Convert arguments to PPNodes and collect for appending to $allArgs
3509 foreach ( $args as $k => $v ) {
3510 if ( $v instanceof PPNode ||
$k === 0 ) {
3513 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3517 # Add a frame parameter, and pass the arguments as an array
3518 $allArgs[] = $frame;
3519 $allArgs[] = $funcArgs;
3521 # Convert arguments to plain text and append to $allArgs
3522 foreach ( $args as $k => $v ) {
3523 if ( $v instanceof PPNode
) {
3524 $allArgs[] = trim( $frame->expand( $v ) );
3525 } elseif ( is_int( $k ) && $k >= 0 ) {
3526 $allArgs[] = trim( $v );
3528 $allArgs[] = trim( "$k=$v" );
3533 $result = $callback( ...$allArgs );
3535 # The interface for function hooks allows them to return a wikitext
3536 # string or an array containing the string and any flags. This mungs
3537 # things around to match what this method should return.
3538 if ( !is_array( $result ) ) {
3544 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3545 $result['text'] = $result[0];
3547 unset( $result[0] );
3554 $preprocessFlags = 0;
3555 if ( isset( $result['noparse'] ) ) {
3556 $noparse = $result['noparse'];
3558 if ( isset( $result['preprocessFlags'] ) ) {
3559 $preprocessFlags = $result['preprocessFlags'];
3563 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3564 $result['isChildObj'] = true;
3571 * Get the semi-parsed DOM representation of a template with a given title,
3572 * and its redirect destination title. Cached.
3574 * @param Title $title
3578 public function getTemplateDom( $title ) {
3579 $cacheTitle = $title;
3580 $titleText = $title->getPrefixedDBkey();
3582 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3583 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3584 $title = Title
::makeTitle( $ns, $dbk );
3585 $titleText = $title->getPrefixedDBkey();
3587 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3588 return [ $this->mTplDomCache
[$titleText], $title ];
3591 # Cache miss, go to the database
3592 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3594 if ( $text === false ) {
3595 $this->mTplDomCache
[$titleText] = false;
3596 return [ false, $title ];
3599 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3600 $this->mTplDomCache
[$titleText] = $dom;
3602 if ( !$title->equals( $cacheTitle ) ) {
3603 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3604 [ $title->getNamespace(), $title->getDBkey() ];
3607 return [ $dom, $title ];
3611 * Fetch the current revision of a given title. Note that the revision
3612 * (and even the title) may not exist in the database, so everything
3613 * contributing to the output of the parser should use this method
3614 * where possible, rather than getting the revisions themselves. This
3615 * method also caches its results, so using it benefits performance.
3618 * @param Title $title
3621 public function fetchCurrentRevisionOfTitle( $title ) {
3622 $cacheKey = $title->getPrefixedDBkey();
3623 if ( !$this->currentRevisionCache
) {
3624 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3626 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3627 $this->currentRevisionCache
->set( $cacheKey,
3628 // Defaults to Parser::statelessFetchRevision()
3629 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3632 return $this->currentRevisionCache
->get( $cacheKey );
3636 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3637 * without passing them on to it.
3640 * @param Title $title
3641 * @param Parser|bool $parser
3642 * @return Revision|bool False if missing
3644 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3645 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3651 * Fetch the unparsed text of a template and register a reference to it.
3652 * @param Title $title
3653 * @return array ( string or false, Title )
3655 public function fetchTemplateAndTitle( $title ) {
3656 // Defaults to Parser::statelessFetchTemplate()
3657 $templateCb = $this->mOptions
->getTemplateCallback();
3658 $stuff = call_user_func( $templateCb, $title, $this );
3659 // We use U+007F DELETE to distinguish strip markers from regular text.
3660 $text = $stuff['text'];
3661 if ( is_string( $stuff['text'] ) ) {
3662 $text = strtr( $text, "\x7f", "?" );
3664 $finalTitle = $stuff['finalTitle'] ??
$title;
3665 if ( isset( $stuff['deps'] ) ) {
3666 foreach ( $stuff['deps'] as $dep ) {
3667 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3668 if ( $dep['title']->equals( $this->getTitle() ) ) {
3669 // If we transclude ourselves, the final result
3670 // will change based on the new version of the page
3671 $this->mOutput
->setFlag( 'vary-revision' );
3675 return [ $text, $finalTitle ];
3679 * Fetch the unparsed text of a template and register a reference to it.
3680 * @param Title $title
3681 * @return string|bool
3683 public function fetchTemplate( $title ) {
3684 return $this->fetchTemplateAndTitle( $title )[0];
3688 * Static function to get a template
3689 * Can be overridden via ParserOptions::setTemplateCallback().
3691 * @param Title $title
3692 * @param bool|Parser $parser
3696 public static function statelessFetchTemplate( $title, $parser = false ) {
3697 $text = $skip = false;
3698 $finalTitle = $title;
3701 # Loop to fetch the article, with up to 1 redirect
3702 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3703 # Give extensions a chance to select the revision instead
3704 $id = false; # Assume current
3705 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3706 [ $parser, $title, &$skip, &$id ] );
3712 'page_id' => $title->getArticleID(),
3719 $rev = Revision
::newFromId( $id );
3720 } elseif ( $parser ) {
3721 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3723 $rev = Revision
::newFromTitle( $title );
3725 $rev_id = $rev ?
$rev->getId() : 0;
3726 # If there is no current revision, there is no page
3727 if ( $id === false && !$rev ) {
3728 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3729 $linkCache->addBadLinkObj( $title );
3734 'page_id' => $title->getArticleID(),
3735 'rev_id' => $rev_id ];
3736 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3737 # We fetched a rev from a different title; register it too...
3739 'title' => $rev->getTitle(),
3740 'page_id' => $rev->getPage(),
3741 'rev_id' => $rev_id ];
3745 $content = $rev->getContent();
3746 $text = $content ?
$content->getWikitextForTransclusion() : null;
3748 Hooks
::run( 'ParserFetchTemplate',
3749 [ $parser, $title, $rev, &$text, &$deps ] );
3751 if ( $text === false ||
$text === null ) {
3755 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3756 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3757 lcfirst( $title->getText() ) )->inContentLanguage();
3758 if ( !$message->exists() ) {
3762 $content = $message->content();
3763 $text = $message->plain();
3771 $finalTitle = $title;
3772 $title = $content->getRedirectTarget();
3776 'finalTitle' => $finalTitle,
3781 * Fetch a file and its title and register a reference to it.
3782 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3783 * @param Title $title
3784 * @param array $options Array of options to RepoGroup::findFile
3786 * @deprecated since 1.32, use fetchFileAndTitle instead
3788 public function fetchFile( $title, $options = [] ) {
3789 wfDeprecated( __METHOD__
, '1.32' );
3790 return $this->fetchFileAndTitle( $title, $options )[0];
3794 * Fetch a file and its title and register a reference to it.
3795 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3796 * @param Title $title
3797 * @param array $options Array of options to RepoGroup::findFile
3798 * @return array ( File or false, Title of file )
3800 public function fetchFileAndTitle( $title, $options = [] ) {
3801 $file = $this->fetchFileNoRegister( $title, $options );
3803 $time = $file ?
$file->getTimestamp() : false;
3804 $sha1 = $file ?
$file->getSha1() : false;
3805 # Register the file as a dependency...
3806 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3807 if ( $file && !$title->equals( $file->getTitle() ) ) {
3808 # Update fetched file title
3809 $title = $file->getTitle();
3810 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3812 return [ $file, $title ];
3816 * Helper function for fetchFileAndTitle.
3818 * Also useful if you need to fetch a file but not use it yet,
3819 * for example to get the file's handler.
3821 * @param Title $title
3822 * @param array $options Array of options to RepoGroup::findFile
3825 protected function fetchFileNoRegister( $title, $options = [] ) {
3826 if ( isset( $options['broken'] ) ) {
3827 $file = false; // broken thumbnail forced by hook
3828 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3829 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3830 } else { // get by (name,timestamp)
3831 $file = wfFindFile( $title, $options );
3837 * Transclude an interwiki link.
3839 * @param Title $title
3840 * @param string $action Usually one of (raw, render)
3844 public function interwikiTransclude( $title, $action ) {
3845 if ( !$this->siteConfig
->get( 'EnableScaryTranscluding' ) ) {
3846 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3849 $url = $title->getFullURL( [ 'action' => $action ] );
3850 if ( strlen( $url ) > 1024 ) {
3851 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3854 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3856 $fname = __METHOD__
;
3857 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3859 $data = $cache->getWithSetCallback(
3860 $cache->makeGlobalKey(
3861 'interwiki-transclude',
3862 ( $wikiId !== false ) ?
$wikiId : 'external',
3865 $this->siteConfig
->get( 'TranscludeCacheExpiry' ),
3866 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3867 $req = MWHttpRequest
::factory( $url, [], $fname );
3869 $status = $req->execute(); // Status object
3870 if ( !$status->isOK() ) {
3871 $ttl = $cache::TTL_UNCACHEABLE
;
3872 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3873 $ttl = min( $cache::TTL_LAGGED
, $ttl );
3877 'text' => $status->isOK() ?
$req->getContent() : null,
3878 'code' => $req->getStatus()
3882 'checkKeys' => ( $wikiId !== false )
3883 ?
[ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
3885 'pcGroup' => 'interwiki-transclude:5',
3886 'pcTTL' => $cache::TTL_PROC_LONG
3890 if ( is_string( $data['text'] ) ) {
3891 $text = $data['text'];
3892 } elseif ( $data['code'] != 200 ) {
3893 // Though we failed to fetch the content, this status is useless.
3894 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
3895 ->params( $url, $data['code'] )->inContentLanguage()->text();
3897 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3904 * Triple brace replacement -- used for template arguments
3907 * @param array $piece
3908 * @param PPFrame $frame
3912 public function argSubstitution( $piece, $frame ) {
3914 $parts = $piece['parts'];
3915 $nameWithSpaces = $frame->expand( $piece['title'] );
3916 $argName = trim( $nameWithSpaces );
3918 $text = $frame->getArgument( $argName );
3919 if ( $text === false && $parts->getLength() > 0
3920 && ( $this->ot
['html']
3922 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3925 # No match in frame, use the supplied default
3926 $object = $parts->item( 0 )->getChildren();
3928 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3929 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3930 $this->limitationWarn( 'post-expand-template-argument' );
3933 if ( $text === false && $object === false ) {
3935 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3937 if ( $error !== false ) {
3940 if ( $object !== false ) {
3941 $ret = [ 'object' => $object ];
3943 $ret = [ 'text' => $text ];
3950 * Return the text to be used for a given extension tag.
3951 * This is the ghost of strip().
3953 * @param array $params Associative array of parameters:
3954 * name PPNode for the tag name
3955 * attr PPNode for unparsed text where tag attributes are thought to be
3956 * attributes Optional associative array of parsed attributes
3957 * inner Contents of extension element
3958 * noClose Original text did not have a close tag
3959 * @param PPFrame $frame
3961 * @throws MWException
3964 public function extensionSubstitution( $params, $frame ) {
3965 static $errorStr = '<span class="error">';
3966 static $errorLen = 20;
3968 $name = $frame->expand( $params['name'] );
3969 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3970 // Probably expansion depth or node count exceeded. Just punt the
3975 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3976 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3981 // We can't safely check if the expansion for $content resulted in an
3982 // error, because the content could happen to be the error string
3984 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3986 $marker = self
::MARKER_PREFIX
. "-$name-"
3987 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3989 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3990 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3991 if ( $isFunctionTag ) {
3992 $markerType = 'none';
3994 $markerType = 'general';
3996 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3997 $name = strtolower( $name );
3998 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3999 if ( isset( $params['attributes'] ) ) {
4000 $attributes +
= $params['attributes'];
4003 if ( isset( $this->mTagHooks
[$name] ) ) {
4004 $output = call_user_func_array( $this->mTagHooks
[$name],
4005 [ $content, $attributes, $this, $frame ] );
4006 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4007 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4009 // Avoid PHP 7.1 warning from passing $this by reference
4011 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
4013 $output = '<span class="error">Invalid tag extension name: ' .
4014 htmlspecialchars( $name ) . '</span>';
4017 if ( is_array( $output ) ) {
4020 $output = $flags[0];
4021 if ( isset( $flags['markerType'] ) ) {
4022 $markerType = $flags['markerType'];
4026 if ( is_null( $attrText ) ) {
4029 if ( isset( $params['attributes'] ) ) {
4030 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4031 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4032 htmlspecialchars( $attrValue ) . '"';
4035 if ( $content === null ) {
4036 $output = "<$name$attrText/>";
4038 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4039 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4043 $output = "<$name$attrText>$content$close";
4047 if ( $markerType === 'none' ) {
4049 } elseif ( $markerType === 'nowiki' ) {
4050 $this->mStripState
->addNoWiki( $marker, $output );
4051 } elseif ( $markerType === 'general' ) {
4052 $this->mStripState
->addGeneral( $marker, $output );
4054 throw new MWException( __METHOD__
. ': invalid marker type' );
4060 * Increment an include size counter
4062 * @param string $type The type of expansion
4063 * @param int $size The size of the text
4064 * @return bool False if this inclusion would take it over the maximum, true otherwise
4066 public function incrementIncludeSize( $type, $size ) {
4067 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4070 $this->mIncludeSizes
[$type] +
= $size;
4076 * Increment the expensive function count
4078 * @return bool False if the limit has been exceeded
4080 public function incrementExpensiveFunctionCount() {
4081 $this->mExpensiveFunctionCount++
;
4082 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4086 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4087 * Fills $this->mDoubleUnderscores, returns the modified text
4089 * @param string $text
4093 public function doDoubleUnderscore( $text ) {
4094 # The position of __TOC__ needs to be recorded
4095 $mw = $this->magicWordFactory
->get( 'toc' );
4096 if ( $mw->match( $text ) ) {
4097 $this->mShowToc
= true;
4098 $this->mForceTocPosition
= true;
4100 # Set a placeholder. At the end we'll fill it in with the TOC.
4101 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4103 # Only keep the first one.
4104 $text = $mw->replace( '', $text );
4107 # Now match and remove the rest of them
4108 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4109 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4111 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4112 $this->mOutput
->mNoGallery
= true;
4114 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4115 $this->mShowToc
= false;
4117 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4118 && $this->mTitle
->getNamespace() == NS_CATEGORY
4120 $this->addTrackingCategory( 'hidden-category-category' );
4122 # (T10068) Allow control over whether robots index a page.
4123 # __INDEX__ always overrides __NOINDEX__, see T16899
4124 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4125 $this->mOutput
->setIndexPolicy( 'noindex' );
4126 $this->addTrackingCategory( 'noindex-category' );
4128 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4129 $this->mOutput
->setIndexPolicy( 'index' );
4130 $this->addTrackingCategory( 'index-category' );
4133 # Cache all double underscores in the database
4134 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4135 $this->mOutput
->setProperty( $key, '' );
4142 * @see ParserOutput::addTrackingCategory()
4143 * @param string $msg Message key
4144 * @return bool Whether the addition was successful
4146 public function addTrackingCategory( $msg ) {
4147 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4151 * This function accomplishes several tasks:
4152 * 1) Auto-number headings if that option is enabled
4153 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4154 * 3) Add a Table of contents on the top for users who have enabled the option
4155 * 4) Auto-anchor headings
4157 * It loops through all headlines, collects the necessary data, then splits up the
4158 * string and re-inserts the newly formatted headlines.
4160 * @param string $text
4161 * @param string $origText Original, untouched wikitext
4162 * @param bool $isMain
4163 * @return mixed|string
4166 public function formatHeadings( $text, $origText, $isMain = true ) {
4167 # Inhibit editsection links if requested in the page
4168 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4169 $maybeShowEditLink = false;
4171 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4174 # Get all headlines for numbering them and adding funky stuff like [edit]
4175 # links - this is for later, but we need the number of headlines right now
4176 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4177 # be trimmed here since whitespace in HTML headings is significant.
4179 $numMatches = preg_match_all(
4180 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4185 # if there are fewer than 4 headlines in the article, do not show TOC
4186 # unless it's been explicitly enabled.
4187 $enoughToc = $this->mShowToc
&&
4188 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4190 # Allow user to stipulate that a page should have a "new section"
4191 # link added via __NEWSECTIONLINK__
4192 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4193 $this->mOutput
->setNewSection( true );
4196 # Allow user to remove the "new section"
4197 # link via __NONEWSECTIONLINK__
4198 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4199 $this->mOutput
->hideNewSection( true );
4202 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4203 # override above conditions and always show TOC above first header
4204 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4205 $this->mShowToc
= true;
4213 # Ugh .. the TOC should have neat indentation levels which can be
4214 # passed to the skin functions. These are determined here
4218 $sublevelCount = [];
4224 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4225 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4226 $oldType = $this->mOutputType
;
4227 $this->setOutputType( self
::OT_WIKI
);
4228 $frame = $this->getPreprocessor()->newFrame();
4229 $root = $this->preprocessToDom( $origText );
4230 $node = $root->getFirstChild();
4235 $headlines = $numMatches !== false ?
$matches[3] : [];
4237 $maxTocLevel = $this->siteConfig
->get( 'MaxTocLevel' );
4238 foreach ( $headlines as $headline ) {
4239 $isTemplate = false;
4241 $sectionIndex = false;
4243 $markerMatches = [];
4244 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4245 $serial = $markerMatches[1];
4246 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4247 $isTemplate = ( $titleText != $baseTitleText );
4248 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4252 $prevlevel = $level;
4254 $level = $matches[1][$headlineCount];
4256 if ( $level > $prevlevel ) {
4257 # Increase TOC level
4259 $sublevelCount[$toclevel] = 0;
4260 if ( $toclevel < $maxTocLevel ) {
4261 $prevtoclevel = $toclevel;
4262 $toc .= Linker
::tocIndent();
4265 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4266 # Decrease TOC level, find level to jump to
4268 for ( $i = $toclevel; $i > 0; $i-- ) {
4269 if ( $levelCount[$i] == $level ) {
4270 # Found last matching level
4273 } elseif ( $levelCount[$i] < $level ) {
4274 # Found first matching level below current level
4282 if ( $toclevel < $maxTocLevel ) {
4283 if ( $prevtoclevel < $maxTocLevel ) {
4284 # Unindent only if the previous toc level was shown :p
4285 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4286 $prevtoclevel = $toclevel;
4288 $toc .= Linker
::tocLineEnd();
4292 # No change in level, end TOC line
4293 if ( $toclevel < $maxTocLevel ) {
4294 $toc .= Linker
::tocLineEnd();
4298 $levelCount[$toclevel] = $level;
4300 # count number of headlines for each level
4301 $sublevelCount[$toclevel]++
;
4303 for ( $i = 1; $i <= $toclevel; $i++
) {
4304 if ( !empty( $sublevelCount[$i] ) ) {
4308 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4313 # The safe header is a version of the header text safe to use for links
4315 # Remove link placeholders by the link text.
4316 # <!--LINK number-->
4318 # link text with suffix
4319 # Do this before unstrip since link text can contain strip markers
4320 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4322 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4323 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4325 # Remove any <style> or <script> tags (T198618)
4326 $safeHeadline = preg_replace(
4327 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4332 # Strip out HTML (first regex removes any tag not allowed)
4334 # * <sup> and <sub> (T10393)
4338 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4339 # * <s> and <strike> (T35715)
4340 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4341 # to allow setting directionality in toc items.
4342 $tocline = preg_replace(
4344 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4345 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4351 # Strip '<span></span>', which is the result from the above if
4352 # <span id="foo"></span> is used to produce an additional anchor
4354 $tocline = str_replace( '<span></span>', '', $tocline );
4356 $tocline = trim( $tocline );
4358 # For the anchor, strip out HTML-y stuff period
4359 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4360 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4362 # Save headline for section edit hint before it's escaped
4363 $headlineHint = $safeHeadline;
4365 # Decode HTML entities
4366 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4368 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4370 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4371 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4372 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4373 if ( $fallbackHeadline === $safeHeadline ) {
4374 # No reason to have both (in fact, we can't)
4375 $fallbackHeadline = false;
4378 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4379 # @todo FIXME: We may be changing them depending on the current locale.
4380 $arrayKey = strtolower( $safeHeadline );
4381 if ( $fallbackHeadline === false ) {
4382 $fallbackArrayKey = false;
4384 $fallbackArrayKey = strtolower( $fallbackHeadline );
4387 # Create the anchor for linking from the TOC to the section
4388 $anchor = $safeHeadline;
4389 $fallbackAnchor = $fallbackHeadline;
4390 if ( isset( $refers[$arrayKey] ) ) {
4391 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4392 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4394 $linkAnchor .= "_$i";
4395 $refers["${arrayKey}_$i"] = true;
4397 $refers[$arrayKey] = true;
4399 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4400 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4401 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4402 $fallbackAnchor .= "_$i";
4403 $refers["${fallbackArrayKey}_$i"] = true;
4405 $refers[$fallbackArrayKey] = true;
4408 # Don't number the heading if it is the only one (looks silly)
4409 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4410 # the two are different if the line contains a link
4411 $headline = Html
::element(
4413 [ 'class' => 'mw-headline-number' ],
4415 ) . ' ' . $headline;
4418 if ( $enoughToc && ( !isset( $maxTocLevel ) ||
$toclevel < $maxTocLevel ) ) {
4419 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4420 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4423 # Add the section to the section tree
4424 # Find the DOM node for this header
4425 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4426 while ( $node && !$noOffset ) {
4427 if ( $node->getName() === 'h' ) {
4428 $bits = $node->splitHeading();
4429 if ( $bits['i'] == $sectionIndex ) {
4433 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4434 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4435 $node = $node->getNextSibling();
4438 'toclevel' => $toclevel,
4441 'number' => $numbering,
4442 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4443 'fromtitle' => $titleText,
4444 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4445 'anchor' => $anchor,
4448 # give headline the correct <h#> tag
4449 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4450 // Output edit section links as markers with styles that can be customized by skins
4451 if ( $isTemplate ) {
4452 # Put a T flag in the section identifier, to indicate to extractSections()
4453 # that sections inside <includeonly> should be counted.
4454 $editsectionPage = $titleText;
4455 $editsectionSection = "T-$sectionIndex";
4456 $editsectionContent = null;
4458 $editsectionPage = $this->mTitle
->getPrefixedText();
4459 $editsectionSection = $sectionIndex;
4460 $editsectionContent = $headlineHint;
4462 // We use a bit of pesudo-xml for editsection markers. The
4463 // language converter is run later on. Using a UNIQ style marker
4464 // leads to the converter screwing up the tokens when it
4465 // converts stuff. And trying to insert strip tags fails too. At
4466 // this point all real inputted tags have already been escaped,
4467 // so we don't have to worry about a user trying to input one of
4468 // these markers directly. We use a page and section attribute
4469 // to stop the language converter from converting these
4470 // important bits of data, but put the headline hint inside a
4471 // content block because the language converter is supposed to
4472 // be able to convert that piece of data.
4473 // Gets replaced with html in ParserOutput::getText
4474 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4475 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4476 if ( $editsectionContent !== null ) {
4477 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4484 $head[$headlineCount] = Linker
::makeHeadline( $level,
4485 $matches['attrib'][$headlineCount], $anchor, $headline,
4486 $editlink, $fallbackAnchor );
4491 $this->setOutputType( $oldType );
4493 # Never ever show TOC if no headers
4494 if ( $numVisible < 1 ) {
4499 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4500 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4502 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4503 $this->mOutput
->setTOCHTML( $toc );
4504 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4508 $this->mOutput
->setSections( $tocraw );
4511 # split up and insert constructed headlines
4512 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4515 // build an array of document sections
4517 foreach ( $blocks as $block ) {
4518 // $head is zero-based, sections aren't.
4519 if ( empty( $head[$i - 1] ) ) {
4520 $sections[$i] = $block;
4522 $sections[$i] = $head[$i - 1] . $block;
4526 * Send a hook, one per section.
4527 * The idea here is to be able to make section-level DIVs, but to do so in a
4528 * lower-impact, more correct way than r50769
4531 * $section : the section number
4532 * &$sectionContent : ref to the content of the section
4533 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4535 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4540 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4541 // append the TOC at the beginning
4542 // Top anchor now in skin
4543 $sections[0] .= $toc . "\n";
4546 $full .= implode( '', $sections );
4548 if ( $this->mForceTocPosition
) {
4549 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4556 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4557 * conversion, substituting signatures, {{subst:}} templates, etc.
4559 * @param string $text The text to transform
4560 * @param Title $title The Title object for the current article
4561 * @param User $user The User object describing the current user
4562 * @param ParserOptions $options Parsing options
4563 * @param bool $clearState Whether to clear the parser state first
4564 * @return string The altered wiki markup
4566 public function preSaveTransform( $text, Title
$title, User
$user,
4567 ParserOptions
$options, $clearState = true
4569 if ( $clearState ) {
4570 $magicScopeVariable = $this->lock();
4572 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4573 $this->setUser( $user );
4575 // Strip U+0000 NULL (T159174)
4576 $text = str_replace( "\000", '', $text );
4578 // We still normalize line endings for backwards-compatibility
4579 // with other code that just calls PST, but this should already
4580 // be handled in TextContent subclasses
4581 $text = TextContent
::normalizeLineEndings( $text );
4583 if ( $options->getPreSaveTransform() ) {
4584 $text = $this->pstPass2( $text, $user );
4586 $text = $this->mStripState
->unstripBoth( $text );
4588 $this->setUser( null ); # Reset
4594 * Pre-save transform helper function
4596 * @param string $text
4601 private function pstPass2( $text, $user ) {
4602 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4603 # $this->contLang here in order to give everyone the same signature and use the default one
4604 # rather than the one selected in each user's preferences. (see also T14815)
4605 $ts = $this->mOptions
->getTimestamp();
4606 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4607 $ts = $timestamp->format( 'YmdHis' );
4608 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4610 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4612 # Variable replacement
4613 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4614 $text = $this->replaceVariables( $text );
4616 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4617 # which may corrupt this parser instance via its wfMessage()->text() call-
4620 if ( strpos( $text, '~~~' ) !== false ) {
4621 $sigText = $this->getUserSig( $user );
4622 $text = strtr( $text, [
4624 '~~~~' => "$sigText $d",
4627 # The main two signature forms used above are time-sensitive
4628 $this->mOutput
->setFlag( 'user-signature' );
4631 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4632 $tc = '[' . Title
::legalChars() . ']';
4633 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4635 // [[ns:page (context)|]]
4636 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4637 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4638 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4639 // [[ns:page (context), context|]] (using either single or double-width comma)
4640 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4641 // [[|page]] (reverse pipe trick: add context from page title)
4642 $p2 = "/\[\[\\|($tc+)]]/";
4644 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4645 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4646 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4647 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4649 $t = $this->mTitle
->getText();
4651 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4652 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4653 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4654 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4656 # if there's no context, don't bother duplicating the title
4657 $text = preg_replace( $p2, '[[\\1]]', $text );
4664 * Fetch the user's signature text, if any, and normalize to
4665 * validated, ready-to-insert wikitext.
4666 * If you have pre-fetched the nickname or the fancySig option, you can
4667 * specify them here to save a database query.
4668 * Do not reuse this parser instance after calling getUserSig(),
4669 * as it may have changed if it's the $wgParser.
4671 * @param User &$user
4672 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4673 * @param bool|null $fancySig whether the nicknname is the complete signature
4674 * or null to use default value
4677 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4678 $username = $user->getName();
4680 # If not given, retrieve from the user object.
4681 if ( $nickname === false ) {
4682 $nickname = $user->getOption( 'nickname' );
4685 if ( is_null( $fancySig ) ) {
4686 $fancySig = $user->getBoolOption( 'fancysig' );
4689 $nickname = $nickname == null ?
$username : $nickname;
4691 if ( mb_strlen( $nickname ) > $this->siteConfig
->get( 'MaxSigChars' ) ) {
4692 $nickname = $username;
4693 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4694 } elseif ( $fancySig !== false ) {
4695 # Sig. might contain markup; validate this
4696 if ( $this->validateSig( $nickname ) !== false ) {
4697 # Validated; clean up (if needed) and return it
4698 return $this->cleanSig( $nickname, true );
4700 # Failed to validate; fall back to the default
4701 $nickname = $username;
4702 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4706 # Make sure nickname doesnt get a sig in a sig
4707 $nickname = self
::cleanSigInSig( $nickname );
4709 # If we're still here, make it a link to the user page
4710 $userText = wfEscapeWikiText( $username );
4711 $nickText = wfEscapeWikiText( $nickname );
4712 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4714 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4715 ->title( $this->getTitle() )->text();
4719 * Check that the user's signature contains no bad XML
4721 * @param string $text
4722 * @return string|bool An expanded string, or false if invalid.
4724 public function validateSig( $text ) {
4725 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4729 * Clean up signature text
4731 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4732 * 2) Substitute all transclusions
4734 * @param string $text
4735 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4736 * @return string Signature text
4738 public function cleanSig( $text, $parsing = false ) {
4741 $magicScopeVariable = $this->lock();
4742 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4745 # Option to disable this feature
4746 if ( !$this->mOptions
->getCleanSignatures() ) {
4750 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4751 # => Move this logic to braceSubstitution()
4752 $substWord = $this->magicWordFactory
->get( 'subst' );
4753 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4754 $substText = '{{' . $substWord->getSynonym( 0 );
4756 $text = preg_replace( $substRegex, $substText, $text );
4757 $text = self
::cleanSigInSig( $text );
4758 $dom = $this->preprocessToDom( $text );
4759 $frame = $this->getPreprocessor()->newFrame();
4760 $text = $frame->expand( $dom );
4763 $text = $this->mStripState
->unstripBoth( $text );
4770 * Strip 3, 4 or 5 tildes out of signatures.
4772 * @param string $text
4773 * @return string Signature text with /~{3,5}/ removed
4775 public static function cleanSigInSig( $text ) {
4776 $text = preg_replace( '/~{3,5}/', '', $text );
4781 * Set up some variables which are usually set up in parse()
4782 * so that an external function can call some class members with confidence
4784 * @param Title|null $title
4785 * @param ParserOptions $options
4786 * @param int $outputType
4787 * @param bool $clearState
4789 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4790 $outputType, $clearState = true
4792 $this->startParse( $title, $options, $outputType, $clearState );
4796 * @param Title|null $title
4797 * @param ParserOptions $options
4798 * @param int $outputType
4799 * @param bool $clearState
4801 private function startParse( Title
$title = null, ParserOptions
$options,
4802 $outputType, $clearState = true
4804 $this->setTitle( $title );
4805 $this->mOptions
= $options;
4806 $this->setOutputType( $outputType );
4807 if ( $clearState ) {
4808 $this->clearState();
4813 * Wrapper for preprocess()
4815 * @param string $text The text to preprocess
4816 * @param ParserOptions $options
4817 * @param Title|null $title Title object or null to use $wgTitle
4820 public function transformMsg( $text, $options, $title = null ) {
4821 static $executing = false;
4823 # Guard against infinite recursion
4834 $text = $this->preprocess( $text, $title, $options );
4841 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4842 * The callback should have the following form:
4843 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4845 * Transform and return $text. Use $parser for any required context, e.g. use
4846 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4848 * Hooks may return extended information by returning an array, of which the
4849 * first numbered element (index 0) must be the return string, and all other
4850 * entries are extracted into local variables within an internal function
4851 * in the Parser class.
4853 * This interface (introduced r61913) appears to be undocumented, but
4854 * 'markerType' is used by some core tag hooks to override which strip
4855 * array their results are placed in. **Use great caution if attempting
4856 * this interface, as it is not documented and injudicious use could smash
4857 * private variables.**
4859 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4860 * @param callable $callback The callback function (and object) to use for the tag
4861 * @throws MWException
4862 * @return callable|null The old value of the mTagHooks array associated with the hook
4864 public function setHook( $tag, callable
$callback ) {
4865 $tag = strtolower( $tag );
4866 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4867 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4869 $oldVal = $this->mTagHooks
[$tag] ??
null;
4870 $this->mTagHooks
[$tag] = $callback;
4871 if ( !in_array( $tag, $this->mStripList
) ) {
4872 $this->mStripList
[] = $tag;
4879 * As setHook(), but letting the contents be parsed.
4881 * Transparent tag hooks are like regular XML-style tag hooks, except they
4882 * operate late in the transformation sequence, on HTML instead of wikitext.
4884 * This is probably obsoleted by things dealing with parser frames?
4885 * The only extension currently using it is geoserver.
4888 * @todo better document or deprecate this
4890 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4891 * @param callable $callback The callback function (and object) to use for the tag
4892 * @throws MWException
4893 * @return callable|null The old value of the mTagHooks array associated with the hook
4895 public function setTransparentTagHook( $tag, callable
$callback ) {
4896 $tag = strtolower( $tag );
4897 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4898 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4900 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4901 $this->mTransparentTagHooks
[$tag] = $callback;
4907 * Remove all tag hooks
4909 public function clearTagHooks() {
4910 $this->mTagHooks
= [];
4911 $this->mFunctionTagHooks
= [];
4912 $this->mStripList
= $this->mDefaultStripList
;
4916 * Create a function, e.g. {{sum:1|2|3}}
4917 * The callback function should have the form:
4918 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4920 * Or with Parser::SFH_OBJECT_ARGS:
4921 * function myParserFunction( $parser, $frame, $args ) { ... }
4923 * The callback may either return the text result of the function, or an array with the text
4924 * in element 0, and a number of flags in the other elements. The names of the flags are
4925 * specified in the keys. Valid flags are:
4926 * found The text returned is valid, stop processing the template. This
4928 * nowiki Wiki markup in the return value should be escaped
4929 * isHTML The returned text is HTML, armour it against wikitext transformation
4931 * @param string $id The magic word ID
4932 * @param callable $callback The callback function (and object) to use
4933 * @param int $flags A combination of the following flags:
4934 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4936 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4937 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4938 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4939 * the arguments, and to control the way they are expanded.
4941 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4942 * arguments, for instance:
4943 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4945 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4946 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4947 * working if/when this is changed.
4949 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4952 * Please read the documentation in includes/parser/Preprocessor.php for more information
4953 * about the methods available in PPFrame and PPNode.
4955 * @throws MWException
4956 * @return string|callable The old callback function for this name, if any
4958 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4959 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4960 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4962 # Add to function cache
4963 $mw = $this->magicWordFactory
->get( $id );
4965 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4968 $synonyms = $mw->getSynonyms();
4969 $sensitive = intval( $mw->isCaseSensitive() );
4971 foreach ( $synonyms as $syn ) {
4973 if ( !$sensitive ) {
4974 $syn = $this->contLang
->lc( $syn );
4977 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4980 # Remove trailing colon
4981 if ( substr( $syn, -1, 1 ) === ':' ) {
4982 $syn = substr( $syn, 0, -1 );
4984 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4990 * Get all registered function hook identifiers
4994 public function getFunctionHooks() {
4995 $this->firstCallInit();
4996 return array_keys( $this->mFunctionHooks
);
5000 * Create a tag function, e.g. "<test>some stuff</test>".
5001 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5002 * Unlike parser functions, their content is not preprocessed.
5003 * @param string $tag
5004 * @param callable $callback
5006 * @throws MWException
5009 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
5010 $tag = strtolower( $tag );
5011 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5012 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5014 $old = $this->mFunctionTagHooks
[$tag] ??
null;
5015 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
5017 if ( !in_array( $tag, $this->mStripList
) ) {
5018 $this->mStripList
[] = $tag;
5025 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5026 * Placeholders created in Linker::link()
5028 * @param string &$text
5029 * @param int $options
5031 public function replaceLinkHolders( &$text, $options = 0 ) {
5032 $this->mLinkHolders
->replace( $text );
5036 * Replace "<!--LINK-->" link placeholders with plain text of links
5037 * (not HTML-formatted).
5039 * @param string $text
5042 public function replaceLinkHoldersText( $text ) {
5043 return $this->mLinkHolders
->replaceText( $text );
5047 * Renders an image gallery from a text with one line per image.
5048 * text labels may be given by using |-style alternative text. E.g.
5049 * Image:one.jpg|The number "1"
5050 * Image:tree.jpg|A tree
5051 * given as text will return the HTML of a gallery with two images,
5052 * labeled 'The number "1"' and
5055 * @param string $text
5056 * @param array $params
5057 * @return string HTML
5059 public function renderImageGallery( $text, $params ) {
5061 if ( isset( $params['mode'] ) ) {
5062 $mode = $params['mode'];
5066 $ig = ImageGalleryBase
::factory( $mode );
5067 } catch ( Exception
$e ) {
5068 // If invalid type set, fallback to default.
5069 $ig = ImageGalleryBase
::factory( false );
5072 $ig->setContextTitle( $this->mTitle
);
5073 $ig->setShowBytes( false );
5074 $ig->setShowDimensions( false );
5075 $ig->setShowFilename( false );
5076 $ig->setParser( $this );
5077 $ig->setHideBadImages();
5078 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5080 if ( isset( $params['showfilename'] ) ) {
5081 $ig->setShowFilename( true );
5083 $ig->setShowFilename( false );
5085 if ( isset( $params['caption'] ) ) {
5086 // NOTE: We aren't passing a frame here or below. Frame info
5087 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5088 // See T107332#4030581
5089 $caption = $this->recursiveTagParse( $params['caption'] );
5090 $ig->setCaptionHtml( $caption );
5092 if ( isset( $params['perrow'] ) ) {
5093 $ig->setPerRow( $params['perrow'] );
5095 if ( isset( $params['widths'] ) ) {
5096 $ig->setWidths( $params['widths'] );
5098 if ( isset( $params['heights'] ) ) {
5099 $ig->setHeights( $params['heights'] );
5101 $ig->setAdditionalOptions( $params );
5103 // Avoid PHP 7.1 warning from passing $this by reference
5105 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5107 $lines = StringUtils
::explode( "\n", $text );
5108 foreach ( $lines as $line ) {
5109 # match lines like these:
5110 # Image:someimage.jpg|This is some image
5112 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5114 if ( count( $matches ) == 0 ) {
5118 if ( strpos( $matches[0], '%' ) !== false ) {
5119 $matches[1] = rawurldecode( $matches[1] );
5121 $title = Title
::newFromText( $matches[1], NS_FILE
);
5122 if ( is_null( $title ) ) {
5123 # Bogus title. Ignore these so we don't bomb out later.
5127 # We need to get what handler the file uses, to figure out parameters.
5128 # Note, a hook can overide the file name, and chose an entirely different
5129 # file (which potentially could be of a different type and have different handler).
5132 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5133 [ $this, $title, &$options, &$descQuery ] );
5134 # Don't register it now, as TraditionalImageGallery does that later.
5135 $file = $this->fetchFileNoRegister( $title, $options );
5136 $handler = $file ?
$file->getHandler() : false;
5139 'img_alt' => 'gallery-internal-alt',
5140 'img_link' => 'gallery-internal-link',
5143 $paramMap +
= $handler->getParamMap();
5144 // We don't want people to specify per-image widths.
5145 // Additionally the width parameter would need special casing anyhow.
5146 unset( $paramMap['img_width'] );
5149 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5154 $handlerOptions = [];
5155 if ( isset( $matches[3] ) ) {
5156 // look for an |alt= definition while trying not to break existing
5157 // captions with multiple pipes (|) in it, until a more sensible grammar
5158 // is defined for images in galleries
5160 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5161 // splitting on '|' is a bit odd, and different from makeImage.
5162 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5163 // Protect LanguageConverter markup
5164 $parameterMatches = StringUtils
::delimiterExplode(
5165 '-{', '}-', '|', $matches[3], true /* nested */
5168 foreach ( $parameterMatches as $parameterMatch ) {
5169 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5171 $paramName = $paramMap[$magicName];
5173 switch ( $paramName ) {
5174 case 'gallery-internal-alt':
5175 $alt = $this->stripAltText( $match, false );
5177 case 'gallery-internal-link':
5178 $linkValue = $this->stripAltText( $match, false );
5179 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5180 // Result of LanguageConverter::markNoConversion
5181 // invoked on an external link.
5182 $linkValue = substr( $linkValue, 4, -2 );
5184 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5185 if ( $type === 'link-url' ) {
5187 $this->mOutput
->addExternalLink( $target );
5188 } elseif ( $type === 'link-title' ) {
5189 $link = $target->getLinkURL();
5190 $this->mOutput
->addLink( $target );
5194 // Must be a handler specific parameter.
5195 if ( $handler->validateParam( $paramName, $match ) ) {
5196 $handlerOptions[$paramName] = $match;
5198 // Guess not, consider it as caption.
5199 wfDebug( "$parameterMatch failed parameter validation\n" );
5200 $label = $parameterMatch;
5206 $label = $parameterMatch;
5211 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5213 $html = $ig->toHTML();
5214 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5219 * @param MediaHandler $handler
5222 public function getImageParams( $handler ) {
5224 $handlerClass = get_class( $handler );
5228 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5229 # Initialise static lists
5230 static $internalParamNames = [
5231 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5232 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5233 'bottom', 'text-bottom' ],
5234 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5235 'upright', 'border', 'link', 'alt', 'class' ],
5237 static $internalParamMap;
5238 if ( !$internalParamMap ) {
5239 $internalParamMap = [];
5240 foreach ( $internalParamNames as $type => $names ) {
5241 foreach ( $names as $name ) {
5242 // For grep: img_left, img_right, img_center, img_none,
5243 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5244 // img_bottom, img_text_bottom,
5245 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5246 // img_border, img_link, img_alt, img_class
5247 $magicName = str_replace( '-', '_', "img_$name" );
5248 $internalParamMap[$magicName] = [ $type, $name ];
5253 # Add handler params
5254 $paramMap = $internalParamMap;
5256 $handlerParamMap = $handler->getParamMap();
5257 foreach ( $handlerParamMap as $magic => $paramName ) {
5258 $paramMap[$magic] = [ 'handler', $paramName ];
5261 $this->mImageParams
[$handlerClass] = $paramMap;
5262 $this->mImageParamsMagicArray
[$handlerClass] =
5263 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5265 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5269 * Parse image options text and use it to make an image
5271 * @param Title $title
5272 * @param string $options
5273 * @param LinkHolderArray|bool $holders
5274 * @return string HTML
5276 public function makeImage( $title, $options, $holders = false ) {
5277 # Check if the options text is of the form "options|alt text"
5279 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5280 # * left no resizing, just left align. label is used for alt= only
5281 # * right same, but right aligned
5282 # * none same, but not aligned
5283 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5284 # * center center the image
5285 # * frame Keep original image size, no magnify-button.
5286 # * framed Same as "frame"
5287 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5288 # * upright reduce width for upright images, rounded to full __0 px
5289 # * border draw a 1px border around the image
5290 # * alt Text for HTML alt attribute (defaults to empty)
5291 # * class Set a class for img node
5292 # * link Set the target of the image link. Can be external, interwiki, or local
5293 # vertical-align values (no % or length right now):
5303 # Protect LanguageConverter markup when splitting into parts
5304 $parts = StringUtils
::delimiterExplode(
5305 '-{', '}-', '|', $options, true /* allow nesting */
5308 # Give extensions a chance to select the file revision for us
5311 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5312 [ $this, $title, &$options, &$descQuery ] );
5313 # Fetch and register the file (file title may be different via hooks)
5314 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5317 $handler = $file ?
$file->getHandler() : false;
5319 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5322 $this->addTrackingCategory( 'broken-file-category' );
5325 # Process the input parameters
5327 $params = [ 'frame' => [], 'handler' => [],
5328 'horizAlign' => [], 'vertAlign' => [] ];
5329 $seenformat = false;
5330 foreach ( $parts as $part ) {
5331 $part = trim( $part );
5332 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5334 if ( isset( $paramMap[$magicName] ) ) {
5335 list( $type, $paramName ) = $paramMap[$magicName];
5337 # Special case; width and height come in one variable together
5338 if ( $type === 'handler' && $paramName === 'width' ) {
5339 $parsedWidthParam = self
::parseWidthParam( $value );
5340 if ( isset( $parsedWidthParam['width'] ) ) {
5341 $width = $parsedWidthParam['width'];
5342 if ( $handler->validateParam( 'width', $width ) ) {
5343 $params[$type]['width'] = $width;
5347 if ( isset( $parsedWidthParam['height'] ) ) {
5348 $height = $parsedWidthParam['height'];
5349 if ( $handler->validateParam( 'height', $height ) ) {
5350 $params[$type]['height'] = $height;
5354 # else no validation -- T15436
5356 if ( $type === 'handler' ) {
5357 # Validate handler parameter
5358 $validated = $handler->validateParam( $paramName, $value );
5360 # Validate internal parameters
5361 switch ( $paramName ) {
5365 # @todo FIXME: Possibly check validity here for
5366 # manualthumb? downstream behavior seems odd with
5367 # missing manual thumbs.
5369 $value = $this->stripAltText( $value, $holders );
5372 list( $paramName, $value ) =
5373 $this->parseLinkParameter(
5374 $this->stripAltText( $value, $holders )
5378 if ( $paramName === 'no-link' ) {
5381 if ( ( $paramName === 'link-url' ) && $this->mOptions
->getExternalLinkTarget() ) {
5382 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5389 // use first appearing option, discard others.
5390 $validated = !$seenformat;
5394 # Most other things appear to be empty or numeric...
5395 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5400 $params[$type][$paramName] = $value;
5404 if ( !$validated ) {
5409 # Process alignment parameters
5410 if ( $params['horizAlign'] ) {
5411 $params['frame']['align'] = key( $params['horizAlign'] );
5413 if ( $params['vertAlign'] ) {
5414 $params['frame']['valign'] = key( $params['vertAlign'] );
5417 $params['frame']['caption'] = $caption;
5419 # Will the image be presented in a frame, with the caption below?
5420 $imageIsFramed = isset( $params['frame']['frame'] )
5421 ||
isset( $params['frame']['framed'] )
5422 ||
isset( $params['frame']['thumbnail'] )
5423 ||
isset( $params['frame']['manualthumb'] );
5425 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5426 # came to also set the caption, ordinary text after the image -- which
5427 # makes no sense, because that just repeats the text multiple times in
5428 # screen readers. It *also* came to set the title attribute.
5429 # Now that we have an alt attribute, we should not set the alt text to
5430 # equal the caption: that's worse than useless, it just repeats the
5431 # text. This is the framed/thumbnail case. If there's no caption, we
5432 # use the unnamed parameter for alt text as well, just for the time be-
5433 # ing, if the unnamed param is set and the alt param is not.
5434 # For the future, we need to figure out if we want to tweak this more,
5435 # e.g., introducing a title= parameter for the title; ignoring the un-
5436 # named parameter entirely for images without a caption; adding an ex-
5437 # plicit caption= parameter and preserving the old magic unnamed para-
5439 if ( $imageIsFramed ) { # Framed image
5440 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5441 # No caption or alt text, add the filename as the alt text so
5442 # that screen readers at least get some description of the image
5443 $params['frame']['alt'] = $title->getText();
5445 # Do not set $params['frame']['title'] because tooltips don't make sense
5447 } else { # Inline image
5448 if ( !isset( $params['frame']['alt'] ) ) {
5449 # No alt text, use the "caption" for the alt text
5450 if ( $caption !== '' ) {
5451 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5453 # No caption, fall back to using the filename for the
5455 $params['frame']['alt'] = $title->getText();
5458 # Use the "caption" for the tooltip text
5459 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5461 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5463 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5465 # Linker does the rest
5466 $time = $options['time'] ??
false;
5467 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5468 $time, $descQuery, $this->mOptions
->getThumbSize() );
5470 # Give the handler a chance to modify the parser object
5472 $handler->parserTransformHook( $this, $file );
5479 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5481 * Adds an entry to appropriate link tables.
5484 * @param string $value
5485 * @return array of `[ type, target ]`, where:
5486 * - `type` is one of:
5487 * - `null`: Given value is not a valid link target, use default
5488 * - `'no-link'`: Given value is empty, do not generate a link
5489 * - `'link-url'`: Given value is a valid external link
5490 * - `'link-title'`: Given value is a valid internal link
5492 * - When `type` is `null` or `'no-link'`: `false`
5493 * - When `type` is `'link-url'`: URL string corresponding to given value
5494 * - When `type` is `'link-title'`: Title object corresponding to given value
5496 public function parseLinkParameter( $value ) {
5497 $chars = self
::EXT_LINK_URL_CLASS
;
5498 $addr = self
::EXT_LINK_ADDR
;
5499 $prots = $this->mUrlProtocols
;
5502 if ( $value === '' ) {
5504 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5505 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5506 $this->mOutput
->addExternalLink( $value );
5511 $linkTitle = Title
::newFromText( $value );
5513 $this->mOutput
->addLink( $linkTitle );
5514 $type = 'link-title';
5515 $target = $linkTitle;
5518 return [ $type, $target ];
5522 * @param string $caption
5523 * @param LinkHolderArray|bool $holders
5524 * @return mixed|string
5526 protected function stripAltText( $caption, $holders ) {
5527 # Strip bad stuff out of the title (tooltip). We can't just use
5528 # replaceLinkHoldersText() here, because if this function is called
5529 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5531 $tooltip = $holders->replaceText( $caption );
5533 $tooltip = $this->replaceLinkHoldersText( $caption );
5536 # make sure there are no placeholders in thumbnail attributes
5537 # that are later expanded to html- so expand them now and
5539 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5540 # Compatibility hack! In HTML certain entity references not terminated
5541 # by a semicolon are decoded (but not if we're in an attribute; that's
5542 # how link URLs get away without properly escaping & in queries).
5543 # But wikitext has always required semicolon-termination of entities,
5544 # so encode & where needed to avoid decode of semicolon-less entities.
5546 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5547 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5548 $tooltip = preg_replace( "/
5549 & # 1. entity prefix
5550 (?= # 2. followed by:
5551 (?: # a. one of the legacy semicolon-less named entities
5552 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5553 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5554 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5555 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5556 U(?:acute|circ|grave|uml)|Yacute|
5557 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5558 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5559 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5560 frac(?:1(?:2|4)|34)|
5561 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5562 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5563 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5564 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5565 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5566 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5567 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5568 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5569 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5571 (?:[^;]|$)) # b. and not followed by a semicolon
5572 # S = study, for efficiency
5573 /Sx", '&', $tooltip );
5574 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5580 * Set a flag in the output object indicating that the content is dynamic and
5581 * shouldn't be cached.
5582 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5584 public function disableCache() {
5585 wfDebug( "Parser output marked as uncacheable.\n" );
5586 if ( !$this->mOutput
) {
5587 throw new MWException( __METHOD__
.
5588 " can only be called when actually parsing something" );
5590 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5594 * Callback from the Sanitizer for expanding items found in HTML attribute
5595 * values, so they can be safely tested and escaped.
5597 * @param string &$text
5598 * @param bool|PPFrame $frame
5601 public function attributeStripCallback( &$text, $frame = false ) {
5602 $text = $this->replaceVariables( $text, $frame );
5603 $text = $this->mStripState
->unstripBoth( $text );
5612 public function getTags() {
5613 $this->firstCallInit();
5615 array_keys( $this->mTransparentTagHooks
),
5616 array_keys( $this->mTagHooks
),
5617 array_keys( $this->mFunctionTagHooks
)
5625 public function getFunctionSynonyms() {
5626 $this->firstCallInit();
5627 return $this->mFunctionSynonyms
;
5634 public function getUrlProtocols() {
5635 return $this->mUrlProtocols
;
5639 * Replace transparent tags in $text with the values given by the callbacks.
5641 * Transparent tag hooks are like regular XML-style tag hooks, except they
5642 * operate late in the transformation sequence, on HTML instead of wikitext.
5644 * @param string $text
5648 public function replaceTransparentTags( $text ) {
5650 $elements = array_keys( $this->mTransparentTagHooks
);
5651 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5654 foreach ( $matches as $marker => $data ) {
5655 list( $element, $content, $params, $tag ) = $data;
5656 $tagName = strtolower( $element );
5657 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5658 $output = call_user_func_array(
5659 $this->mTransparentTagHooks
[$tagName],
5660 [ $content, $params, $this ]
5665 $replacements[$marker] = $output;
5667 return strtr( $text, $replacements );
5671 * Break wikitext input into sections, and either pull or replace
5672 * some particular section's text.
5674 * External callers should use the getSection and replaceSection methods.
5676 * @param string $text Page wikitext
5677 * @param string|int $sectionId A section identifier string of the form:
5678 * "<flag1> - <flag2> - ... - <section number>"
5680 * Currently the only recognised flag is "T", which means the target section number
5681 * was derived during a template inclusion parse, in other words this is a template
5682 * section edit link. If no flags are given, it was an ordinary section edit link.
5683 * This flag is required to avoid a section numbering mismatch when a section is
5684 * enclosed by "<includeonly>" (T8563).
5686 * The section number 0 pulls the text before the first heading; other numbers will
5687 * pull the given section along with its lower-level subsections. If the section is
5688 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5690 * Section 0 is always considered to exist, even if it only contains the empty
5691 * string. If $text is the empty string and section 0 is replaced, $newText is
5694 * @param string $mode One of "get" or "replace"
5695 * @param string $newText Replacement text for section data.
5696 * @return string For "get", the extracted section text.
5697 * for "replace", the whole page with the section replaced.
5699 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5700 global $wgTitle; # not generally used but removes an ugly failure mode
5702 $magicScopeVariable = $this->lock();
5703 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5705 $frame = $this->getPreprocessor()->newFrame();
5707 # Process section extraction flags
5709 $sectionParts = explode( '-', $sectionId );
5710 $sectionIndex = array_pop( $sectionParts );
5711 foreach ( $sectionParts as $part ) {
5712 if ( $part === 'T' ) {
5713 $flags |
= self
::PTD_FOR_INCLUSION
;
5717 # Check for empty input
5718 if ( strval( $text ) === '' ) {
5719 # Only sections 0 and T-0 exist in an empty document
5720 if ( $sectionIndex == 0 ) {
5721 if ( $mode === 'get' ) {
5727 if ( $mode === 'get' ) {
5735 # Preprocess the text
5736 $root = $this->preprocessToDom( $text, $flags );
5738 # <h> nodes indicate section breaks
5739 # They can only occur at the top level, so we can find them by iterating the root's children
5740 $node = $root->getFirstChild();
5742 # Find the target section
5743 if ( $sectionIndex == 0 ) {
5744 # Section zero doesn't nest, level=big
5745 $targetLevel = 1000;
5748 if ( $node->getName() === 'h' ) {
5749 $bits = $node->splitHeading();
5750 if ( $bits['i'] == $sectionIndex ) {
5751 $targetLevel = $bits['level'];
5755 if ( $mode === 'replace' ) {
5756 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5758 $node = $node->getNextSibling();
5764 if ( $mode === 'get' ) {
5771 # Find the end of the section, including nested sections
5773 if ( $node->getName() === 'h' ) {
5774 $bits = $node->splitHeading();
5775 $curLevel = $bits['level'];
5776 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5780 if ( $mode === 'get' ) {
5781 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5783 $node = $node->getNextSibling();
5786 # Write out the remainder (in replace mode only)
5787 if ( $mode === 'replace' ) {
5788 # Output the replacement text
5789 # Add two newlines on -- trailing whitespace in $newText is conventionally
5790 # stripped by the editor, so we need both newlines to restore the paragraph gap
5791 # Only add trailing whitespace if there is newText
5792 if ( $newText != "" ) {
5793 $outText .= $newText . "\n\n";
5797 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5798 $node = $node->getNextSibling();
5802 if ( is_string( $outText ) ) {
5803 # Re-insert stripped tags
5804 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5811 * This function returns the text of a section, specified by a number ($section).
5812 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5813 * the first section before any such heading (section 0).
5815 * If a section contains subsections, these are also returned.
5817 * @param string $text Text to look in
5818 * @param string|int $sectionId Section identifier as a number or string
5819 * (e.g. 0, 1 or 'T-1').
5820 * @param string $defaultText Default to return if section is not found
5822 * @return string Text of the requested section
5824 public function getSection( $text, $sectionId, $defaultText = '' ) {
5825 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5829 * This function returns $oldtext after the content of the section
5830 * specified by $section has been replaced with $text. If the target
5831 * section does not exist, $oldtext is returned unchanged.
5833 * @param string $oldText Former text of the article
5834 * @param string|int $sectionId Section identifier as a number or string
5835 * (e.g. 0, 1 or 'T-1').
5836 * @param string $newText Replacing text
5838 * @return string Modified text
5840 public function replaceSection( $oldText, $sectionId, $newText ) {
5841 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5845 * Get the ID of the revision we are parsing
5849 public function getRevisionId() {
5850 return $this->mRevisionId
;
5854 * Get the revision object for $this->mRevisionId
5856 * @return Revision|null Either a Revision object or null
5857 * @since 1.23 (public since 1.23)
5859 public function getRevisionObject() {
5860 if ( !is_null( $this->mRevisionObject
) ) {
5861 return $this->mRevisionObject
;
5864 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5865 // This is useful when parsing revision that has not yet been saved.
5866 // However, if we get back a saved revision even though we are in
5867 // preview mode, we'll have to ignore it, see below.
5868 // NOTE: This callback may be used to inject an OLD revision that was
5869 // already loaded, so "current" is a bit of a misnomer. We can't just
5870 // skip it if mRevisionId is set.
5871 $rev = call_user_func(
5872 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5875 if ( $this->mRevisionId
=== null && $rev && $rev->getId() ) {
5876 // We are in preview mode (mRevisionId is null), and the current revision callback
5877 // returned an existing revision. Ignore it and return null, it's probably the page's
5878 // current revision, which is not what we want here. Note that we do want to call the
5879 // callback to allow the unsaved revision to be injected here, e.g. for
5880 // self-transclusion previews.
5884 // If the parse is for a new revision, then the callback should have
5885 // already been set to force the object and should match mRevisionId.
5886 // If not, try to fetch by mRevisionId for sanity.
5887 if ( $this->mRevisionId
&& $rev && $rev->getId() != $this->mRevisionId
) {
5888 $rev = Revision
::newFromId( $this->mRevisionId
);
5891 $this->mRevisionObject
= $rev;
5893 return $this->mRevisionObject
;
5897 * Get the timestamp associated with the current revision, adjusted for
5898 * the default server-local timestamp
5901 public function getRevisionTimestamp() {
5902 if ( is_null( $this->mRevisionTimestamp
) ) {
5903 $revObject = $this->getRevisionObject();
5904 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5906 # The cryptic '' timezone parameter tells to use the site-default
5907 # timezone offset instead of the user settings.
5908 # Since this value will be saved into the parser cache, served
5909 # to other users, and potentially even used inside links and such,
5910 # it needs to be consistent for all visitors.
5911 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
5913 return $this->mRevisionTimestamp
;
5917 * Get the name of the user that edited the last revision
5919 * @return string User name
5921 public function getRevisionUser() {
5922 if ( is_null( $this->mRevisionUser
) ) {
5923 $revObject = $this->getRevisionObject();
5925 # if this template is subst: the revision id will be blank,
5926 # so just use the current user's name
5928 $this->mRevisionUser
= $revObject->getUserText();
5929 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5930 $this->mRevisionUser
= $this->getUser()->getName();
5933 return $this->mRevisionUser
;
5937 * Get the size of the revision
5939 * @return int|null Revision size
5941 public function getRevisionSize() {
5942 if ( is_null( $this->mRevisionSize
) ) {
5943 $revObject = $this->getRevisionObject();
5945 # if this variable is subst: the revision id will be blank,
5946 # so just use the parser input size, because the own substituation
5947 # will change the size.
5949 $this->mRevisionSize
= $revObject->getSize();
5951 $this->mRevisionSize
= $this->mInputSize
;
5954 return $this->mRevisionSize
;
5958 * Mutator for $mDefaultSort
5960 * @param string $sort New value
5962 public function setDefaultSort( $sort ) {
5963 $this->mDefaultSort
= $sort;
5964 $this->mOutput
->setProperty( 'defaultsort', $sort );
5968 * Accessor for $mDefaultSort
5969 * Will use the empty string if none is set.
5971 * This value is treated as a prefix, so the
5972 * empty string is equivalent to sorting by
5977 public function getDefaultSort() {
5978 if ( $this->mDefaultSort
!== false ) {
5979 return $this->mDefaultSort
;
5986 * Accessor for $mDefaultSort
5987 * Unlike getDefaultSort(), will return false if none is set
5989 * @return string|bool
5991 public function getCustomDefaultSort() {
5992 return $this->mDefaultSort
;
5995 private static function getSectionNameFromStrippedText( $text ) {
5996 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5997 $text = Sanitizer
::decodeCharReferences( $text );
5998 $text = self
::normalizeSectionName( $text );
6002 private static function makeAnchor( $sectionName ) {
6003 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
6006 private function makeLegacyAnchor( $sectionName ) {
6007 $fragmentMode = $this->siteConfig
->get( 'FragmentMode' );
6008 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
6009 // ForAttribute() and ForLink() are the same for legacy encoding
6010 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
6012 $id = Sanitizer
::escapeIdForLink( $sectionName );
6019 * Try to guess the section anchor name based on a wikitext fragment
6020 * presumably extracted from a heading, for example "Header" from
6023 * @param string $text
6024 * @return string Anchor (starting with '#')
6026 public function guessSectionNameFromWikiText( $text ) {
6027 # Strip out wikitext links(they break the anchor)
6028 $text = $this->stripSectionName( $text );
6029 $sectionName = self
::getSectionNameFromStrippedText( $text );
6030 return self
::makeAnchor( $sectionName );
6034 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6035 * instead, if possible. For use in redirects, since various versions
6036 * of Microsoft browsers interpret Location: headers as something other
6037 * than UTF-8, resulting in breakage.
6039 * @param string $text The section name
6040 * @return string Anchor (starting with '#')
6042 public function guessLegacySectionNameFromWikiText( $text ) {
6043 # Strip out wikitext links(they break the anchor)
6044 $text = $this->stripSectionName( $text );
6045 $sectionName = self
::getSectionNameFromStrippedText( $text );
6046 return $this->makeLegacyAnchor( $sectionName );
6050 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6051 * @param string $text Section name (plain text)
6052 * @return string Anchor (starting with '#')
6054 public static function guessSectionNameFromStrippedText( $text ) {
6055 $sectionName = self
::getSectionNameFromStrippedText( $text );
6056 return self
::makeAnchor( $sectionName );
6060 * Apply the same normalization as code making links to this section would
6062 * @param string $text
6065 private static function normalizeSectionName( $text ) {
6066 # T90902: ensure the same normalization is applied for IDs as to links
6067 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
6070 $parts = $titleParser->splitTitleString( "#$text" );
6071 } catch ( MalformedTitleException
$ex ) {
6074 return $parts['fragment'];
6078 * Strips a text string of wikitext for use in a section anchor
6080 * Accepts a text string and then removes all wikitext from the
6081 * string and leaves only the resultant text (i.e. the result of
6082 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6083 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6084 * to create valid section anchors by mimicing the output of the
6085 * parser when headings are parsed.
6087 * @param string $text Text string to be stripped of wikitext
6088 * for use in a Section anchor
6089 * @return string Filtered text string
6091 public function stripSectionName( $text ) {
6092 # Strip internal link markup
6093 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6094 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6096 # Strip external link markup
6097 # @todo FIXME: Not tolerant to blank link text
6098 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6099 # on how many empty links there are on the page - need to figure that out.
6100 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6102 # Parse wikitext quotes (italics & bold)
6103 $text = $this->doQuotes( $text );
6106 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6111 * strip/replaceVariables/unstrip for preprocessor regression testing
6113 * @param string $text
6114 * @param Title $title
6115 * @param ParserOptions $options
6116 * @param int $outputType
6120 public function testSrvus( $text, Title
$title, ParserOptions
$options,
6121 $outputType = self
::OT_HTML
6123 $magicScopeVariable = $this->lock();
6124 $this->startParse( $title, $options, $outputType, true );
6126 $text = $this->replaceVariables( $text );
6127 $text = $this->mStripState
->unstripBoth( $text );
6128 $text = Sanitizer
::removeHTMLtags( $text );
6133 * @param string $text
6134 * @param Title $title
6135 * @param ParserOptions $options
6138 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6139 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6143 * @param string $text
6144 * @param Title $title
6145 * @param ParserOptions $options
6148 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6149 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6153 * Call a callback function on all regions of the given text that are not
6154 * inside strip markers, and replace those regions with the return value
6155 * of the callback. For example, with input:
6159 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6160 * two strings will be replaced with the value returned by the callback in
6164 * @param callable $callback
6168 public function markerSkipCallback( $s, $callback ) {
6171 while ( $i < strlen( $s ) ) {
6172 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6173 if ( $markerStart === false ) {
6174 $out .= call_user_func( $callback, substr( $s, $i ) );
6177 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6178 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6179 if ( $markerEnd === false ) {
6180 $out .= substr( $s, $markerStart );
6183 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6184 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6193 * Remove any strip markers found in the given text.
6195 * @param string $text
6198 public function killMarkers( $text ) {
6199 return $this->mStripState
->killMarkers( $text );
6203 * Save the parser state required to convert the given half-parsed text to
6204 * HTML. "Half-parsed" in this context means the output of
6205 * recursiveTagParse() or internalParse(). This output has strip markers
6206 * from replaceVariables (extensionSubstitution() etc.), and link
6207 * placeholders from replaceLinkHolders().
6209 * Returns an array which can be serialized and stored persistently. This
6210 * array can later be loaded into another parser instance with
6211 * unserializeHalfParsedText(). The text can then be safely incorporated into
6212 * the return value of a parser hook.
6214 * @deprecated since 1.31
6215 * @param string $text
6219 public function serializeHalfParsedText( $text ) {
6220 wfDeprecated( __METHOD__
, '1.31' );
6223 'version' => self
::HALF_PARSED_VERSION
,
6224 'stripState' => $this->mStripState
->getSubState( $text ),
6225 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6231 * Load the parser state given in the $data array, which is assumed to
6232 * have been generated by serializeHalfParsedText(). The text contents is
6233 * extracted from the array, and its markers are transformed into markers
6234 * appropriate for the current Parser instance. This transformed text is
6235 * returned, and can be safely included in the return value of a parser
6238 * If the $data array has been stored persistently, the caller should first
6239 * check whether it is still valid, by calling isValidHalfParsedText().
6241 * @deprecated since 1.31
6242 * @param array $data Serialized data
6243 * @throws MWException
6246 public function unserializeHalfParsedText( $data ) {
6247 wfDeprecated( __METHOD__
, '1.31' );
6248 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6249 throw new MWException( __METHOD__
. ': invalid version' );
6252 # First, extract the strip state.
6253 $texts = [ $data['text'] ];
6254 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6256 # Now renumber links
6257 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6259 # Should be good to go.
6264 * Returns true if the given array, presumed to be generated by
6265 * serializeHalfParsedText(), is compatible with the current version of the
6268 * @deprecated since 1.31
6269 * @param array $data
6273 public function isValidHalfParsedText( $data ) {
6274 wfDeprecated( __METHOD__
, '1.31' );
6275 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6279 * Parsed a width param of imagelink like 300px or 200x300px
6281 * @param string $value
6282 * @param bool $parseHeight
6287 public static function parseWidthParam( $value, $parseHeight = true ) {
6288 $parsedWidthParam = [];
6289 if ( $value === '' ) {
6290 return $parsedWidthParam;
6293 # (T15500) In both cases (width/height and width only),
6294 # permit trailing "px" for backward compatibility.
6295 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6296 $width = intval( $m[1] );
6297 $height = intval( $m[2] );
6298 $parsedWidthParam['width'] = $width;
6299 $parsedWidthParam['height'] = $height;
6300 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6301 $width = intval( $value );
6302 $parsedWidthParam['width'] = $width;
6304 return $parsedWidthParam;
6308 * Lock the current instance of the parser.
6310 * This is meant to stop someone from calling the parser
6311 * recursively and messing up all the strip state.
6313 * @throws MWException If parser is in a parse
6314 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6316 protected function lock() {
6317 if ( $this->mInParse
) {
6318 throw new MWException( "Parser state cleared while parsing. "
6319 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6322 // Save the backtrace when locking, so that if some code tries locking again,
6323 // we can print the lock owner's backtrace for easier debugging
6325 $this->mInParse
= $e->getTraceAsString();
6327 $recursiveCheck = new ScopedCallback( function () {
6328 $this->mInParse
= false;
6331 return $recursiveCheck;
6335 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6337 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6338 * or if there is more than one <p/> tag in the input HTML.
6340 * @param string $html
6344 public static function stripOuterParagraph( $html ) {
6346 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '</p>' ) === false ) {
6354 * Return this parser if it is not doing anything, otherwise
6355 * get a fresh parser. You can use this method by doing
6356 * $myParser = $wgParser->getFreshParser(), or more simply
6357 * $wgParser->getFreshParser()->parse( ... );
6358 * if you're unsure if $wgParser is safe to use.
6361 * @return Parser A parser object that is not parsing anything
6363 public function getFreshParser() {
6364 if ( $this->mInParse
) {
6365 return $this->factory
->create();
6372 * Set's up the PHP implementation of OOUI for use in this request
6373 * and instructs OutputPage to enable OOUI for itself.
6377 public function enableOOUI() {
6378 OutputPage
::setupOOUI();
6379 $this->mOutput
->setEnableOOUI( true );