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\Config\ServiceOptions
;
24 use MediaWiki\Linker\LinkRenderer
;
25 use MediaWiki\Linker\LinkRendererFactory
;
26 use MediaWiki\Linker\LinkTarget
;
27 use MediaWiki\MediaWikiServices
;
28 use MediaWiki\Special\SpecialPageFactory
;
29 use Wikimedia\ScopedCallback
;
32 * @defgroup Parser Parser
36 * PHP Parser - Processes wiki markup (which uses a more user-friendly
37 * syntax, such as "[[link]]" for making links), and provides a one-way
38 * transformation of that wiki markup it into (X)HTML output / markup
39 * (which in turn the browser understands, and can display).
41 * There are seven main entry points into the Parser class:
44 * produces HTML output
45 * - Parser::preSaveTransform()
46 * produces altered wiki markup
47 * - Parser::preprocess()
48 * removes HTML comments and expands templates
49 * - Parser::cleanSig() and Parser::cleanSigInSig()
50 * cleans a signature before saving it to preferences
51 * - Parser::getSection()
52 * return the content of a section from an article for section editing
53 * - Parser::replaceSection()
54 * replaces a section by number inside an article
55 * - Parser::getPreloadText()
56 * removes <noinclude> sections and <includeonly> tags
58 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
61 * $wgNamespacesWithSubpages
63 * @par Settings only within ParserOptions:
64 * $wgAllowExternalImages
65 * $wgAllowSpecialInclusion
73 * Update this version number when the ParserOutput format
74 * changes in an incompatible way, so the parser cache
75 * can automatically discard old data.
77 const VERSION
= '1.6.4';
80 * Update this version number when the output of serialiseHalfParsedText()
81 * changes in an incompatible way
83 const HALF_PARSED_VERSION
= 2;
85 # Flags for Parser::setFunctionHook
86 const SFH_NO_HASH
= 1;
87 const SFH_OBJECT_ARGS
= 2;
89 # Constants needed for external link processing
90 # Everything except bracket, space, or control characters
91 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
92 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
93 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
94 # uses to replace invalid HTML characters.
95 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
96 # Simplified expression to match an IPv4 or IPv6 address, or
97 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
98 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
99 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
100 // phpcs:ignore Generic.Files.LineLength
101 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
102 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
104 # Regular expression for a non-newline space
105 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
107 # Flags for preprocessToDom
108 const PTD_FOR_INCLUSION
= 1;
110 # Allowed values for $this->mOutputType
111 # Parameter to startExternalParse().
112 const OT_HTML
= 1; # like parse()
113 const OT_WIKI
= 2; # like preSaveTransform()
114 const OT_PREPROCESS
= 3; # like preprocess()
116 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
119 * @var string Prefix and suffix for temporary replacement strings
120 * for the multipass parser.
122 * \x7f should never appear in input as it's disallowed in XML.
123 * Using it at the front also gives us a little extra robustness
124 * since it shouldn't match when butted up against identifier-like
127 * Must not consist of all title characters, or else it will change
128 * the behavior of <nowiki> in a link.
130 * Must have a character that needs escaping in attributes, otherwise
131 * someone could put a strip marker in an attribute, to get around
132 * escaping quote marks, and break out of the attribute. Thus we add
135 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
136 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
138 # Markers used for wrapping the table of contents
139 const TOC_START
= '<mw:toc>';
140 const TOC_END
= '</mw:toc>';
142 /** @var int Assume that no output will later be saved this many seconds after parsing */
146 public $mTagHooks = [];
147 public $mTransparentTagHooks = [];
148 public $mFunctionHooks = [];
149 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
150 public $mFunctionTagHooks = [];
151 public $mStripList = [];
152 public $mDefaultStripList = [];
153 public $mVarCache = [];
154 public $mImageParams = [];
155 public $mImageParamsMagicArray = [];
156 public $mMarkerIndex = 0;
158 * @var bool Whether firstCallInit still needs to be called
160 public $mFirstCall = true;
162 # Initialised by initialiseVariables()
165 * @var MagicWordArray
170 * @var MagicWordArray
175 * @deprecated since 1.34, there should be no need to use this
180 # Initialised in constructor
181 public $mExtLinkBracketedRegex, $mUrlProtocols;
183 # Initialized in getPreprocessor()
184 /** @var Preprocessor */
185 public $mPreprocessor;
187 # Cleared with clearState():
199 public $mIncludeCount;
201 * @var LinkHolderArray
203 public $mLinkHolders;
206 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
207 public $mDefaultSort;
208 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
209 public $mExpensiveFunctionCount; # number of expensive parser function calls
210 public $mShowToc, $mForceTocPosition;
215 public $mUser; # User object; only used when doing pre-save transform
218 # These are variables reset at least once per parse regardless of $clearState
228 public $mTitle; # Title context, used for self-link rendering and similar things
229 public $mOutputType; # Output type, one of the OT_xxx constants
230 public $ot; # Shortcut alias, see setOutputType()
231 public $mRevisionObject; # The revision object of the specified revision ID
232 public $mRevisionId; # ID to display in {{REVISIONID}} tags
233 public $mRevisionTimestamp; # The timestamp of the specified revision ID
234 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
235 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
236 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
237 public $mInputSize = false; # For {{PAGESIZE}} on current page.
240 * @var array Array with the language name of each language link (i.e. the
241 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
242 * duplicate language links to the ParserOutput.
244 public $mLangLinkLanguages;
247 * @var MapCacheLRU|null
250 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
252 public $currentRevisionCache;
255 * @var bool|string Recursive call protection.
256 * This variable should be treated as if it were private.
258 public $mInParse = false;
260 /** @var SectionProfiler */
261 protected $mProfiler;
266 protected $mLinkRenderer;
268 /** @var MagicWordFactory */
269 private $magicWordFactory;
274 /** @var ParserFactory */
277 /** @var SpecialPageFactory */
278 private $specialPageFactory;
281 * This is called $svcOptions instead of $options like elsewhere to avoid confusion with
282 * $mOptions, which is public and widely used, and also with the local variable $options used
283 * for ParserOptions throughout this file.
285 * @var ServiceOptions
289 /** @var LinkRendererFactory */
290 private $linkRendererFactory;
292 /** @var NamespaceInfo */
296 * TODO Make this a const when HHVM support is dropped (T192166)
301 public static $constructorOptions = [
302 // See $wgParserConf documentation
305 // See documentation for the corresponding config options
307 'EnableScaryTranscluding',
308 'ExtraInterlanguageLinkPrefixes',
320 'TranscludeCacheExpiry',
324 * Constructing parsers directly is deprecated! Use a ParserFactory.
326 * @param ServiceOptions|null $svcOptions
327 * @param MagicWordFactory|null $magicWordFactory
328 * @param Language|null $contLang Content language
329 * @param ParserFactory|null $factory
330 * @param string|null $urlProtocols As returned from wfUrlProtocols()
331 * @param SpecialPageFactory|null $spFactory
332 * @param LinkRendererFactory|null $linkRendererFactory
333 * @param NamespaceInfo|null $nsInfo
335 public function __construct(
336 $svcOptions = null, MagicWordFactory
$magicWordFactory = null,
337 Language
$contLang = null, ParserFactory
$factory = null, $urlProtocols = null,
338 SpecialPageFactory
$spFactory = null, $linkRendererFactory = null, $nsInfo = null
340 $services = MediaWikiServices
::getInstance();
341 if ( !$svcOptions ||
is_array( $svcOptions ) ) {
342 // Pre-1.34 calling convention is the first parameter is just ParserConf, the seventh is
343 // Config, and the eighth is LinkRendererFactory.
344 $this->mConf
= (array)$svcOptions;
345 if ( empty( $this->mConf
['class'] ) ) {
346 $this->mConf
['class'] = self
::class;
348 if ( empty( $this->mConf
['preprocessorClass'] ) ) {
349 $this->mConf
['preprocessorClass'] = self
::getDefaultPreprocessorClass();
351 $this->svcOptions
= new ServiceOptions( self
::$constructorOptions,
353 func_num_args() > 6 ?
func_get_arg( 6 ) : $services->getMainConfig()
355 $linkRendererFactory = func_num_args() > 7 ?
func_get_arg( 7 ) : null;
356 $nsInfo = func_num_args() > 8 ?
func_get_arg( 8 ) : null;
358 // New calling convention
359 $svcOptions->assertRequiredOptions( self
::$constructorOptions );
360 // $this->mConf is public, so we'll keep those two options there as well for
361 // compatibility until it's removed
363 'class' => $svcOptions->get( 'class' ),
364 'preprocessorClass' => $svcOptions->get( 'preprocessorClass' ),
366 $this->svcOptions
= $svcOptions;
369 $this->mUrlProtocols
= $urlProtocols ??
wfUrlProtocols();
370 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
371 self
::EXT_LINK_ADDR
.
372 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
374 $this->magicWordFactory
= $magicWordFactory ??
375 $services->getMagicWordFactory();
377 $this->contLang
= $contLang ??
$services->getContentLanguage();
379 $this->factory
= $factory ??
$services->getParserFactory();
380 $this->specialPageFactory
= $spFactory ??
$services->getSpecialPageFactory();
381 $this->linkRendererFactory
= $linkRendererFactory ??
$services->getLinkRendererFactory();
382 $this->nsInfo
= $nsInfo ??
$services->getNamespaceInfo();
386 * Reduce memory usage to reduce the impact of circular references
388 public function __destruct() {
389 if ( isset( $this->mLinkHolders
) ) {
390 unset( $this->mLinkHolders
);
392 foreach ( $this as $name => $value ) {
393 unset( $this->$name );
398 * Allow extensions to clean up when the parser is cloned
400 public function __clone() {
401 $this->mInParse
= false;
403 // T58226: When you create a reference "to" an object field, that
404 // makes the object field itself be a reference too (until the other
405 // reference goes out of scope). When cloning, any field that's a
406 // reference is copied as a reference in the new object. Both of these
407 // are defined PHP5 behaviors, as inconvenient as it is for us when old
408 // hooks from PHP4 days are passing fields by reference.
409 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
410 // Make a non-reference copy of the field, then rebind the field to
411 // reference the new copy.
417 Hooks
::run( 'ParserCloned', [ $this ] );
421 * Which class should we use for the preprocessor if not otherwise specified?
424 * @deprecated since 1.34, removing configurability of preprocessor
427 public static function getDefaultPreprocessorClass() {
428 return Preprocessor_Hash
::class;
432 * Do various kinds of initialisation on the first call of the parser
434 public function firstCallInit() {
435 if ( !$this->mFirstCall
) {
438 $this->mFirstCall
= false;
440 CoreParserFunctions
::register( $this );
441 CoreTagHooks
::register( $this );
442 $this->initialiseVariables();
444 // Avoid PHP 7.1 warning from passing $this by reference
446 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
454 public function clearState() {
455 $this->firstCallInit();
456 $this->mOutput
= new ParserOutput
;
457 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
458 $this->mAutonumber
= 0;
459 $this->mIncludeCount
= [];
460 $this->mLinkHolders
= new LinkHolderArray( $this );
462 $this->mRevisionObject
= $this->mRevisionTimestamp
=
463 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
464 $this->mVarCache
= [];
466 $this->mLangLinkLanguages
= [];
467 $this->currentRevisionCache
= null;
469 $this->mStripState
= new StripState( $this );
471 # Clear these on every parse, T6549
472 $this->mTplRedirCache
= $this->mTplDomCache
= [];
474 $this->mShowToc
= true;
475 $this->mForceTocPosition
= false;
476 $this->mIncludeSizes
= [
480 $this->mPPNodeCount
= 0;
481 $this->mGeneratedPPNodeCount
= 0;
482 $this->mHighestExpansionDepth
= 0;
483 $this->mDefaultSort
= false;
484 $this->mHeadings
= [];
485 $this->mDoubleUnderscores
= [];
486 $this->mExpensiveFunctionCount
= 0;
489 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
490 $this->mPreprocessor
= null;
493 $this->mProfiler
= new SectionProfiler();
495 // Avoid PHP 7.1 warning from passing $this by reference
497 Hooks
::run( 'ParserClearState', [ &$parser ] );
501 * Convert wikitext to HTML
502 * Do not call this function recursively.
504 * @param string $text Text we want to parse
505 * @param-taint $text escapes_htmlnoent
506 * @param Title $title
507 * @param ParserOptions $options
508 * @param bool $linestart
509 * @param bool $clearState
510 * @param int|null $revid Number to pass in {{REVISIONID}}
511 * @return ParserOutput A ParserOutput
512 * @return-taint escaped
514 public function parse(
515 $text, Title
$title, ParserOptions
$options,
516 $linestart = true, $clearState = true, $revid = null
519 // We use U+007F DELETE to construct strip markers, so we have to make
520 // sure that this character does not occur in the input text.
521 $text = strtr( $text, "\x7f", "?" );
522 $magicScopeVariable = $this->lock();
524 // Strip U+0000 NULL (T159174)
525 $text = str_replace( "\000", '', $text );
527 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
529 $this->currentRevisionCache
= null;
530 $this->mInputSize
= strlen( $text );
531 if ( $this->mOptions
->getEnableLimitReport() ) {
532 $this->mOutput
->resetParseStartTime();
535 $oldRevisionId = $this->mRevisionId
;
536 $oldRevisionObject = $this->mRevisionObject
;
537 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
538 $oldRevisionUser = $this->mRevisionUser
;
539 $oldRevisionSize = $this->mRevisionSize
;
540 if ( $revid !== null ) {
541 $this->mRevisionId
= $revid;
542 $this->mRevisionObject
= null;
543 $this->mRevisionTimestamp
= null;
544 $this->mRevisionUser
= null;
545 $this->mRevisionSize
= null;
548 // Avoid PHP 7.1 warning from passing $this by reference
550 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
552 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
553 $text = $this->internalParse( $text );
554 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
556 $text = $this->internalParseHalfParsed( $text, true, $linestart );
559 * A converted title will be provided in the output object if title and
560 * content conversion are enabled, the article text does not contain
561 * a conversion-suppressing double-underscore tag, and no
562 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
563 * automatic link conversion.
565 if ( !( $options->getDisableTitleConversion()
566 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
567 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
568 ||
$this->mOutput
->getDisplayTitle() !== false )
570 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
571 if ( $convruletitle ) {
572 $this->mOutput
->setTitleText( $convruletitle );
574 $titleText = $this->getTargetLanguage()->convertTitle( $title );
575 $this->mOutput
->setTitleText( $titleText );
579 # Compute runtime adaptive expiry if set
580 $this->mOutput
->finalizeAdaptiveCacheExpiry();
582 # Warn if too many heavyweight parser functions were used
583 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
584 $this->limitationWarn( 'expensive-parserfunction',
585 $this->mExpensiveFunctionCount
,
586 $this->mOptions
->getExpensiveParserFunctionLimit()
590 # Information on limits, for the benefit of users who try to skirt them
591 if ( $this->mOptions
->getEnableLimitReport() ) {
592 $text .= $this->makeLimitReport();
595 # Wrap non-interface parser output in a <div> so it can be targeted
597 $class = $this->mOptions
->getWrapOutputClass();
598 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
599 $this->mOutput
->addWrapperDivClass( $class );
602 $this->mOutput
->setText( $text );
604 $this->mRevisionId
= $oldRevisionId;
605 $this->mRevisionObject
= $oldRevisionObject;
606 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
607 $this->mRevisionUser
= $oldRevisionUser;
608 $this->mRevisionSize
= $oldRevisionSize;
609 $this->mInputSize
= false;
610 $this->currentRevisionCache
= null;
612 return $this->mOutput
;
616 * Set the limit report data in the current ParserOutput, and return the
617 * limit report HTML comment.
621 protected function makeLimitReport() {
622 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
624 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
625 if ( $cpuTime !== null ) {
626 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
627 sprintf( "%.3f", $cpuTime )
631 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
632 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
633 sprintf( "%.3f", $wallTime )
636 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
637 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
639 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
640 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
642 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
643 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
645 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
646 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
648 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
649 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
651 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
652 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
655 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
656 $this->mOutput
->setLimitReportData( $key, $value );
659 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
661 $limitReport = "NewPP limit report\n";
662 if ( $this->svcOptions
->get( 'ShowHostnames' ) ) {
663 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
665 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
666 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
667 $limitReport .= 'Dynamic content: ' .
668 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
670 $limitReport .= 'Complications: [' . implode( ', ', $this->mOutput
->getAllFlags() ) . "]\n";
672 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
673 if ( Hooks
::run( 'ParserLimitReportFormat',
674 [ $key, &$value, &$limitReport, false, false ]
676 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
677 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
678 ->inLanguage( 'en' )->useDatabase( false );
679 if ( !$valueMsg->exists() ) {
680 $valueMsg = new RawMessage( '$1' );
682 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
683 $valueMsg->params( $value );
684 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
688 // Since we're not really outputting HTML, decode the entities and
689 // then re-encode the things that need hiding inside HTML comments.
690 $limitReport = htmlspecialchars_decode( $limitReport );
692 // Sanitize for comment. Note '‐' in the replacement is U+2010,
693 // which looks much like the problematic '-'.
694 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
695 $text = "\n<!-- \n$limitReport-->\n";
697 // Add on template profiling data in human/machine readable way
698 $dataByFunc = $this->mProfiler
->getFunctionStats();
699 uasort( $dataByFunc, function ( $a, $b ) {
700 return $b['real'] <=> $a['real']; // descending order
703 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
704 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
705 $item['%real'], $item['real'], $item['calls'],
706 htmlspecialchars( $item['name'] ) );
708 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
709 $text .= implode( "\n", $profileReport ) . "\n-->\n";
711 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
713 // Add other cache related metadata
714 if ( $this->svcOptions
->get( 'ShowHostnames' ) ) {
715 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
717 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
718 $this->mOutput
->getCacheTime() );
719 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
720 $this->mOutput
->getCacheExpiry() );
721 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
722 $this->mOutput
->hasDynamicContent() );
724 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
725 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
726 $this->mTitle
->getPrefixedDBkey() );
732 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
733 * can be called from an extension tag hook.
735 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
736 * instead, which means that lists and links have not been fully parsed yet,
737 * and strip markers are still present.
739 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
741 * Use this function if you're a parser tag hook and you want to parse
742 * wikitext before or after applying additional transformations, and you
743 * intend to *return the result as hook output*, which will cause it to go
744 * through the rest of parsing process automatically.
746 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
747 * $text are not expanded
749 * @param string $text Text extension wants to have parsed
750 * @param-taint $text escapes_htmlnoent
751 * @param bool|PPFrame $frame The frame to use for expanding any template variables
752 * @return string UNSAFE half-parsed HTML
753 * @return-taint escaped
755 public function recursiveTagParse( $text, $frame = false ) {
756 // Avoid PHP 7.1 warning from passing $this by reference
758 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
759 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
760 $text = $this->internalParse( $text, false, $frame );
765 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
766 * point can be called from an extension tag hook.
768 * The output of this function is fully-parsed HTML that is safe for output.
769 * If you're a parser tag hook, you might want to use recursiveTagParse()
772 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
773 * $text are not expanded
777 * @param string $text Text extension wants to have parsed
778 * @param-taint $text escapes_htmlnoent
779 * @param bool|PPFrame $frame The frame to use for expanding any template variables
780 * @return string Fully parsed HTML
781 * @return-taint escaped
783 public function recursiveTagParseFully( $text, $frame = false ) {
784 $text = $this->recursiveTagParse( $text, $frame );
785 $text = $this->internalParseHalfParsed( $text, false );
790 * Expand templates and variables in the text, producing valid, static wikitext.
791 * Also removes comments.
792 * Do not call this function recursively.
793 * @param string $text
794 * @param Title|null $title
795 * @param ParserOptions $options
796 * @param int|null $revid
797 * @param bool|PPFrame $frame
798 * @return mixed|string
800 public function preprocess( $text, Title
$title = null,
801 ParserOptions
$options, $revid = null, $frame = false
803 $magicScopeVariable = $this->lock();
804 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
805 if ( $revid !== null ) {
806 $this->mRevisionId
= $revid;
808 // Avoid PHP 7.1 warning from passing $this by reference
810 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
811 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
812 $text = $this->replaceVariables( $text, $frame );
813 $text = $this->mStripState
->unstripBoth( $text );
818 * Recursive parser entry point that can be called from an extension tag
821 * @param string $text Text to be expanded
822 * @param bool|PPFrame $frame The frame to use for expanding any template variables
826 public function recursivePreprocess( $text, $frame = false ) {
827 $text = $this->replaceVariables( $text, $frame );
828 $text = $this->mStripState
->unstripBoth( $text );
833 * Process the wikitext for the "?preload=" feature. (T7210)
835 * "<noinclude>", "<includeonly>" etc. are parsed as for template
836 * transclusion, comments, templates, arguments, tags hooks and parser
837 * functions are untouched.
839 * @param string $text
840 * @param Title $title
841 * @param ParserOptions $options
842 * @param array $params
845 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
846 $msg = new RawMessage( $text );
847 $text = $msg->params( $params )->plain();
849 # Parser (re)initialisation
850 $magicScopeVariable = $this->lock();
851 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
853 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
854 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
855 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
856 $text = $this->mStripState
->unstripBoth( $text );
861 * Set the current user.
862 * Should only be used when doing pre-save transform.
864 * @param User|null $user User object or null (to reset)
866 public function setUser( $user ) {
867 $this->mUser
= $user;
871 * Set the context title
875 public function setTitle( $t ) {
877 $t = Title
::newFromText( 'NO TITLE' );
880 if ( $t->hasFragment() ) {
881 # Strip the fragment to avoid various odd effects
882 $this->mTitle
= $t->createFragmentTarget( '' );
889 * Accessor for the Title object
893 public function getTitle() {
894 return $this->mTitle
;
898 * Accessor/mutator for the Title object
900 * @param Title|null $x Title object or null to just get the current one
903 public function Title( $x = null ) {
904 return wfSetVar( $this->mTitle
, $x );
908 * Set the output type
910 * @param int $ot New value
912 public function setOutputType( $ot ) {
913 $this->mOutputType
= $ot;
916 'html' => $ot == self
::OT_HTML
,
917 'wiki' => $ot == self
::OT_WIKI
,
918 'pre' => $ot == self
::OT_PREPROCESS
,
919 'plain' => $ot == self
::OT_PLAIN
,
924 * Accessor/mutator for the output type
926 * @param int|null $x New value or null to just get the current one
929 public function OutputType( $x = null ) {
930 return wfSetVar( $this->mOutputType
, $x );
934 * Get the ParserOutput object
936 * @return ParserOutput
938 public function getOutput() {
939 return $this->mOutput
;
943 * Get the ParserOptions object
945 * @return ParserOptions
947 public function getOptions() {
948 return $this->mOptions
;
952 * Accessor/mutator for the ParserOptions object
954 * @param ParserOptions|null $x New value or null to just get the current one
955 * @return ParserOptions Current ParserOptions object
957 public function Options( $x = null ) {
958 return wfSetVar( $this->mOptions
, $x );
964 public function nextLinkID() {
965 return $this->mLinkID++
;
971 public function setLinkID( $id ) {
972 $this->mLinkID
= $id;
976 * Get a language object for use in parser functions such as {{FORMATNUM:}}
979 public function getFunctionLang() {
980 return $this->getTargetLanguage();
984 * Get the target language for the content being parsed. This is usually the
985 * language that the content is in.
989 * @throws MWException
992 public function getTargetLanguage() {
993 $target = $this->mOptions
->getTargetLanguage();
995 if ( $target !== null ) {
997 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
998 return $this->mOptions
->getUserLangObj();
999 } elseif ( is_null( $this->mTitle
) ) {
1000 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
1003 return $this->mTitle
->getPageLanguage();
1007 * Get the language object for language conversion
1008 * @deprecated since 1.32, just use getTargetLanguage()
1009 * @return Language|null
1011 public function getConverterLanguage() {
1012 return $this->getTargetLanguage();
1016 * Get a User object either from $this->mUser, if set, or from the
1017 * ParserOptions object otherwise
1021 public function getUser() {
1022 if ( !is_null( $this->mUser
) ) {
1023 return $this->mUser
;
1025 return $this->mOptions
->getUser();
1029 * Get a preprocessor object
1031 * @return Preprocessor
1033 public function getPreprocessor() {
1034 if ( !isset( $this->mPreprocessor
) ) {
1035 $class = $this->svcOptions
->get( 'preprocessorClass' );
1036 $this->mPreprocessor
= new $class( $this );
1038 return $this->mPreprocessor
;
1042 * Get a LinkRenderer instance to make links with
1045 * @return LinkRenderer
1047 public function getLinkRenderer() {
1048 // XXX We make the LinkRenderer with current options and then cache it forever
1049 if ( !$this->mLinkRenderer
) {
1050 $this->mLinkRenderer
= $this->linkRendererFactory
->create();
1051 $this->mLinkRenderer
->setStubThreshold(
1052 $this->getOptions()->getStubThreshold()
1056 return $this->mLinkRenderer
;
1060 * Get the MagicWordFactory that this Parser is using
1063 * @return MagicWordFactory
1065 public function getMagicWordFactory() {
1066 return $this->magicWordFactory
;
1070 * Get the content language that this Parser is using
1075 public function getContentLanguage() {
1076 return $this->contLang
;
1080 * Replaces all occurrences of HTML-style comments and the given tags
1081 * in the text with a random marker and returns the next text. The output
1082 * parameter $matches will be an associative array filled with data in
1089 * [ 'param' => 'x' ],
1090 * '<element param="x">tag content</element>' ]
1093 * @param array $elements List of element names. Comments are always extracted.
1094 * @param string $text Source text string.
1095 * @param array &$matches Out parameter, Array: extracted tags
1096 * @return string Stripped text
1098 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1103 $taglist = implode( '|', $elements );
1104 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
1106 while ( $text != '' ) {
1107 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1109 if ( count( $p ) < 5 ) {
1112 if ( count( $p ) > 5 ) {
1120 list( , $element, $attributes, $close, $inside ) = $p;
1123 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1124 $stripped .= $marker;
1126 if ( $close === '/>' ) {
1127 # Empty element tag, <tag />
1132 if ( $element === '!--' ) {
1135 $end = "/(<\\/$element\\s*>)/i";
1137 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1139 if ( count( $q ) < 3 ) {
1140 # No end tag -- let it run out to the end of the text.
1144 list( , $tail, $text ) = $q;
1148 $matches[$marker] = [ $element,
1150 Sanitizer
::decodeTagAttributes( $attributes ),
1151 "<$element$attributes$close$content$tail" ];
1157 * Get a list of strippable XML-like elements
1161 public function getStripList() {
1162 return $this->mStripList
;
1166 * Add an item to the strip state
1167 * Returns the unique tag which must be inserted into the stripped text
1168 * The tag will be replaced with the original text in unstrip()
1170 * @param string $text
1174 public function insertStripItem( $text ) {
1175 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1176 $this->mMarkerIndex++
;
1177 $this->mStripState
->addGeneral( $marker, $text );
1182 * parse the wiki syntax used to render tables
1185 * @param string $text
1188 public function doTableStuff( $text ) {
1189 $lines = StringUtils
::explode( "\n", $text );
1191 $td_history = []; # Is currently a td tag open?
1192 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1193 $tr_history = []; # Is currently a tr tag open?
1194 $tr_attributes = []; # history of tr attributes
1195 $has_opened_tr = []; # Did this table open a <tr> element?
1196 $indent_level = 0; # indent level of the table
1198 foreach ( $lines as $outLine ) {
1199 $line = trim( $outLine );
1201 if ( $line === '' ) { # empty line, go to next line
1202 $out .= $outLine . "\n";
1206 $first_character = $line[0];
1207 $first_two = substr( $line, 0, 2 );
1210 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1211 # First check if we are starting a new table
1212 $indent_level = strlen( $matches[1] );
1214 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1215 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1217 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1218 array_push( $td_history, false );
1219 array_push( $last_tag_history, '' );
1220 array_push( $tr_history, false );
1221 array_push( $tr_attributes, '' );
1222 array_push( $has_opened_tr, false );
1223 } elseif ( count( $td_history ) == 0 ) {
1224 # Don't do any of the following
1225 $out .= $outLine . "\n";
1227 } elseif ( $first_two === '|}' ) {
1228 # We are ending a table
1229 $line = '</table>' . substr( $line, 2 );
1230 $last_tag = array_pop( $last_tag_history );
1232 if ( !array_pop( $has_opened_tr ) ) {
1233 $line = "<tr><td></td></tr>{$line}";
1236 if ( array_pop( $tr_history ) ) {
1237 $line = "</tr>{$line}";
1240 if ( array_pop( $td_history ) ) {
1241 $line = "</{$last_tag}>{$line}";
1243 array_pop( $tr_attributes );
1244 if ( $indent_level > 0 ) {
1245 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1249 } elseif ( $first_two === '|-' ) {
1250 # Now we have a table row
1251 $line = preg_replace( '#^\|-+#', '', $line );
1253 # Whats after the tag is now only attributes
1254 $attributes = $this->mStripState
->unstripBoth( $line );
1255 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1256 array_pop( $tr_attributes );
1257 array_push( $tr_attributes, $attributes );
1260 $last_tag = array_pop( $last_tag_history );
1261 array_pop( $has_opened_tr );
1262 array_push( $has_opened_tr, true );
1264 if ( array_pop( $tr_history ) ) {
1268 if ( array_pop( $td_history ) ) {
1269 $line = "</{$last_tag}>{$line}";
1273 array_push( $tr_history, false );
1274 array_push( $td_history, false );
1275 array_push( $last_tag_history, '' );
1276 } elseif ( $first_character === '|'
1277 ||
$first_character === '!'
1278 ||
$first_two === '|+'
1280 # This might be cell elements, td, th or captions
1281 if ( $first_two === '|+' ) {
1282 $first_character = '+';
1283 $line = substr( $line, 2 );
1285 $line = substr( $line, 1 );
1288 // Implies both are valid for table headings.
1289 if ( $first_character === '!' ) {
1290 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1293 # Split up multiple cells on the same line.
1294 # FIXME : This can result in improper nesting of tags processed
1295 # by earlier parser steps.
1296 $cells = explode( '||', $line );
1300 # Loop through each table cell
1301 foreach ( $cells as $cell ) {
1303 if ( $first_character !== '+' ) {
1304 $tr_after = array_pop( $tr_attributes );
1305 if ( !array_pop( $tr_history ) ) {
1306 $previous = "<tr{$tr_after}>\n";
1308 array_push( $tr_history, true );
1309 array_push( $tr_attributes, '' );
1310 array_pop( $has_opened_tr );
1311 array_push( $has_opened_tr, true );
1314 $last_tag = array_pop( $last_tag_history );
1316 if ( array_pop( $td_history ) ) {
1317 $previous = "</{$last_tag}>\n{$previous}";
1320 if ( $first_character === '|' ) {
1322 } elseif ( $first_character === '!' ) {
1324 } elseif ( $first_character === '+' ) {
1325 $last_tag = 'caption';
1330 array_push( $last_tag_history, $last_tag );
1332 # A cell could contain both parameters and data
1333 $cell_data = explode( '|', $cell, 2 );
1335 # T2553: Note that a '|' inside an invalid link should not
1336 # be mistaken as delimiting cell parameters
1337 # Bug T153140: Neither should language converter markup.
1338 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1339 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1340 } elseif ( count( $cell_data ) == 1 ) {
1341 // Whitespace in cells is trimmed
1342 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1344 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1345 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1346 // Whitespace in cells is trimmed
1347 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1351 array_push( $td_history, true );
1354 $out .= $outLine . "\n";
1357 # Closing open td, tr && table
1358 while ( count( $td_history ) > 0 ) {
1359 if ( array_pop( $td_history ) ) {
1362 if ( array_pop( $tr_history ) ) {
1365 if ( !array_pop( $has_opened_tr ) ) {
1366 $out .= "<tr><td></td></tr>\n";
1369 $out .= "</table>\n";
1372 # Remove trailing line-ending (b/c)
1373 if ( substr( $out, -1 ) === "\n" ) {
1374 $out = substr( $out, 0, -1 );
1377 # special case: don't return empty table
1378 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1386 * Helper function for parse() that transforms wiki markup into half-parsed
1387 * HTML. Only called for $mOutputType == self::OT_HTML.
1391 * @param string $text The text to parse
1392 * @param-taint $text escapes_html
1393 * @param bool $isMain Whether this is being called from the main parse() function
1394 * @param PPFrame|bool $frame A pre-processor frame
1398 public function internalParse( $text, $isMain = true, $frame = false ) {
1401 // Avoid PHP 7.1 warning from passing $this by reference
1404 # Hook to suspend the parser in this state
1405 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1409 # if $frame is provided, then use $frame for replacing any variables
1411 # use frame depth to infer how include/noinclude tags should be handled
1412 # depth=0 means this is the top-level document; otherwise it's an included document
1413 if ( !$frame->depth
) {
1416 $flag = self
::PTD_FOR_INCLUSION
;
1418 $dom = $this->preprocessToDom( $text, $flag );
1419 $text = $frame->expand( $dom );
1421 # if $frame is not provided, then use old-style replaceVariables
1422 $text = $this->replaceVariables( $text );
1425 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1426 $text = Sanitizer
::removeHTMLtags(
1428 [ $this, 'attributeStripCallback' ],
1430 array_keys( $this->mTransparentTagHooks
),
1432 [ $this, 'addTrackingCategory' ]
1434 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1436 # Tables need to come after variable replacement for things to work
1437 # properly; putting them before other transformations should keep
1438 # exciting things like link expansions from showing up in surprising
1440 $text = $this->doTableStuff( $text );
1442 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1444 $text = $this->doDoubleUnderscore( $text );
1446 $text = $this->doHeadings( $text );
1447 $text = $this->replaceInternalLinks( $text );
1448 $text = $this->doAllQuotes( $text );
1449 $text = $this->replaceExternalLinks( $text );
1451 # replaceInternalLinks may sometimes leave behind
1452 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1453 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1455 $text = $this->doMagicLinks( $text );
1456 $text = $this->formatHeadings( $text, $origText, $isMain );
1462 * Helper function for parse() that transforms half-parsed HTML into fully
1465 * @param string $text
1466 * @param bool $isMain
1467 * @param bool $linestart
1470 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1471 $text = $this->mStripState
->unstripGeneral( $text );
1473 // Avoid PHP 7.1 warning from passing $this by reference
1477 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1480 # Clean up special characters, only run once, next-to-last before doBlockLevels
1481 $text = Sanitizer
::armorFrenchSpaces( $text );
1483 $text = $this->doBlockLevels( $text, $linestart );
1485 $this->replaceLinkHolders( $text );
1488 * The input doesn't get language converted if
1490 * b) Content isn't converted
1491 * c) It's a conversion table
1492 * d) it is an interface message (which is in the user language)
1494 if ( !( $this->mOptions
->getDisableContentConversion()
1495 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1496 && !$this->mOptions
->getInterfaceMessage()
1498 # The position of the convert() call should not be changed. it
1499 # assumes that the links are all replaced and the only thing left
1500 # is the <nowiki> mark.
1501 $text = $this->getTargetLanguage()->convert( $text );
1504 $text = $this->mStripState
->unstripNoWiki( $text );
1507 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1510 $text = $this->replaceTransparentTags( $text );
1511 $text = $this->mStripState
->unstripGeneral( $text );
1513 $text = Sanitizer
::normalizeCharReferences( $text );
1515 if ( MWTidy
::isEnabled() ) {
1516 if ( $this->mOptions
->getTidy() ) {
1517 $text = MWTidy
::tidy( $text );
1520 # attempt to sanitize at least some nesting problems
1521 # (T4702 and quite a few others)
1522 # This code path is buggy and deprecated!
1523 wfDeprecated( 'disabling tidy', '1.33' );
1525 # ''Something [http://www.cool.com cool''] -->
1526 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1527 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1528 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1529 # fix up an anchor inside another anchor, only
1530 # at least for a single single nested link (T5695)
1531 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1532 '\\1\\2</a>\\3</a>\\1\\4</a>',
1533 # fix div inside inline elements- doBlockLevels won't wrap a line which
1534 # contains a div, so fix it up here; replace
1535 # div with escaped text
1536 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1537 '\\1\\3<div\\5>\\6</div>\\8\\9',
1538 # remove empty italic or bold tag pairs, some
1539 # introduced by rules above
1540 '/<([bi])><\/\\1>/' => '',
1543 $text = preg_replace(
1544 array_keys( $tidyregs ),
1545 array_values( $tidyregs ),
1550 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1557 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1558 * magic external links.
1563 * @param string $text
1567 public function doMagicLinks( $text ) {
1568 $prots = wfUrlProtocolsWithoutProtRel();
1569 $urlChar = self
::EXT_LINK_URL_CLASS
;
1570 $addr = self
::EXT_LINK_ADDR
;
1571 $space = self
::SPACE_NOT_NL
; # non-newline space
1572 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1573 $spaces = "$space++"; # possessive match of 1 or more spaces
1574 $text = preg_replace_callback(
1576 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1577 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1578 (\b # m[3]: Free external links
1580 ($addr$urlChar*) # m[4]: Post-protocol path
1582 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1584 \bISBN $spaces ( # m[6]: ISBN, capture number
1585 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1586 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1587 [0-9Xx] # check digit
1589 )!xu", [ $this, 'magicLinkCallback' ], $text );
1594 * @throws MWException
1596 * @return string HTML
1598 public function magicLinkCallback( $m ) {
1599 if ( isset( $m[1] ) && $m[1] !== '' ) {
1602 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1605 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1606 # Free external link
1607 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1608 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1610 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1611 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1616 $cssClass = 'mw-magiclink-rfc';
1617 $trackingCat = 'magiclink-tracking-rfc';
1619 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1620 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1624 $urlmsg = 'pubmedurl';
1625 $cssClass = 'mw-magiclink-pmid';
1626 $trackingCat = 'magiclink-tracking-pmid';
1629 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1630 substr( $m[0], 0, 20 ) . '"' );
1632 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1633 $this->addTrackingCategory( $trackingCat );
1634 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1635 } elseif ( isset( $m[6] ) && $m[6] !== ''
1636 && $this->mOptions
->getMagicISBNLinks()
1640 $space = self
::SPACE_NOT_NL
; # non-newline space
1641 $isbn = preg_replace( "/$space/", ' ', $isbn );
1642 $num = strtr( $isbn, [
1647 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1648 return $this->getLinkRenderer()->makeKnownLink(
1649 SpecialPage
::getTitleFor( 'Booksources', $num ),
1652 'class' => 'internal mw-magiclink-isbn',
1653 'title' => false // suppress title attribute
1662 * Make a free external link, given a user-supplied URL
1664 * @param string $url
1665 * @param int $numPostProto
1666 * The number of characters after the protocol.
1667 * @return string HTML
1670 public function makeFreeExternalLink( $url, $numPostProto ) {
1673 # The characters '<' and '>' (which were escaped by
1674 # removeHTMLtags()) should not be included in
1675 # URLs, per RFC 2396.
1676 # Make terminate a URL as well (bug T84937)
1679 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1684 $trail = substr( $url, $m2[0][1] ) . $trail;
1685 $url = substr( $url, 0, $m2[0][1] );
1688 # Move trailing punctuation to $trail
1690 # If there is no left bracket, then consider right brackets fair game too
1691 if ( strpos( $url, '(' ) === false ) {
1695 $urlRev = strrev( $url );
1696 $numSepChars = strspn( $urlRev, $sep );
1697 # Don't break a trailing HTML entity by moving the ; into $trail
1698 # This is in hot code, so use substr_compare to avoid having to
1699 # create a new string object for the comparison
1700 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1701 # more optimization: instead of running preg_match with a $
1702 # anchor, which can be slow, do the match on the reversed
1703 # string starting at the desired offset.
1704 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1705 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1709 if ( $numSepChars ) {
1710 $trail = substr( $url, -$numSepChars ) . $trail;
1711 $url = substr( $url, 0, -$numSepChars );
1714 # Verify that we still have a real URL after trail removal, and
1715 # not just lone protocol
1716 if ( strlen( $trail ) >= $numPostProto ) {
1717 return $url . $trail;
1720 $url = Sanitizer
::cleanUrl( $url );
1722 # Is this an external image?
1723 $text = $this->maybeMakeExternalImage( $url );
1724 if ( $text === false ) {
1725 # Not an image, make a link
1726 $text = Linker
::makeExternalLink( $url,
1727 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1729 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1730 # Register it in the output object...
1731 $this->mOutput
->addExternalLink( $url );
1733 return $text . $trail;
1737 * Parse headers and return html
1741 * @param string $text
1745 public function doHeadings( $text ) {
1746 for ( $i = 6; $i >= 1; --$i ) {
1747 $h = str_repeat( '=', $i );
1748 // Trim non-newline whitespace from headings
1749 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1750 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1756 * Replace single quotes with HTML markup
1759 * @param string $text
1761 * @return string The altered text
1763 public function doAllQuotes( $text ) {
1765 $lines = StringUtils
::explode( "\n", $text );
1766 foreach ( $lines as $line ) {
1767 $outtext .= $this->doQuotes( $line ) . "\n";
1769 $outtext = substr( $outtext, 0, -1 );
1774 * Helper function for doAllQuotes()
1776 * @param string $text
1780 public function doQuotes( $text ) {
1781 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1782 $countarr = count( $arr );
1783 if ( $countarr == 1 ) {
1787 // First, do some preliminary work. This may shift some apostrophes from
1788 // being mark-up to being text. It also counts the number of occurrences
1789 // of bold and italics mark-ups.
1792 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1793 $thislen = strlen( $arr[$i] );
1794 // If there are ever four apostrophes, assume the first is supposed to
1795 // be text, and the remaining three constitute mark-up for bold text.
1796 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1797 if ( $thislen == 4 ) {
1798 $arr[$i - 1] .= "'";
1801 } elseif ( $thislen > 5 ) {
1802 // If there are more than 5 apostrophes in a row, assume they're all
1803 // text except for the last 5.
1804 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1805 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1809 // Count the number of occurrences of bold and italics mark-ups.
1810 if ( $thislen == 2 ) {
1812 } elseif ( $thislen == 3 ) {
1814 } elseif ( $thislen == 5 ) {
1820 // If there is an odd number of both bold and italics, it is likely
1821 // that one of the bold ones was meant to be an apostrophe followed
1822 // by italics. Which one we cannot know for certain, but it is more
1823 // likely to be one that has a single-letter word before it.
1824 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1825 $firstsingleletterword = -1;
1826 $firstmultiletterword = -1;
1828 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1829 if ( strlen( $arr[$i] ) == 3 ) {
1830 $x1 = substr( $arr[$i - 1], -1 );
1831 $x2 = substr( $arr[$i - 1], -2, 1 );
1832 if ( $x1 === ' ' ) {
1833 if ( $firstspace == -1 ) {
1836 } elseif ( $x2 === ' ' ) {
1837 $firstsingleletterword = $i;
1838 // if $firstsingleletterword is set, we don't
1839 // look at the other options, so we can bail early.
1841 } elseif ( $firstmultiletterword == -1 ) {
1842 $firstmultiletterword = $i;
1847 // If there is a single-letter word, use it!
1848 if ( $firstsingleletterword > -1 ) {
1849 $arr[$firstsingleletterword] = "''";
1850 $arr[$firstsingleletterword - 1] .= "'";
1851 } elseif ( $firstmultiletterword > -1 ) {
1852 // If not, but there's a multi-letter word, use that one.
1853 $arr[$firstmultiletterword] = "''";
1854 $arr[$firstmultiletterword - 1] .= "'";
1855 } elseif ( $firstspace > -1 ) {
1856 // ... otherwise use the first one that has neither.
1857 // (notice that it is possible for all three to be -1 if, for example,
1858 // there is only one pentuple-apostrophe in the line)
1859 $arr[$firstspace] = "''";
1860 $arr[$firstspace - 1] .= "'";
1864 // Now let's actually convert our apostrophic mush to HTML!
1869 foreach ( $arr as $r ) {
1870 if ( ( $i %
2 ) == 0 ) {
1871 if ( $state === 'both' ) {
1877 $thislen = strlen( $r );
1878 if ( $thislen == 2 ) {
1879 if ( $state === 'i' ) {
1882 } elseif ( $state === 'bi' ) {
1885 } elseif ( $state === 'ib' ) {
1886 $output .= '</b></i><b>';
1888 } elseif ( $state === 'both' ) {
1889 $output .= '<b><i>' . $buffer . '</i>';
1891 } else { // $state can be 'b' or ''
1895 } elseif ( $thislen == 3 ) {
1896 if ( $state === 'b' ) {
1899 } elseif ( $state === 'bi' ) {
1900 $output .= '</i></b><i>';
1902 } elseif ( $state === 'ib' ) {
1905 } elseif ( $state === 'both' ) {
1906 $output .= '<i><b>' . $buffer . '</b>';
1908 } else { // $state can be 'i' or ''
1912 } elseif ( $thislen == 5 ) {
1913 if ( $state === 'b' ) {
1914 $output .= '</b><i>';
1916 } elseif ( $state === 'i' ) {
1917 $output .= '</i><b>';
1919 } elseif ( $state === 'bi' ) {
1920 $output .= '</i></b>';
1922 } elseif ( $state === 'ib' ) {
1923 $output .= '</b></i>';
1925 } elseif ( $state === 'both' ) {
1926 $output .= '<i><b>' . $buffer . '</b></i>';
1928 } else { // ($state == '')
1936 // Now close all remaining tags. Notice that the order is important.
1937 if ( $state === 'b' ||
$state === 'ib' ) {
1940 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1943 if ( $state === 'bi' ) {
1946 // There might be lonely ''''', so make sure we have a buffer
1947 if ( $state === 'both' && $buffer ) {
1948 $output .= '<b><i>' . $buffer . '</i></b>';
1954 * Replace external links (REL)
1956 * Note: this is all very hackish and the order of execution matters a lot.
1957 * Make sure to run tests/parser/parserTests.php if you change this code.
1961 * @param string $text
1963 * @throws MWException
1966 public function replaceExternalLinks( $text ) {
1967 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1968 if ( $bits === false ) {
1969 throw new MWException( "PCRE needs to be compiled with "
1970 . "--enable-unicode-properties in order for MediaWiki to function" );
1972 $s = array_shift( $bits );
1975 while ( $i < count( $bits ) ) {
1978 $text = $bits[$i++
];
1979 $trail = $bits[$i++
];
1981 # The characters '<' and '>' (which were escaped by
1982 # removeHTMLtags()) should not be included in
1983 # URLs, per RFC 2396.
1985 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1986 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1987 $url = substr( $url, 0, $m2[0][1] );
1990 # If the link text is an image URL, replace it with an <img> tag
1991 # This happened by accident in the original parser, but some people used it extensively
1992 $img = $this->maybeMakeExternalImage( $text );
1993 if ( $img !== false ) {
1999 # Set linktype for CSS
2002 # No link text, e.g. [http://domain.tld/some.link]
2003 if ( $text == '' ) {
2005 $langObj = $this->getTargetLanguage();
2006 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
2007 $linktype = 'autonumber';
2009 # Have link text, e.g. [http://domain.tld/some.link text]s
2011 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
2014 // Excluding protocol-relative URLs may avoid many false positives.
2015 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
2016 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
2019 $url = Sanitizer
::cleanUrl( $url );
2021 # Use the encoded URL
2022 # This means that users can paste URLs directly into the text
2023 # Funny characters like ö aren't valid in URLs anyway
2024 # This was changed in August 2004
2025 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
2026 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
2028 # Register link in the output object.
2029 $this->mOutput
->addExternalLink( $url );
2036 * Get the rel attribute for a particular external link.
2039 * @param string|bool $url Optional URL, to extract the domain from for rel =>
2040 * nofollow if appropriate
2041 * @param LinkTarget|null $title Optional LinkTarget, for wgNoFollowNsExceptions lookups
2042 * @return string|null Rel attribute for $url
2044 public static function getExternalLinkRel( $url = false, $title = null ) {
2045 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
2046 $ns = $title ?
$title->getNamespace() : false;
2047 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
2048 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
2056 * Get an associative array of additional HTML attributes appropriate for a
2057 * particular external link. This currently may include rel => nofollow
2058 * (depending on configuration, namespace, and the URL's domain) and/or a
2059 * target attribute (depending on configuration).
2061 * @param string $url URL to extract the domain from for rel =>
2062 * nofollow if appropriate
2063 * @return array Associative array of HTML attributes
2065 public function getExternalLinkAttribs( $url ) {
2067 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
2069 $target = $this->mOptions
->getExternalLinkTarget();
2071 $attribs['target'] = $target;
2072 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
2073 // T133507. New windows can navigate parent cross-origin.
2074 // Including noreferrer due to lacking browser
2075 // support of noopener. Eventually noreferrer should be removed.
2076 if ( $rel !== '' ) {
2079 $rel .= 'noreferrer noopener';
2082 $attribs['rel'] = $rel;
2087 * Replace unusual escape codes in a URL with their equivalent characters
2089 * This generally follows the syntax defined in RFC 3986, with special
2090 * consideration for HTTP query strings.
2092 * @param string $url
2095 public static function normalizeLinkUrl( $url ) {
2096 # Test for RFC 3986 IPv6 syntax
2097 $scheme = '[a-z][a-z0-9+.-]*:';
2098 $userinfo = '(?:[a-z0-9\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*';
2099 $ipv6Host = '\\[((?:[0-9a-f:]|%3[0-A]|%[46][1-6])+)\\]';
2100 if ( preg_match( "<^(?:{$scheme})?//(?:{$userinfo}@)?{$ipv6Host}(?:[:/?#].*|)$>i", $url, $m ) &&
2101 IP
::isValid( rawurldecode( $m[1] ) )
2103 $isIPv6 = rawurldecode( $m[1] );
2108 # Make sure unsafe characters are encoded
2109 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2111 return rawurlencode( $m[0] );
2117 $end = strlen( $url );
2119 # Fragment part - 'fragment'
2120 $start = strpos( $url, '#' );
2121 if ( $start !== false && $start < $end ) {
2122 $ret = self
::normalizeUrlComponent(
2123 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2127 # Query part - 'query' minus &=+;
2128 $start = strpos( $url, '?' );
2129 if ( $start !== false && $start < $end ) {
2130 $ret = self
::normalizeUrlComponent(
2131 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2135 # Scheme and path part - 'pchar'
2136 # (we assume no userinfo or encoded colons in the host)
2137 $ret = self
::normalizeUrlComponent(
2138 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2141 if ( $isIPv6 !== false ) {
2142 $ipv6Host = "%5B({$isIPv6})%5D";
2143 $ret = preg_replace(
2144 "<^((?:{$scheme})?//(?:{$userinfo}@)?){$ipv6Host}(?=[:/?#]|$)>i",
2153 private static function normalizeUrlComponent( $component, $unsafe ) {
2154 $callback = function ( $matches ) use ( $unsafe ) {
2155 $char = urldecode( $matches[0] );
2156 $ord = ord( $char );
2157 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2161 # Leave it escaped, but use uppercase for a-f
2162 return strtoupper( $matches[0] );
2165 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2169 * make an image if it's allowed, either through the global
2170 * option, through the exception, or through the on-wiki whitelist
2172 * @param string $url
2176 private function maybeMakeExternalImage( $url ) {
2177 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2178 $imagesexception = !empty( $imagesfrom );
2180 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2181 if ( $imagesexception && is_array( $imagesfrom ) ) {
2182 $imagematch = false;
2183 foreach ( $imagesfrom as $match ) {
2184 if ( strpos( $url, $match ) === 0 ) {
2189 } elseif ( $imagesexception ) {
2190 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2192 $imagematch = false;
2195 if ( $this->mOptions
->getAllowExternalImages()
2196 ||
( $imagesexception && $imagematch )
2198 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2200 $text = Linker
::makeExternalImage( $url );
2203 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2204 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2206 $whitelist = explode(
2208 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2211 foreach ( $whitelist as $entry ) {
2212 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2213 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2216 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2217 # Image matches a whitelist entry
2218 $text = Linker
::makeExternalImage( $url );
2227 * Process [[ ]] wikilinks
2231 * @return string Processed text
2235 public function replaceInternalLinks( $s ) {
2236 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2241 * Process [[ ]] wikilinks (RIL)
2243 * @throws MWException
2244 * @return LinkHolderArray
2248 public function replaceInternalLinks2( &$s ) {
2249 static $tc = false, $e1, $e1_img;
2250 # the % is needed to support urlencoded titles as well
2252 $tc = Title
::legalChars() . '#%';
2253 # Match a link having the form [[namespace:link|alternate]]trail
2254 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2255 # Match cases where there is no "]]", which might still be images
2256 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2259 $holders = new LinkHolderArray( $this );
2261 # split the entire text string on occurrences of [[
2262 $a = StringUtils
::explode( '[[', ' ' . $s );
2263 # get the first element (all text up to first [[), and remove the space we added
2266 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2267 $s = substr( $s, 1 );
2269 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2271 if ( $useLinkPrefixExtension ) {
2272 # Match the end of a line for a word that's not followed by whitespace,
2273 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2274 $charset = $this->contLang
->linkPrefixCharset();
2275 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2278 if ( is_null( $this->mTitle
) ) {
2279 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2281 $nottalk = !$this->mTitle
->isTalkPage();
2283 if ( $useLinkPrefixExtension ) {
2285 if ( preg_match( $e2, $s, $m ) ) {
2286 $first_prefix = $m[2];
2288 $first_prefix = false;
2294 $useSubpages = $this->areSubpagesAllowed();
2296 # Loop for each link
2297 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2298 # Check for excessive memory usage
2299 if ( $holders->isBig() ) {
2301 # Do the existence check, replace the link holders and clear the array
2302 $holders->replace( $s );
2306 if ( $useLinkPrefixExtension ) {
2307 if ( preg_match( $e2, $s, $m ) ) {
2308 list( , $s, $prefix ) = $m;
2313 if ( $first_prefix ) {
2314 $prefix = $first_prefix;
2315 $first_prefix = false;
2319 $might_be_img = false;
2321 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2323 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2324 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2325 # the real problem is with the $e1 regex
2327 # Still some problems for cases where the ] is meant to be outside punctuation,
2328 # and no image is in sight. See T4095.
2330 && substr( $m[3], 0, 1 ) === ']'
2331 && strpos( $text, '[' ) !== false
2333 $text .= ']'; # so that replaceExternalLinks($text) works later
2334 $m[3] = substr( $m[3], 1 );
2336 # fix up urlencoded title texts
2337 if ( strpos( $m[1], '%' ) !== false ) {
2338 # Should anchors '#' also be rejected?
2339 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2342 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2343 # Invalid, but might be an image with a link in its caption
2344 $might_be_img = true;
2346 if ( strpos( $m[1], '%' ) !== false ) {
2347 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2350 } else { # Invalid form; output directly
2351 $s .= $prefix . '[[' . $line;
2355 $origLink = ltrim( $m[1], ' ' );
2357 # Don't allow internal links to pages containing
2358 # PROTO: where PROTO is a valid URL protocol; these
2359 # should be external links.
2360 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2361 $s .= $prefix . '[[' . $line;
2365 # Make subpage if necessary
2366 if ( $useSubpages ) {
2367 $link = $this->maybeDoSubpageLink( $origLink, $text );
2372 // \x7f isn't a default legal title char, so most likely strip
2373 // markers will force us into the "invalid form" path above. But,
2374 // just in case, let's assert that xmlish tags aren't valid in
2375 // the title position.
2376 $unstrip = $this->mStripState
->killMarkers( $link );
2377 $noMarkers = ( $unstrip === $link );
2379 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2380 if ( $nt === null ) {
2381 $s .= $prefix . '[[' . $line;
2385 $ns = $nt->getNamespace();
2386 $iw = $nt->getInterwiki();
2388 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2390 if ( $might_be_img ) { # if this is actually an invalid link
2391 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2394 # look at the next 'line' to see if we can close it there
2396 $next_line = $a->current();
2397 if ( $next_line === false ||
$next_line === null ) {
2400 $m = explode( ']]', $next_line, 3 );
2401 if ( count( $m ) == 3 ) {
2402 # the first ]] closes the inner link, the second the image
2404 $text .= "[[{$m[0]}]]{$m[1]}";
2407 } elseif ( count( $m ) == 2 ) {
2408 # if there's exactly one ]] that's fine, we'll keep looking
2409 $text .= "[[{$m[0]}]]{$m[1]}";
2411 # if $next_line is invalid too, we need look no further
2412 $text .= '[[' . $next_line;
2417 # we couldn't find the end of this imageLink, so output it raw
2418 # but don't ignore what might be perfectly normal links in the text we've examined
2419 $holders->merge( $this->replaceInternalLinks2( $text ) );
2420 $s .= "{$prefix}[[$link|$text";
2421 # note: no $trail, because without an end, there *is* no trail
2424 } else { # it's not an image, so output it raw
2425 $s .= "{$prefix}[[$link|$text";
2426 # note: no $trail, because without an end, there *is* no trail
2431 $wasblank = ( $text == '' );
2435 # Strip off leading ':'
2436 $text = substr( $text, 1 );
2439 # T6598 madness. Handle the quotes only if they come from the alternate part
2440 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2441 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2442 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2443 $text = $this->doQuotes( $text );
2446 # Link not escaped by : , create the various objects
2447 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2450 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2451 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2452 in_array( $iw, $this->svcOptions
->get( 'ExtraInterlanguageLinkPrefixes' ) )
2455 # T26502: filter duplicates
2456 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2457 $this->mLangLinkLanguages
[$iw] = true;
2458 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2462 * Strip the whitespace interwiki links produce, see T10897
2464 $s = rtrim( $s . $prefix ) . $trail; # T175416
2468 if ( $ns == NS_FILE
) {
2469 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2471 # if no parameters were passed, $text
2472 # becomes something like "File:Foo.png",
2473 # which we don't want to pass on to the
2477 # recursively parse links inside the image caption
2478 # actually, this will parse them in any other parameters, too,
2479 # but it might be hard to fix that, and it doesn't matter ATM
2480 $text = $this->replaceExternalLinks( $text );
2481 $holders->merge( $this->replaceInternalLinks2( $text ) );
2483 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2484 $s .= $prefix . $this->armorLinks(
2485 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2488 } elseif ( $ns == NS_CATEGORY
) {
2490 * Strip the whitespace Category links produce, see T2087
2492 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2495 $sortkey = $this->getDefaultSort();
2499 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2500 $sortkey = str_replace( "\n", '', $sortkey );
2501 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2502 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2508 # Self-link checking. For some languages, variants of the title are checked in
2509 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2510 # for linking to a different variant.
2511 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2512 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2516 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2517 # @todo FIXME: Should do batch file existence checks, see comment below
2518 if ( $ns == NS_MEDIA
) {
2519 # Give extensions a chance to select the file revision for us
2522 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2523 [ $this, $nt, &$options, &$descQuery ] );
2524 # Fetch and register the file (file title may be different via hooks)
2525 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2526 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2527 $s .= $prefix . $this->armorLinks(
2528 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2532 # Some titles, such as valid special pages or files in foreign repos, should
2533 # be shown as bluelinks even though they're not included in the page table
2534 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2535 # batch file existence checks for NS_FILE and NS_MEDIA
2536 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2537 $this->mOutput
->addLink( $nt );
2538 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2540 # Links will be added to the output link list after checking
2541 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2548 * Render a forced-blue link inline; protect against double expansion of
2549 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2550 * Since this little disaster has to split off the trail text to avoid
2551 * breaking URLs in the following text without breaking trails on the
2552 * wiki links, it's been made into a horrible function.
2555 * @param string $text
2556 * @param string $trail
2557 * @param string $prefix
2558 * @return string HTML-wikitext mix oh yuck
2560 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2561 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2563 if ( $text == '' ) {
2564 $text = htmlspecialchars( $nt->getPrefixedText() );
2567 $link = $this->getLinkRenderer()->makeKnownLink(
2568 $nt, new HtmlArmor( "$prefix$text$inside" )
2571 return $this->armorLinks( $link ) . $trail;
2575 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2576 * going to go through further parsing steps before inline URL expansion.
2578 * Not needed quite as much as it used to be since free links are a bit
2579 * more sensible these days. But bracketed links are still an issue.
2581 * @param string $text More-or-less HTML
2582 * @return string Less-or-more HTML with NOPARSE bits
2584 public function armorLinks( $text ) {
2585 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2586 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2590 * Return true if subpage links should be expanded on this page.
2593 public function areSubpagesAllowed() {
2594 # Some namespaces don't allow subpages
2595 return $this->nsInfo
->hasSubpages( $this->mTitle
->getNamespace() );
2599 * Handle link to subpage if necessary
2601 * @param string $target The source of the link
2602 * @param string &$text The link text, modified as necessary
2603 * @return string The full name of the link
2606 public function maybeDoSubpageLink( $target, &$text ) {
2607 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2611 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2613 * @param string $text
2614 * @param bool $linestart Whether or not this is at the start of a line.
2616 * @return string The lists rendered as HTML
2618 public function doBlockLevels( $text, $linestart ) {
2619 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2623 * Return value of a magic variable (like PAGENAME)
2627 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2628 * @param bool|PPFrame $frame
2630 * @throws MWException
2633 public function getVariableValue( $index, $frame = false ) {
2634 if ( is_null( $this->mTitle
) ) {
2635 // If no title set, bad things are going to happen
2636 // later. Title should always be set since this
2637 // should only be called in the middle of a parse
2638 // operation (but the unit-tests do funky stuff)
2639 throw new MWException( __METHOD__
. ' Should only be '
2640 . ' called while parsing (no title set)' );
2643 // Avoid PHP 7.1 warning from passing $this by reference
2647 * Some of these require message or data lookups and can be
2648 * expensive to check many times.
2651 Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) &&
2652 isset( $this->mVarCache
[$index] )
2654 return $this->mVarCache
[$index];
2657 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2658 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2660 $pageLang = $this->getFunctionLang();
2666 case 'currentmonth':
2667 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2669 case 'currentmonth1':
2670 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2672 case 'currentmonthname':
2673 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2675 case 'currentmonthnamegen':
2676 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2678 case 'currentmonthabbrev':
2679 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2682 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2685 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2688 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2691 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2693 case 'localmonthname':
2694 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2696 case 'localmonthnamegen':
2697 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2699 case 'localmonthabbrev':
2700 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2703 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2706 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2709 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2712 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2714 case 'fullpagename':
2715 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2717 case 'fullpagenamee':
2718 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2721 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2723 case 'subpagenamee':
2724 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2726 case 'rootpagename':
2727 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2729 case 'rootpagenamee':
2730 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2733 $this->mTitle
->getRootText()
2736 case 'basepagename':
2737 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2739 case 'basepagenamee':
2740 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2743 $this->mTitle
->getBaseText()
2746 case 'talkpagename':
2747 if ( $this->mTitle
->canHaveTalkPage() ) {
2748 $talkPage = $this->mTitle
->getTalkPage();
2749 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2754 case 'talkpagenamee':
2755 if ( $this->mTitle
->canHaveTalkPage() ) {
2756 $talkPage = $this->mTitle
->getTalkPage();
2757 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2762 case 'subjectpagename':
2763 $subjPage = $this->mTitle
->getSubjectPage();
2764 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2766 case 'subjectpagenamee':
2767 $subjPage = $this->mTitle
->getSubjectPage();
2768 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2770 case 'pageid': // requested in T25427
2771 $pageid = $this->getTitle()->getArticleID();
2772 if ( $pageid == 0 ) {
2773 # 0 means the page doesn't exist in the database,
2774 # which means the user is previewing a new page.
2775 # The vary-revision flag must be set, because the magic word
2776 # will have a different value once the page is saved.
2777 $this->mOutput
->setFlag( 'vary-revision' );
2778 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision" );
2780 $value = $pageid ?
: null;
2784 $this->svcOptions
->get( 'MiserMode' ) &&
2785 !$this->mOptions
->getInterfaceMessage() &&
2786 // @TODO: disallow this word on all namespaces
2787 $this->nsInfo
->isContent( $this->mTitle
->getNamespace() )
2789 // Use a stub result instead of the actual revision ID in order to avoid
2790 // double parses on page save but still allow preview detection (T137900)
2791 if ( $this->getRevisionId() ||
$this->mOptions
->getSpeculativeRevId() ) {
2794 $this->mOutput
->setFlag( 'vary-revision-exists' );
2795 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-exists" );
2799 # Inform the edit saving system that getting the canonical output after
2800 # revision insertion requires another parse using the actual revision ID
2801 $this->mOutput
->setFlag( 'vary-revision-id' );
2802 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id" );
2803 $value = $this->getRevisionId();
2804 if ( $value === 0 ) {
2805 $rev = $this->getRevisionObject();
2806 $value = $rev ?
$rev->getId() : $value;
2809 $value = $this->mOptions
->getSpeculativeRevId();
2811 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2817 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2819 case 'revisionday2':
2820 $value = $this->getRevisionTimestampSubstring( 6, 2, self
::MAX_TTS
, $index );
2822 case 'revisionmonth':
2823 $value = $this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2825 case 'revisionmonth1':
2826 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self
::MAX_TTS
, $index );
2828 case 'revisionyear':
2829 $value = $this->getRevisionTimestampSubstring( 0, 4, self
::MAX_TTS
, $index );
2831 case 'revisiontimestamp':
2832 $value = $this->getRevisionTimestampSubstring( 0, 14, self
::MAX_TTS
, $index );
2834 case 'revisionuser':
2835 # Inform the edit saving system that getting the canonical output after
2836 # revision insertion requires a parse that used the actual user ID
2837 $this->mOutput
->setFlag( 'vary-user' );
2838 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user" );
2839 $value = $this->getRevisionUser();
2841 case 'revisionsize':
2842 $value = $this->getRevisionSize();
2845 $value = str_replace( '_', ' ',
2846 $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2849 $value = wfUrlencode( $this->contLang
->getNsText( $this->mTitle
->getNamespace() ) );
2851 case 'namespacenumber':
2852 $value = $this->mTitle
->getNamespace();
2855 $value = $this->mTitle
->canHaveTalkPage()
2856 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2860 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2862 case 'subjectspace':
2863 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2865 case 'subjectspacee':
2866 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2868 case 'currentdayname':
2869 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2872 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2875 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2878 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2881 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2882 # int to remove the padding
2883 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2886 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2888 case 'localdayname':
2889 $value = $pageLang->getWeekdayName(
2890 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2894 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2897 $value = $pageLang->time(
2898 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2904 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2907 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2908 # int to remove the padding
2909 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2912 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2914 case 'numberofarticles':
2915 $value = $pageLang->formatNum( SiteStats
::articles() );
2917 case 'numberoffiles':
2918 $value = $pageLang->formatNum( SiteStats
::images() );
2920 case 'numberofusers':
2921 $value = $pageLang->formatNum( SiteStats
::users() );
2923 case 'numberofactiveusers':
2924 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2926 case 'numberofpages':
2927 $value = $pageLang->formatNum( SiteStats
::pages() );
2929 case 'numberofadmins':
2930 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2932 case 'numberofedits':
2933 $value = $pageLang->formatNum( SiteStats
::edits() );
2935 case 'currenttimestamp':
2936 $value = wfTimestamp( TS_MW
, $ts );
2938 case 'localtimestamp':
2939 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2941 case 'currentversion':
2942 $value = SpecialVersion
::getVersion();
2945 return $this->svcOptions
->get( 'ArticlePath' );
2947 return $this->svcOptions
->get( 'Sitename' );
2949 return $this->svcOptions
->get( 'Server' );
2951 return $this->svcOptions
->get( 'ServerName' );
2953 return $this->svcOptions
->get( 'ScriptPath' );
2955 return $this->svcOptions
->get( 'StylePath' );
2956 case 'directionmark':
2957 return $pageLang->getDirMark();
2958 case 'contentlanguage':
2959 return $this->svcOptions
->get( 'LanguageCode' );
2960 case 'pagelanguage':
2961 $value = $pageLang->getCode();
2963 case 'cascadingsources':
2964 $value = CoreParserFunctions
::cascadingsources( $this );
2969 'ParserGetVariableValueSwitch',
2970 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2977 $this->mVarCache
[$index] = $value;
2986 * @param int $mtts Max time-till-save; sets vary-revision-timestamp if result changes by then
2987 * @param string $variable Parser variable name
2990 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2991 # Get the timezone-adjusted timestamp to be used for this revision
2992 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2993 # Possibly set vary-revision if there is not yet an associated revision
2994 if ( !$this->getRevisionObject() ) {
2995 # Get the timezone-adjusted timestamp $mtts seconds in the future.
2996 # This future is relative to the current time and not that of the
2997 # parser options. The rendered timestamp can be compared to that
2998 # of the timestamp specified by the parser options.
3000 $this->contLang
->userAdjust( wfTimestamp( TS_MW
, time() +
$mtts ), '' ),
3005 if ( $resNow !== $resThen ) {
3006 # Inform the edit saving system that getting the canonical output after
3007 # revision insertion requires a parse that used an actual revision timestamp
3008 $this->mOutput
->setFlag( 'vary-revision-timestamp' );
3009 wfDebug( __METHOD__
. ": $variable used, setting vary-revision-timestamp" );
3017 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3021 public function initialiseVariables() {
3022 $variableIDs = $this->magicWordFactory
->getVariableIDs();
3023 $substIDs = $this->magicWordFactory
->getSubstIDs();
3025 $this->mVariables
= $this->magicWordFactory
->newArray( $variableIDs );
3026 $this->mSubstWords
= $this->magicWordFactory
->newArray( $substIDs );
3030 * Preprocess some wikitext and return the document tree.
3031 * This is the ghost of replace_variables().
3033 * @param string $text The text to parse
3034 * @param int $flags Bitwise combination of:
3035 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3036 * included. Default is to assume a direct page view.
3038 * The generated DOM tree must depend only on the input text and the flags.
3039 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
3041 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3042 * change in the DOM tree for a given text, must be passed through the section identifier
3043 * in the section edit link and thus back to extractSections().
3045 * The output of this function is currently only cached in process memory, but a persistent
3046 * cache may be implemented at a later date which takes further advantage of these strict
3047 * dependency requirements.
3051 public function preprocessToDom( $text, $flags = 0 ) {
3052 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3057 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3063 public static function splitWhitespace( $s ) {
3064 $ltrimmed = ltrim( $s );
3065 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3066 $trimmed = rtrim( $ltrimmed );
3067 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3069 $w2 = substr( $ltrimmed, -$diff );
3073 return [ $w1, $trimmed, $w2 ];
3077 * Replace magic variables, templates, and template arguments
3078 * with the appropriate text. Templates are substituted recursively,
3079 * taking care to avoid infinite loops.
3081 * Note that the substitution depends on value of $mOutputType:
3082 * self::OT_WIKI: only {{subst:}} templates
3083 * self::OT_PREPROCESS: templates but not extension tags
3084 * self::OT_HTML: all templates and extension tags
3086 * @param string $text The text to transform
3087 * @param bool|PPFrame $frame Object describing the arguments passed to the
3088 * template. Arguments may also be provided as an associative array, as
3089 * was the usual case before MW1.12. Providing arguments this way may be
3090 * useful for extensions wishing to perform variable replacement
3092 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3093 * double-brace expansion.
3096 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3097 # Is there any text? Also, Prevent too big inclusions!
3098 $textSize = strlen( $text );
3099 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3103 if ( $frame === false ) {
3104 $frame = $this->getPreprocessor()->newFrame();
3105 } elseif ( !( $frame instanceof PPFrame
) ) {
3106 wfDebug( __METHOD__
. " called using plain parameters instead of "
3107 . "a PPFrame instance. Creating custom frame.\n" );
3108 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3111 $dom = $this->preprocessToDom( $text );
3112 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3113 $text = $frame->expand( $dom, $flags );
3119 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3121 * @param array $args
3125 public static function createAssocArgs( $args ) {
3128 foreach ( $args as $arg ) {
3129 $eqpos = strpos( $arg, '=' );
3130 if ( $eqpos === false ) {
3131 $assocArgs[$index++
] = $arg;
3133 $name = trim( substr( $arg, 0, $eqpos ) );
3134 $value = trim( substr( $arg, $eqpos +
1 ) );
3135 if ( $value === false ) {
3138 if ( $name !== false ) {
3139 $assocArgs[$name] = $value;
3148 * Warn the user when a parser limitation is reached
3149 * Will warn at most once the user per limitation type
3151 * The results are shown during preview and run through the Parser (See EditPage.php)
3153 * @param string $limitationType Should be one of:
3154 * 'expensive-parserfunction' (corresponding messages:
3155 * 'expensive-parserfunction-warning',
3156 * 'expensive-parserfunction-category')
3157 * 'post-expand-template-argument' (corresponding messages:
3158 * 'post-expand-template-argument-warning',
3159 * 'post-expand-template-argument-category')
3160 * 'post-expand-template-inclusion' (corresponding messages:
3161 * 'post-expand-template-inclusion-warning',
3162 * 'post-expand-template-inclusion-category')
3163 * 'node-count-exceeded' (corresponding messages:
3164 * 'node-count-exceeded-warning',
3165 * 'node-count-exceeded-category')
3166 * 'expansion-depth-exceeded' (corresponding messages:
3167 * 'expansion-depth-exceeded-warning',
3168 * 'expansion-depth-exceeded-category')
3169 * @param string|int|null $current Current value
3170 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3171 * exceeded, provide the values (optional)
3173 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3174 # does no harm if $current and $max are present but are unnecessary for the message
3175 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3176 # only during preview, and that would split the parser cache unnecessarily.
3177 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3179 $this->mOutput
->addWarning( $warning );
3180 $this->addTrackingCategory( "$limitationType-category" );
3184 * Return the text of a template, after recursively
3185 * replacing any variables or templates within the template.
3187 * @param array $piece The parts of the template
3188 * $piece['title']: the title, i.e. the part before the |
3189 * $piece['parts']: the parameter array
3190 * $piece['lineStart']: whether the brace was at the start of a line
3191 * @param PPFrame $frame The current frame, contains template arguments
3193 * @return string The text of the template
3195 public function braceSubstitution( $piece, $frame ) {
3198 // $text has been filled
3200 // wiki markup in $text should be escaped
3202 // $text is HTML, armour it against wikitext transformation
3204 // Force interwiki transclusion to be done in raw mode not rendered
3205 $forceRawInterwiki = false;
3206 // $text is a DOM node needing expansion in a child frame
3207 $isChildObj = false;
3208 // $text is a DOM node needing expansion in the current frame
3209 $isLocalObj = false;
3211 # Title object, where $text came from
3214 # $part1 is the bit before the first |, and must contain only title characters.
3215 # Various prefixes will be stripped from it later.
3216 $titleWithSpaces = $frame->expand( $piece['title'] );
3217 $part1 = trim( $titleWithSpaces );
3220 # Original title text preserved for various purposes
3221 $originalTitle = $part1;
3223 # $args is a list of argument nodes, starting from index 0, not including $part1
3224 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3225 # below won't work b/c this $args isn't an object
3226 $args = ( $piece['parts'] == null ) ?
[] : $piece['parts'];
3228 $profileSection = null; // profile templates
3232 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3234 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3235 # Decide whether to expand template or keep wikitext as-is.
3236 if ( $this->ot
['wiki'] ) {
3237 if ( $substMatch === false ) {
3238 $literal = true; # literal when in PST with no prefix
3240 $literal = false; # expand when in PST with subst: or safesubst:
3243 if ( $substMatch == 'subst' ) {
3244 $literal = true; # literal when not in PST with plain subst:
3246 $literal = false; # expand when not in PST with safesubst: or no prefix
3250 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3257 if ( !$found && $args->getLength() == 0 ) {
3258 $id = $this->mVariables
->matchStartToEnd( $part1 );
3259 if ( $id !== false ) {
3260 $text = $this->getVariableValue( $id, $frame );
3261 if ( $this->magicWordFactory
->getCacheTTL( $id ) > -1 ) {
3262 $this->mOutput
->updateCacheExpiry(
3263 $this->magicWordFactory
->getCacheTTL( $id ) );
3269 # MSG, MSGNW and RAW
3272 $mwMsgnw = $this->magicWordFactory
->get( 'msgnw' );
3273 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3276 # Remove obsolete MSG:
3277 $mwMsg = $this->magicWordFactory
->get( 'msg' );
3278 $mwMsg->matchStartAndRemove( $part1 );
3282 $mwRaw = $this->magicWordFactory
->get( 'raw' );
3283 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3284 $forceRawInterwiki = true;
3290 $colonPos = strpos( $part1, ':' );
3291 if ( $colonPos !== false ) {
3292 $func = substr( $part1, 0, $colonPos );
3293 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3294 $argsLength = $args->getLength();
3295 for ( $i = 0; $i < $argsLength; $i++
) {
3296 $funcArgs[] = $args->item( $i );
3299 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3301 // Extract any forwarded flags
3302 if ( isset( $result['title'] ) ) {
3303 $title = $result['title'];
3305 if ( isset( $result['found'] ) ) {
3306 $found = $result['found'];
3308 if ( array_key_exists( 'text', $result ) ) {
3310 $text = $result['text'];
3312 if ( isset( $result['nowiki'] ) ) {
3313 $nowiki = $result['nowiki'];
3315 if ( isset( $result['isHTML'] ) ) {
3316 $isHTML = $result['isHTML'];
3318 if ( isset( $result['forceRawInterwiki'] ) ) {
3319 $forceRawInterwiki = $result['forceRawInterwiki'];
3321 if ( isset( $result['isChildObj'] ) ) {
3322 $isChildObj = $result['isChildObj'];
3324 if ( isset( $result['isLocalObj'] ) ) {
3325 $isLocalObj = $result['isLocalObj'];
3330 # Finish mangling title and then check for loops.
3331 # Set $title to a Title object and $titleText to the PDBK
3334 # Split the title into page and subpage
3336 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3337 if ( $part1 !== $relative ) {
3339 $ns = $this->mTitle
->getNamespace();
3341 $title = Title
::newFromText( $part1, $ns );
3343 $titleText = $title->getPrefixedText();
3344 # Check for language variants if the template is not found
3345 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3346 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3348 # Do recursion depth check
3349 $limit = $this->mOptions
->getMaxTemplateDepth();
3350 if ( $frame->depth
>= $limit ) {
3352 $text = '<span class="error">'
3353 . wfMessage( 'parser-template-recursion-depth-warning' )
3354 ->numParams( $limit )->inContentLanguage()->text()
3360 # Load from database
3361 if ( !$found && $title ) {
3362 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3363 if ( !$title->isExternal() ) {
3364 if ( $title->isSpecialPage()
3365 && $this->mOptions
->getAllowSpecialInclusion()
3366 && $this->ot
['html']
3368 $specialPage = $this->specialPageFactory
->getPage( $title->getDBkey() );
3369 // Pass the template arguments as URL parameters.
3370 // "uselang" will have no effect since the Language object
3371 // is forced to the one defined in ParserOptions.
3373 $argsLength = $args->getLength();
3374 for ( $i = 0; $i < $argsLength; $i++
) {
3375 $bits = $args->item( $i )->splitArg();
3376 if ( strval( $bits['index'] ) === '' ) {
3377 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3378 $value = trim( $frame->expand( $bits['value'] ) );
3379 $pageArgs[$name] = $value;
3383 // Create a new context to execute the special page
3384 $context = new RequestContext
;
3385 $context->setTitle( $title );
3386 $context->setRequest( new FauxRequest( $pageArgs ) );
3387 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3388 $context->setUser( $this->getUser() );
3390 // If this page is cached, then we better not be per user.
3391 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3393 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3394 $ret = $this->specialPageFactory
->capturePath( $title, $context, $this->getLinkRenderer() );
3396 $text = $context->getOutput()->getHTML();
3397 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3400 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3401 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3402 $specialPage->maxIncludeCacheTime()
3406 } elseif ( $this->nsInfo
->isNonincludable( $title->getNamespace() ) ) {
3407 $found = false; # access denied
3408 wfDebug( __METHOD__
. ": template inclusion denied for " .
3409 $title->getPrefixedDBkey() . "\n" );
3411 list( $text, $title ) = $this->getTemplateDom( $title );
3412 if ( $text !== false ) {
3418 # If the title is valid but undisplayable, make a link to it
3419 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3420 $text = "[[:$titleText]]";
3423 } elseif ( $title->isTrans() ) {
3424 # Interwiki transclusion
3425 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3426 $text = $this->interwikiTransclude( $title, 'render' );
3429 $text = $this->interwikiTransclude( $title, 'raw' );
3430 # Preprocess it like a template
3431 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3437 # Do infinite loop check
3438 # This has to be done after redirect resolution to avoid infinite loops via redirects
3439 if ( !$frame->loopCheck( $title ) ) {
3441 $text = '<span class="error">'
3442 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3444 $this->addTrackingCategory( 'template-loop-category' );
3445 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3446 wfEscapeWikiText( $titleText ) )->text() );
3447 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3451 # If we haven't found text to substitute by now, we're done
3452 # Recover the source wikitext and return it
3454 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3455 if ( $profileSection ) {
3456 $this->mProfiler
->scopedProfileOut( $profileSection );
3458 return [ 'object' => $text ];
3461 # Expand DOM-style return values in a child frame
3462 if ( $isChildObj ) {
3463 # Clean up argument array
3464 $newFrame = $frame->newChild( $args, $title );
3467 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3468 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3469 # Expansion is eligible for the empty-frame cache
3470 $text = $newFrame->cachedExpand( $titleText, $text );
3472 # Uncached expansion
3473 $text = $newFrame->expand( $text );
3476 if ( $isLocalObj && $nowiki ) {
3477 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3478 $isLocalObj = false;
3481 if ( $profileSection ) {
3482 $this->mProfiler
->scopedProfileOut( $profileSection );
3485 # Replace raw HTML by a placeholder
3487 $text = $this->insertStripItem( $text );
3488 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3489 # Escape nowiki-style return values
3490 $text = wfEscapeWikiText( $text );
3491 } elseif ( is_string( $text )
3492 && !$piece['lineStart']
3493 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3495 # T2529: if the template begins with a table or block-level
3496 # element, it should be treated as beginning a new line.
3497 # This behavior is somewhat controversial.
3498 $text = "\n" . $text;
3501 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3502 # Error, oversize inclusion
3503 if ( $titleText !== false ) {
3504 # Make a working, properly escaped link if possible (T25588)
3505 $text = "[[:$titleText]]";
3507 # This will probably not be a working link, but at least it may
3508 # provide some hint of where the problem is
3509 preg_replace( '/^:/', '', $originalTitle );
3510 $text = "[[:$originalTitle]]";
3512 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3513 . 'post-expand include size too large -->' );
3514 $this->limitationWarn( 'post-expand-template-inclusion' );
3517 if ( $isLocalObj ) {
3518 $ret = [ 'object' => $text ];
3520 $ret = [ 'text' => $text ];
3527 * Call a parser function and return an array with text and flags.
3529 * The returned array will always contain a boolean 'found', indicating
3530 * whether the parser function was found or not. It may also contain the
3532 * text: string|object, resulting wikitext or PP DOM object
3533 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3534 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3535 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3536 * nowiki: bool, wiki markup in $text should be escaped
3539 * @param PPFrame $frame The current frame, contains template arguments
3540 * @param string $function Function name
3541 * @param array $args Arguments to the function
3542 * @throws MWException
3545 public function callParserFunction( $frame, $function, array $args = [] ) {
3546 # Case sensitive functions
3547 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3548 $function = $this->mFunctionSynonyms
[1][$function];
3550 # Case insensitive functions
3551 $function = $this->contLang
->lc( $function );
3552 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3553 $function = $this->mFunctionSynonyms
[0][$function];
3555 return [ 'found' => false ];
3559 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3561 // Avoid PHP 7.1 warning from passing $this by reference
3564 $allArgs = [ &$parser ];
3565 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3566 # Convert arguments to PPNodes and collect for appending to $allArgs
3568 foreach ( $args as $k => $v ) {
3569 if ( $v instanceof PPNode ||
$k === 0 ) {
3572 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3576 # Add a frame parameter, and pass the arguments as an array
3577 $allArgs[] = $frame;
3578 $allArgs[] = $funcArgs;
3580 # Convert arguments to plain text and append to $allArgs
3581 foreach ( $args as $k => $v ) {
3582 if ( $v instanceof PPNode
) {
3583 $allArgs[] = trim( $frame->expand( $v ) );
3584 } elseif ( is_int( $k ) && $k >= 0 ) {
3585 $allArgs[] = trim( $v );
3587 $allArgs[] = trim( "$k=$v" );
3592 $result = $callback( ...$allArgs );
3594 # The interface for function hooks allows them to return a wikitext
3595 # string or an array containing the string and any flags. This mungs
3596 # things around to match what this method should return.
3597 if ( !is_array( $result ) ) {
3603 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3604 $result['text'] = $result[0];
3606 unset( $result[0] );
3613 $preprocessFlags = 0;
3614 if ( isset( $result['noparse'] ) ) {
3615 $noparse = $result['noparse'];
3617 if ( isset( $result['preprocessFlags'] ) ) {
3618 $preprocessFlags = $result['preprocessFlags'];
3622 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3623 $result['isChildObj'] = true;
3630 * Get the semi-parsed DOM representation of a template with a given title,
3631 * and its redirect destination title. Cached.
3633 * @param Title $title
3637 public function getTemplateDom( $title ) {
3638 $cacheTitle = $title;
3639 $titleText = $title->getPrefixedDBkey();
3641 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3642 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3643 $title = Title
::makeTitle( $ns, $dbk );
3644 $titleText = $title->getPrefixedDBkey();
3646 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3647 return [ $this->mTplDomCache
[$titleText], $title ];
3650 # Cache miss, go to the database
3651 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3653 if ( $text === false ) {
3654 $this->mTplDomCache
[$titleText] = false;
3655 return [ false, $title ];
3658 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3659 $this->mTplDomCache
[$titleText] = $dom;
3661 if ( !$title->equals( $cacheTitle ) ) {
3662 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3663 [ $title->getNamespace(), $title->getDBkey() ];
3666 return [ $dom, $title ];
3670 * Fetch the current revision of a given title. Note that the revision
3671 * (and even the title) may not exist in the database, so everything
3672 * contributing to the output of the parser should use this method
3673 * where possible, rather than getting the revisions themselves. This
3674 * method also caches its results, so using it benefits performance.
3677 * @param Title $title
3680 public function fetchCurrentRevisionOfTitle( $title ) {
3681 $cacheKey = $title->getPrefixedDBkey();
3682 if ( !$this->currentRevisionCache
) {
3683 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3685 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3686 $this->currentRevisionCache
->set( $cacheKey,
3687 // Defaults to Parser::statelessFetchRevision()
3688 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3691 return $this->currentRevisionCache
->get( $cacheKey );
3695 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3696 * without passing them on to it.
3699 * @param Title $title
3700 * @param Parser|bool $parser
3701 * @return Revision|bool False if missing
3703 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3704 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3710 * Fetch the unparsed text of a template and register a reference to it.
3711 * @param Title $title
3712 * @return array ( string or false, Title )
3714 public function fetchTemplateAndTitle( $title ) {
3715 // Defaults to Parser::statelessFetchTemplate()
3716 $templateCb = $this->mOptions
->getTemplateCallback();
3717 $stuff = call_user_func( $templateCb, $title, $this );
3718 // We use U+007F DELETE to distinguish strip markers from regular text.
3719 $text = $stuff['text'];
3720 if ( is_string( $stuff['text'] ) ) {
3721 $text = strtr( $text, "\x7f", "?" );
3723 $finalTitle = $stuff['finalTitle'] ??
$title;
3724 if ( isset( $stuff['deps'] ) ) {
3725 foreach ( $stuff['deps'] as $dep ) {
3726 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3727 if ( $dep['title']->equals( $this->getTitle() ) ) {
3728 // If we transclude ourselves, the final result
3729 // will change based on the new version of the page
3730 $this->mOutput
->setFlag( 'vary-revision' );
3731 wfDebug( __METHOD__
. ": self transclusion, setting vary-revision" );
3735 return [ $text, $finalTitle ];
3739 * Fetch the unparsed text of a template and register a reference to it.
3740 * @param Title $title
3741 * @return string|bool
3743 public function fetchTemplate( $title ) {
3744 return $this->fetchTemplateAndTitle( $title )[0];
3748 * Static function to get a template
3749 * Can be overridden via ParserOptions::setTemplateCallback().
3751 * @param Title $title
3752 * @param bool|Parser $parser
3756 public static function statelessFetchTemplate( $title, $parser = false ) {
3757 $text = $skip = false;
3758 $finalTitle = $title;
3761 # Loop to fetch the article, with up to 1 redirect
3762 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3763 # Give extensions a chance to select the revision instead
3764 $id = false; # Assume current
3765 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3766 [ $parser, $title, &$skip, &$id ] );
3772 'page_id' => $title->getArticleID(),
3779 $rev = Revision
::newFromId( $id );
3780 } elseif ( $parser ) {
3781 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3783 $rev = Revision
::newFromTitle( $title );
3785 $rev_id = $rev ?
$rev->getId() : 0;
3786 # If there is no current revision, there is no page
3787 if ( $id === false && !$rev ) {
3788 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3789 $linkCache->addBadLinkObj( $title );
3794 'page_id' => $title->getArticleID(),
3795 'rev_id' => $rev_id ];
3796 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3797 # We fetched a rev from a different title; register it too...
3799 'title' => $rev->getTitle(),
3800 'page_id' => $rev->getPage(),
3801 'rev_id' => $rev_id ];
3805 $content = $rev->getContent();
3806 $text = $content ?
$content->getWikitextForTransclusion() : null;
3808 Hooks
::run( 'ParserFetchTemplate',
3809 [ $parser, $title, $rev, &$text, &$deps ] );
3811 if ( $text === false ||
$text === null ) {
3815 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3816 $message = wfMessage( MediaWikiServices
::getInstance()->getContentLanguage()->
3817 lcfirst( $title->getText() ) )->inContentLanguage();
3818 if ( !$message->exists() ) {
3822 $content = $message->content();
3823 $text = $message->plain();
3831 $finalTitle = $title;
3832 $title = $content->getRedirectTarget();
3836 'finalTitle' => $finalTitle,
3841 * Fetch a file and its title and register a reference to it.
3842 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3843 * @param Title $title
3844 * @param array $options Array of options to RepoGroup::findFile
3845 * @return array ( File or false, Title of file )
3847 public function fetchFileAndTitle( $title, $options = [] ) {
3848 $file = $this->fetchFileNoRegister( $title, $options );
3850 $time = $file ?
$file->getTimestamp() : false;
3851 $sha1 = $file ?
$file->getSha1() : false;
3852 # Register the file as a dependency...
3853 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3854 if ( $file && !$title->equals( $file->getTitle() ) ) {
3855 # Update fetched file title
3856 $title = $file->getTitle();
3857 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3859 return [ $file, $title ];
3863 * Helper function for fetchFileAndTitle.
3865 * Also useful if you need to fetch a file but not use it yet,
3866 * for example to get the file's handler.
3868 * @param Title $title
3869 * @param array $options Array of options to RepoGroup::findFile
3872 protected function fetchFileNoRegister( $title, $options = [] ) {
3873 if ( isset( $options['broken'] ) ) {
3874 $file = false; // broken thumbnail forced by hook
3875 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3876 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3877 } else { // get by (name,timestamp)
3878 $file = MediaWikiServices
::getInstance()->getRepoGroup()->findFile( $title, $options );
3884 * Transclude an interwiki link.
3886 * @param Title $title
3887 * @param string $action Usually one of (raw, render)
3891 public function interwikiTransclude( $title, $action ) {
3892 if ( !$this->svcOptions
->get( 'EnableScaryTranscluding' ) ) {
3893 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3896 $url = $title->getFullURL( [ 'action' => $action ] );
3897 if ( strlen( $url ) > 1024 ) {
3898 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3901 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3903 $fname = __METHOD__
;
3904 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3906 $data = $cache->getWithSetCallback(
3907 $cache->makeGlobalKey(
3908 'interwiki-transclude',
3909 ( $wikiId !== false ) ?
$wikiId : 'external',
3912 $this->svcOptions
->get( 'TranscludeCacheExpiry' ),
3913 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3914 $req = MWHttpRequest
::factory( $url, [], $fname );
3916 $status = $req->execute(); // Status object
3917 if ( !$status->isOK() ) {
3918 $ttl = $cache::TTL_UNCACHEABLE
;
3919 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3920 $ttl = min( $cache::TTL_LAGGED
, $ttl );
3924 'text' => $status->isOK() ?
$req->getContent() : null,
3925 'code' => $req->getStatus()
3929 'checkKeys' => ( $wikiId !== false )
3930 ?
[ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
3932 'pcGroup' => 'interwiki-transclude:5',
3933 'pcTTL' => $cache::TTL_PROC_LONG
3937 if ( is_string( $data['text'] ) ) {
3938 $text = $data['text'];
3939 } elseif ( $data['code'] != 200 ) {
3940 // Though we failed to fetch the content, this status is useless.
3941 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
3942 ->params( $url, $data['code'] )->inContentLanguage()->text();
3944 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3951 * Triple brace replacement -- used for template arguments
3954 * @param array $piece
3955 * @param PPFrame $frame
3959 public function argSubstitution( $piece, $frame ) {
3961 $parts = $piece['parts'];
3962 $nameWithSpaces = $frame->expand( $piece['title'] );
3963 $argName = trim( $nameWithSpaces );
3965 $text = $frame->getArgument( $argName );
3966 if ( $text === false && $parts->getLength() > 0
3967 && ( $this->ot
['html']
3969 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3972 # No match in frame, use the supplied default
3973 $object = $parts->item( 0 )->getChildren();
3975 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3976 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3977 $this->limitationWarn( 'post-expand-template-argument' );
3980 if ( $text === false && $object === false ) {
3982 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3984 if ( $error !== false ) {
3987 if ( $object !== false ) {
3988 $ret = [ 'object' => $object ];
3990 $ret = [ 'text' => $text ];
3997 * Return the text to be used for a given extension tag.
3998 * This is the ghost of strip().
4000 * @param array $params Associative array of parameters:
4001 * name PPNode for the tag name
4002 * attr PPNode for unparsed text where tag attributes are thought to be
4003 * attributes Optional associative array of parsed attributes
4004 * inner Contents of extension element
4005 * noClose Original text did not have a close tag
4006 * @param PPFrame $frame
4008 * @throws MWException
4011 public function extensionSubstitution( $params, $frame ) {
4012 static $errorStr = '<span class="error">';
4013 static $errorLen = 20;
4015 $name = $frame->expand( $params['name'] );
4016 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
4017 // Probably expansion depth or node count exceeded. Just punt the
4022 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4023 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
4028 // We can't safely check if the expansion for $content resulted in an
4029 // error, because the content could happen to be the error string
4031 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4033 $marker = self
::MARKER_PREFIX
. "-$name-"
4034 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4036 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4037 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4038 if ( $isFunctionTag ) {
4039 $markerType = 'none';
4041 $markerType = 'general';
4043 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4044 $name = strtolower( $name );
4045 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4046 if ( isset( $params['attributes'] ) ) {
4047 $attributes +
= $params['attributes'];
4050 if ( isset( $this->mTagHooks
[$name] ) ) {
4051 $output = call_user_func_array( $this->mTagHooks
[$name],
4052 [ $content, $attributes, $this, $frame ] );
4053 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4054 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4056 // Avoid PHP 7.1 warning from passing $this by reference
4058 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
4060 $output = '<span class="error">Invalid tag extension name: ' .
4061 htmlspecialchars( $name ) . '</span>';
4064 if ( is_array( $output ) ) {
4067 $output = $flags[0];
4068 if ( isset( $flags['markerType'] ) ) {
4069 $markerType = $flags['markerType'];
4073 if ( is_null( $attrText ) ) {
4076 if ( isset( $params['attributes'] ) ) {
4077 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4078 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4079 htmlspecialchars( $attrValue ) . '"';
4082 if ( $content === null ) {
4083 $output = "<$name$attrText/>";
4085 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4086 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4090 $output = "<$name$attrText>$content$close";
4094 if ( $markerType === 'none' ) {
4096 } elseif ( $markerType === 'nowiki' ) {
4097 $this->mStripState
->addNoWiki( $marker, $output );
4098 } elseif ( $markerType === 'general' ) {
4099 $this->mStripState
->addGeneral( $marker, $output );
4101 throw new MWException( __METHOD__
. ': invalid marker type' );
4107 * Increment an include size counter
4109 * @param string $type The type of expansion
4110 * @param int $size The size of the text
4111 * @return bool False if this inclusion would take it over the maximum, true otherwise
4113 public function incrementIncludeSize( $type, $size ) {
4114 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4117 $this->mIncludeSizes
[$type] +
= $size;
4123 * Increment the expensive function count
4125 * @return bool False if the limit has been exceeded
4127 public function incrementExpensiveFunctionCount() {
4128 $this->mExpensiveFunctionCount++
;
4129 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4133 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4134 * Fills $this->mDoubleUnderscores, returns the modified text
4136 * @param string $text
4140 public function doDoubleUnderscore( $text ) {
4141 # The position of __TOC__ needs to be recorded
4142 $mw = $this->magicWordFactory
->get( 'toc' );
4143 if ( $mw->match( $text ) ) {
4144 $this->mShowToc
= true;
4145 $this->mForceTocPosition
= true;
4147 # Set a placeholder. At the end we'll fill it in with the TOC.
4148 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4150 # Only keep the first one.
4151 $text = $mw->replace( '', $text );
4154 # Now match and remove the rest of them
4155 $mwa = $this->magicWordFactory
->getDoubleUnderscoreArray();
4156 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4158 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4159 $this->mOutput
->mNoGallery
= true;
4161 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4162 $this->mShowToc
= false;
4164 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4165 && $this->mTitle
->getNamespace() == NS_CATEGORY
4167 $this->addTrackingCategory( 'hidden-category-category' );
4169 # (T10068) Allow control over whether robots index a page.
4170 # __INDEX__ always overrides __NOINDEX__, see T16899
4171 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4172 $this->mOutput
->setIndexPolicy( 'noindex' );
4173 $this->addTrackingCategory( 'noindex-category' );
4175 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4176 $this->mOutput
->setIndexPolicy( 'index' );
4177 $this->addTrackingCategory( 'index-category' );
4180 # Cache all double underscores in the database
4181 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4182 $this->mOutput
->setProperty( $key, '' );
4189 * @see ParserOutput::addTrackingCategory()
4190 * @param string $msg Message key
4191 * @return bool Whether the addition was successful
4193 public function addTrackingCategory( $msg ) {
4194 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4198 * This function accomplishes several tasks:
4199 * 1) Auto-number headings if that option is enabled
4200 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4201 * 3) Add a Table of contents on the top for users who have enabled the option
4202 * 4) Auto-anchor headings
4204 * It loops through all headlines, collects the necessary data, then splits up the
4205 * string and re-inserts the newly formatted headlines.
4207 * @param string $text
4208 * @param string $origText Original, untouched wikitext
4209 * @param bool $isMain
4210 * @return mixed|string
4213 public function formatHeadings( $text, $origText, $isMain = true ) {
4214 # Inhibit editsection links if requested in the page
4215 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4216 $maybeShowEditLink = false;
4218 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4221 # Get all headlines for numbering them and adding funky stuff like [edit]
4222 # links - this is for later, but we need the number of headlines right now
4223 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4224 # be trimmed here since whitespace in HTML headings is significant.
4226 $numMatches = preg_match_all(
4227 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4232 # if there are fewer than 4 headlines in the article, do not show TOC
4233 # unless it's been explicitly enabled.
4234 $enoughToc = $this->mShowToc
&&
4235 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4237 # Allow user to stipulate that a page should have a "new section"
4238 # link added via __NEWSECTIONLINK__
4239 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4240 $this->mOutput
->setNewSection( true );
4243 # Allow user to remove the "new section"
4244 # link via __NONEWSECTIONLINK__
4245 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4246 $this->mOutput
->hideNewSection( true );
4249 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4250 # override above conditions and always show TOC above first header
4251 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4252 $this->mShowToc
= true;
4260 # Ugh .. the TOC should have neat indentation levels which can be
4261 # passed to the skin functions. These are determined here
4265 $sublevelCount = [];
4271 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4272 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4273 $oldType = $this->mOutputType
;
4274 $this->setOutputType( self
::OT_WIKI
);
4275 $frame = $this->getPreprocessor()->newFrame();
4276 $root = $this->preprocessToDom( $origText );
4277 $node = $root->getFirstChild();
4282 $headlines = $numMatches !== false ?
$matches[3] : [];
4284 $maxTocLevel = $this->svcOptions
->get( 'MaxTocLevel' );
4285 foreach ( $headlines as $headline ) {
4286 $isTemplate = false;
4288 $sectionIndex = false;
4290 $markerMatches = [];
4291 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4292 $serial = $markerMatches[1];
4293 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4294 $isTemplate = ( $titleText != $baseTitleText );
4295 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4299 $prevlevel = $level;
4301 $level = $matches[1][$headlineCount];
4303 if ( $level > $prevlevel ) {
4304 # Increase TOC level
4306 $sublevelCount[$toclevel] = 0;
4307 if ( $toclevel < $maxTocLevel ) {
4308 $prevtoclevel = $toclevel;
4309 $toc .= Linker
::tocIndent();
4312 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4313 # Decrease TOC level, find level to jump to
4315 for ( $i = $toclevel; $i > 0; $i-- ) {
4316 if ( $levelCount[$i] == $level ) {
4317 # Found last matching level
4320 } elseif ( $levelCount[$i] < $level ) {
4321 # Found first matching level below current level
4329 if ( $toclevel < $maxTocLevel ) {
4330 if ( $prevtoclevel < $maxTocLevel ) {
4331 # Unindent only if the previous toc level was shown :p
4332 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4333 $prevtoclevel = $toclevel;
4335 $toc .= Linker
::tocLineEnd();
4339 # No change in level, end TOC line
4340 if ( $toclevel < $maxTocLevel ) {
4341 $toc .= Linker
::tocLineEnd();
4345 $levelCount[$toclevel] = $level;
4347 # count number of headlines for each level
4348 $sublevelCount[$toclevel]++
;
4350 for ( $i = 1; $i <= $toclevel; $i++
) {
4351 if ( !empty( $sublevelCount[$i] ) ) {
4355 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4360 # The safe header is a version of the header text safe to use for links
4362 # Remove link placeholders by the link text.
4363 # <!--LINK number-->
4365 # link text with suffix
4366 # Do this before unstrip since link text can contain strip markers
4367 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4369 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4370 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4372 # Remove any <style> or <script> tags (T198618)
4373 $safeHeadline = preg_replace(
4374 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4379 # Strip out HTML (first regex removes any tag not allowed)
4381 # * <sup> and <sub> (T10393)
4385 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4386 # * <s> and <strike> (T35715)
4387 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4388 # to allow setting directionality in toc items.
4389 $tocline = preg_replace(
4391 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4392 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4398 # Strip '<span></span>', which is the result from the above if
4399 # <span id="foo"></span> is used to produce an additional anchor
4401 $tocline = str_replace( '<span></span>', '', $tocline );
4403 $tocline = trim( $tocline );
4405 # For the anchor, strip out HTML-y stuff period
4406 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4407 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4409 # Save headline for section edit hint before it's escaped
4410 $headlineHint = $safeHeadline;
4412 # Decode HTML entities
4413 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4415 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4417 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4418 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4419 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4420 if ( $fallbackHeadline === $safeHeadline ) {
4421 # No reason to have both (in fact, we can't)
4422 $fallbackHeadline = false;
4425 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4426 # @todo FIXME: We may be changing them depending on the current locale.
4427 $arrayKey = strtolower( $safeHeadline );
4428 if ( $fallbackHeadline === false ) {
4429 $fallbackArrayKey = false;
4431 $fallbackArrayKey = strtolower( $fallbackHeadline );
4434 # Create the anchor for linking from the TOC to the section
4435 $anchor = $safeHeadline;
4436 $fallbackAnchor = $fallbackHeadline;
4437 if ( isset( $refers[$arrayKey] ) ) {
4438 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4439 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4441 $linkAnchor .= "_$i";
4442 $refers["${arrayKey}_$i"] = true;
4444 $refers[$arrayKey] = true;
4446 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4447 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4448 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4449 $fallbackAnchor .= "_$i";
4450 $refers["${fallbackArrayKey}_$i"] = true;
4452 $refers[$fallbackArrayKey] = true;
4455 # Don't number the heading if it is the only one (looks silly)
4456 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4457 # the two are different if the line contains a link
4458 $headline = Html
::element(
4460 [ 'class' => 'mw-headline-number' ],
4462 ) . ' ' . $headline;
4465 if ( $enoughToc && ( !isset( $maxTocLevel ) ||
$toclevel < $maxTocLevel ) ) {
4466 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4467 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4470 # Add the section to the section tree
4471 # Find the DOM node for this header
4472 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4473 while ( $node && !$noOffset ) {
4474 if ( $node->getName() === 'h' ) {
4475 $bits = $node->splitHeading();
4476 if ( $bits['i'] == $sectionIndex ) {
4480 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4481 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4482 $node = $node->getNextSibling();
4485 'toclevel' => $toclevel,
4488 'number' => $numbering,
4489 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4490 'fromtitle' => $titleText,
4491 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4492 'anchor' => $anchor,
4495 # give headline the correct <h#> tag
4496 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4497 // Output edit section links as markers with styles that can be customized by skins
4498 if ( $isTemplate ) {
4499 # Put a T flag in the section identifier, to indicate to extractSections()
4500 # that sections inside <includeonly> should be counted.
4501 $editsectionPage = $titleText;
4502 $editsectionSection = "T-$sectionIndex";
4503 $editsectionContent = null;
4505 $editsectionPage = $this->mTitle
->getPrefixedText();
4506 $editsectionSection = $sectionIndex;
4507 $editsectionContent = $headlineHint;
4509 // We use a bit of pesudo-xml for editsection markers. The
4510 // language converter is run later on. Using a UNIQ style marker
4511 // leads to the converter screwing up the tokens when it
4512 // converts stuff. And trying to insert strip tags fails too. At
4513 // this point all real inputted tags have already been escaped,
4514 // so we don't have to worry about a user trying to input one of
4515 // these markers directly. We use a page and section attribute
4516 // to stop the language converter from converting these
4517 // important bits of data, but put the headline hint inside a
4518 // content block because the language converter is supposed to
4519 // be able to convert that piece of data.
4520 // Gets replaced with html in ParserOutput::getText
4521 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4522 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4523 if ( $editsectionContent !== null ) {
4524 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4531 $head[$headlineCount] = Linker
::makeHeadline( $level,
4532 $matches['attrib'][$headlineCount], $anchor, $headline,
4533 $editlink, $fallbackAnchor );
4538 $this->setOutputType( $oldType );
4540 # Never ever show TOC if no headers
4541 if ( $numVisible < 1 ) {
4546 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4547 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4549 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4550 $this->mOutput
->setTOCHTML( $toc );
4551 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4555 $this->mOutput
->setSections( $tocraw );
4558 # split up and insert constructed headlines
4559 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4562 // build an array of document sections
4564 foreach ( $blocks as $block ) {
4565 // $head is zero-based, sections aren't.
4566 if ( empty( $head[$i - 1] ) ) {
4567 $sections[$i] = $block;
4569 $sections[$i] = $head[$i - 1] . $block;
4573 * Send a hook, one per section.
4574 * The idea here is to be able to make section-level DIVs, but to do so in a
4575 * lower-impact, more correct way than r50769
4578 * $section : the section number
4579 * &$sectionContent : ref to the content of the section
4580 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4582 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4587 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4588 // append the TOC at the beginning
4589 // Top anchor now in skin
4590 $sections[0] .= $toc . "\n";
4593 $full .= implode( '', $sections );
4595 if ( $this->mForceTocPosition
) {
4596 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4603 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4604 * conversion, substituting signatures, {{subst:}} templates, etc.
4606 * @param string $text The text to transform
4607 * @param Title $title The Title object for the current article
4608 * @param User $user The User object describing the current user
4609 * @param ParserOptions $options Parsing options
4610 * @param bool $clearState Whether to clear the parser state first
4611 * @return string The altered wiki markup
4613 public function preSaveTransform( $text, Title
$title, User
$user,
4614 ParserOptions
$options, $clearState = true
4616 if ( $clearState ) {
4617 $magicScopeVariable = $this->lock();
4619 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4620 $this->setUser( $user );
4622 // Strip U+0000 NULL (T159174)
4623 $text = str_replace( "\000", '', $text );
4625 // We still normalize line endings for backwards-compatibility
4626 // with other code that just calls PST, but this should already
4627 // be handled in TextContent subclasses
4628 $text = TextContent
::normalizeLineEndings( $text );
4630 if ( $options->getPreSaveTransform() ) {
4631 $text = $this->pstPass2( $text, $user );
4633 $text = $this->mStripState
->unstripBoth( $text );
4635 $this->setUser( null ); # Reset
4641 * Pre-save transform helper function
4643 * @param string $text
4648 private function pstPass2( $text, $user ) {
4649 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4650 # $this->contLang here in order to give everyone the same signature and use the default one
4651 # rather than the one selected in each user's preferences. (see also T14815)
4652 $ts = $this->mOptions
->getTimestamp();
4653 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4654 $ts = $timestamp->format( 'YmdHis' );
4655 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4657 $d = $this->contLang
->timeanddate( $ts, false, false ) . " ($tzMsg)";
4659 # Variable replacement
4660 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4661 $text = $this->replaceVariables( $text );
4663 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4664 # which may corrupt this parser instance via its wfMessage()->text() call-
4667 if ( strpos( $text, '~~~' ) !== false ) {
4668 $sigText = $this->getUserSig( $user );
4669 $text = strtr( $text, [
4671 '~~~~' => "$sigText $d",
4674 # The main two signature forms used above are time-sensitive
4675 $this->mOutput
->setFlag( 'user-signature' );
4678 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4679 $tc = '[' . Title
::legalChars() . ']';
4680 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4682 // [[ns:page (context)|]]
4683 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4684 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4685 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4686 // [[ns:page (context), context|]] (using either single or double-width comma)
4687 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4688 // [[|page]] (reverse pipe trick: add context from page title)
4689 $p2 = "/\[\[\\|($tc+)]]/";
4691 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4692 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4693 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4694 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4696 $t = $this->mTitle
->getText();
4698 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4699 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4700 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4701 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4703 # if there's no context, don't bother duplicating the title
4704 $text = preg_replace( $p2, '[[\\1]]', $text );
4711 * Fetch the user's signature text, if any, and normalize to
4712 * validated, ready-to-insert wikitext.
4713 * If you have pre-fetched the nickname or the fancySig option, you can
4714 * specify them here to save a database query.
4715 * Do not reuse this parser instance after calling getUserSig(),
4716 * as it may have changed.
4718 * @param User &$user
4719 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4720 * @param bool|null $fancySig whether the nicknname is the complete signature
4721 * or null to use default value
4724 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4725 $username = $user->getName();
4727 # If not given, retrieve from the user object.
4728 if ( $nickname === false ) {
4729 $nickname = $user->getOption( 'nickname' );
4732 if ( is_null( $fancySig ) ) {
4733 $fancySig = $user->getBoolOption( 'fancysig' );
4736 $nickname = $nickname == null ?
$username : $nickname;
4738 if ( mb_strlen( $nickname ) > $this->svcOptions
->get( 'MaxSigChars' ) ) {
4739 $nickname = $username;
4740 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4741 } elseif ( $fancySig !== false ) {
4742 # Sig. might contain markup; validate this
4743 if ( $this->validateSig( $nickname ) !== false ) {
4744 # Validated; clean up (if needed) and return it
4745 return $this->cleanSig( $nickname, true );
4747 # Failed to validate; fall back to the default
4748 $nickname = $username;
4749 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4753 # Make sure nickname doesnt get a sig in a sig
4754 $nickname = self
::cleanSigInSig( $nickname );
4756 # If we're still here, make it a link to the user page
4757 $userText = wfEscapeWikiText( $username );
4758 $nickText = wfEscapeWikiText( $nickname );
4759 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4761 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4762 ->title( $this->getTitle() )->text();
4766 * Check that the user's signature contains no bad XML
4768 * @param string $text
4769 * @return string|bool An expanded string, or false if invalid.
4771 public function validateSig( $text ) {
4772 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4776 * Clean up signature text
4778 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4779 * 2) Substitute all transclusions
4781 * @param string $text
4782 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4783 * @return string Signature text
4785 public function cleanSig( $text, $parsing = false ) {
4788 $magicScopeVariable = $this->lock();
4789 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4792 # Option to disable this feature
4793 if ( !$this->mOptions
->getCleanSignatures() ) {
4797 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4798 # => Move this logic to braceSubstitution()
4799 $substWord = $this->magicWordFactory
->get( 'subst' );
4800 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4801 $substText = '{{' . $substWord->getSynonym( 0 );
4803 $text = preg_replace( $substRegex, $substText, $text );
4804 $text = self
::cleanSigInSig( $text );
4805 $dom = $this->preprocessToDom( $text );
4806 $frame = $this->getPreprocessor()->newFrame();
4807 $text = $frame->expand( $dom );
4810 $text = $this->mStripState
->unstripBoth( $text );
4817 * Strip 3, 4 or 5 tildes out of signatures.
4819 * @param string $text
4820 * @return string Signature text with /~{3,5}/ removed
4822 public static function cleanSigInSig( $text ) {
4823 $text = preg_replace( '/~{3,5}/', '', $text );
4828 * Set up some variables which are usually set up in parse()
4829 * so that an external function can call some class members with confidence
4831 * @param Title|null $title
4832 * @param ParserOptions $options
4833 * @param int $outputType
4834 * @param bool $clearState
4836 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4837 $outputType, $clearState = true
4839 $this->startParse( $title, $options, $outputType, $clearState );
4843 * @param Title|null $title
4844 * @param ParserOptions $options
4845 * @param int $outputType
4846 * @param bool $clearState
4848 private function startParse( Title
$title = null, ParserOptions
$options,
4849 $outputType, $clearState = true
4851 $this->setTitle( $title );
4852 $this->mOptions
= $options;
4853 $this->setOutputType( $outputType );
4854 if ( $clearState ) {
4855 $this->clearState();
4860 * Wrapper for preprocess()
4862 * @param string $text The text to preprocess
4863 * @param ParserOptions $options
4864 * @param Title|null $title Title object or null to use $wgTitle
4867 public function transformMsg( $text, $options, $title = null ) {
4868 static $executing = false;
4870 # Guard against infinite recursion
4881 $text = $this->preprocess( $text, $title, $options );
4888 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4889 * The callback should have the following form:
4890 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4892 * Transform and return $text. Use $parser for any required context, e.g. use
4893 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4895 * Hooks may return extended information by returning an array, of which the
4896 * first numbered element (index 0) must be the return string, and all other
4897 * entries are extracted into local variables within an internal function
4898 * in the Parser class.
4900 * This interface (introduced r61913) appears to be undocumented, but
4901 * 'markerType' is used by some core tag hooks to override which strip
4902 * array their results are placed in. **Use great caution if attempting
4903 * this interface, as it is not documented and injudicious use could smash
4904 * private variables.**
4906 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4907 * @param callable $callback The callback function (and object) to use for the tag
4908 * @throws MWException
4909 * @return callable|null The old value of the mTagHooks array associated with the hook
4911 public function setHook( $tag, callable
$callback ) {
4912 $tag = strtolower( $tag );
4913 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4914 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4916 $oldVal = $this->mTagHooks
[$tag] ??
null;
4917 $this->mTagHooks
[$tag] = $callback;
4918 if ( !in_array( $tag, $this->mStripList
) ) {
4919 $this->mStripList
[] = $tag;
4926 * As setHook(), but letting the contents be parsed.
4928 * Transparent tag hooks are like regular XML-style tag hooks, except they
4929 * operate late in the transformation sequence, on HTML instead of wikitext.
4931 * This is probably obsoleted by things dealing with parser frames?
4932 * The only extension currently using it is geoserver.
4935 * @todo better document or deprecate this
4937 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4938 * @param callable $callback The callback function (and object) to use for the tag
4939 * @throws MWException
4940 * @return callable|null The old value of the mTagHooks array associated with the hook
4942 public function setTransparentTagHook( $tag, callable
$callback ) {
4943 $tag = strtolower( $tag );
4944 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4945 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4947 $oldVal = $this->mTransparentTagHooks
[$tag] ??
null;
4948 $this->mTransparentTagHooks
[$tag] = $callback;
4954 * Remove all tag hooks
4956 public function clearTagHooks() {
4957 $this->mTagHooks
= [];
4958 $this->mFunctionTagHooks
= [];
4959 $this->mStripList
= $this->mDefaultStripList
;
4963 * Create a function, e.g. {{sum:1|2|3}}
4964 * The callback function should have the form:
4965 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4967 * Or with Parser::SFH_OBJECT_ARGS:
4968 * function myParserFunction( $parser, $frame, $args ) { ... }
4970 * The callback may either return the text result of the function, or an array with the text
4971 * in element 0, and a number of flags in the other elements. The names of the flags are
4972 * specified in the keys. Valid flags are:
4973 * found The text returned is valid, stop processing the template. This
4975 * nowiki Wiki markup in the return value should be escaped
4976 * isHTML The returned text is HTML, armour it against wikitext transformation
4978 * @param string $id The magic word ID
4979 * @param callable $callback The callback function (and object) to use
4980 * @param int $flags A combination of the following flags:
4981 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4983 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4984 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4985 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4986 * the arguments, and to control the way they are expanded.
4988 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4989 * arguments, for instance:
4990 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4992 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4993 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4994 * working if/when this is changed.
4996 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4999 * Please read the documentation in includes/parser/Preprocessor.php for more information
5000 * about the methods available in PPFrame and PPNode.
5002 * @throws MWException
5003 * @return string|callable The old callback function for this name, if any
5005 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
5006 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5007 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
5009 # Add to function cache
5010 $mw = $this->magicWordFactory
->get( $id );
5012 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5015 $synonyms = $mw->getSynonyms();
5016 $sensitive = intval( $mw->isCaseSensitive() );
5018 foreach ( $synonyms as $syn ) {
5020 if ( !$sensitive ) {
5021 $syn = $this->contLang
->lc( $syn );
5024 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5027 # Remove trailing colon
5028 if ( substr( $syn, -1, 1 ) === ':' ) {
5029 $syn = substr( $syn, 0, -1 );
5031 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5037 * Get all registered function hook identifiers
5041 public function getFunctionHooks() {
5042 $this->firstCallInit();
5043 return array_keys( $this->mFunctionHooks
);
5047 * Create a tag function, e.g. "<test>some stuff</test>".
5048 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5049 * Unlike parser functions, their content is not preprocessed.
5050 * @param string $tag
5051 * @param callable $callback
5053 * @throws MWException
5056 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
5057 $tag = strtolower( $tag );
5058 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5059 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5061 $old = $this->mFunctionTagHooks
[$tag] ??
null;
5062 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
5064 if ( !in_array( $tag, $this->mStripList
) ) {
5065 $this->mStripList
[] = $tag;
5072 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5073 * Placeholders created in Linker::link()
5075 * @param string &$text
5076 * @param int $options
5078 public function replaceLinkHolders( &$text, $options = 0 ) {
5079 $this->mLinkHolders
->replace( $text );
5083 * Replace "<!--LINK-->" link placeholders with plain text of links
5084 * (not HTML-formatted).
5086 * @param string $text
5089 public function replaceLinkHoldersText( $text ) {
5090 return $this->mLinkHolders
->replaceText( $text );
5094 * Renders an image gallery from a text with one line per image.
5095 * text labels may be given by using |-style alternative text. E.g.
5096 * Image:one.jpg|The number "1"
5097 * Image:tree.jpg|A tree
5098 * given as text will return the HTML of a gallery with two images,
5099 * labeled 'The number "1"' and
5102 * @param string $text
5103 * @param array $params
5104 * @return string HTML
5106 public function renderImageGallery( $text, $params ) {
5108 if ( isset( $params['mode'] ) ) {
5109 $mode = $params['mode'];
5113 $ig = ImageGalleryBase
::factory( $mode );
5114 } catch ( Exception
$e ) {
5115 // If invalid type set, fallback to default.
5116 $ig = ImageGalleryBase
::factory( false );
5119 $ig->setContextTitle( $this->mTitle
);
5120 $ig->setShowBytes( false );
5121 $ig->setShowDimensions( false );
5122 $ig->setShowFilename( false );
5123 $ig->setParser( $this );
5124 $ig->setHideBadImages();
5125 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
5127 if ( isset( $params['showfilename'] ) ) {
5128 $ig->setShowFilename( true );
5130 $ig->setShowFilename( false );
5132 if ( isset( $params['caption'] ) ) {
5133 // NOTE: We aren't passing a frame here or below. Frame info
5134 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5135 // See T107332#4030581
5136 $caption = $this->recursiveTagParse( $params['caption'] );
5137 $ig->setCaptionHtml( $caption );
5139 if ( isset( $params['perrow'] ) ) {
5140 $ig->setPerRow( $params['perrow'] );
5142 if ( isset( $params['widths'] ) ) {
5143 $ig->setWidths( $params['widths'] );
5145 if ( isset( $params['heights'] ) ) {
5146 $ig->setHeights( $params['heights'] );
5148 $ig->setAdditionalOptions( $params );
5150 // Avoid PHP 7.1 warning from passing $this by reference
5152 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5154 $lines = StringUtils
::explode( "\n", $text );
5155 foreach ( $lines as $line ) {
5156 # match lines like these:
5157 # Image:someimage.jpg|This is some image
5159 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5161 if ( count( $matches ) == 0 ) {
5165 if ( strpos( $matches[0], '%' ) !== false ) {
5166 $matches[1] = rawurldecode( $matches[1] );
5168 $title = Title
::newFromText( $matches[1], NS_FILE
);
5169 if ( is_null( $title ) ) {
5170 # Bogus title. Ignore these so we don't bomb out later.
5174 # We need to get what handler the file uses, to figure out parameters.
5175 # Note, a hook can overide the file name, and chose an entirely different
5176 # file (which potentially could be of a different type and have different handler).
5179 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5180 [ $this, $title, &$options, &$descQuery ] );
5181 # Don't register it now, as TraditionalImageGallery does that later.
5182 $file = $this->fetchFileNoRegister( $title, $options );
5183 $handler = $file ?
$file->getHandler() : false;
5186 'img_alt' => 'gallery-internal-alt',
5187 'img_link' => 'gallery-internal-link',
5190 $paramMap +
= $handler->getParamMap();
5191 // We don't want people to specify per-image widths.
5192 // Additionally the width parameter would need special casing anyhow.
5193 unset( $paramMap['img_width'] );
5196 $mwArray = $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5201 $handlerOptions = [];
5202 if ( isset( $matches[3] ) ) {
5203 // look for an |alt= definition while trying not to break existing
5204 // captions with multiple pipes (|) in it, until a more sensible grammar
5205 // is defined for images in galleries
5207 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5208 // splitting on '|' is a bit odd, and different from makeImage.
5209 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5210 // Protect LanguageConverter markup
5211 $parameterMatches = StringUtils
::delimiterExplode(
5212 '-{', '}-', '|', $matches[3], true /* nested */
5215 foreach ( $parameterMatches as $parameterMatch ) {
5216 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5218 $paramName = $paramMap[$magicName];
5220 switch ( $paramName ) {
5221 case 'gallery-internal-alt':
5222 $alt = $this->stripAltText( $match, false );
5224 case 'gallery-internal-link':
5225 $linkValue = $this->stripAltText( $match, false );
5226 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5227 // Result of LanguageConverter::markNoConversion
5228 // invoked on an external link.
5229 $linkValue = substr( $linkValue, 4, -2 );
5231 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5232 if ( $type === 'link-url' ) {
5234 $this->mOutput
->addExternalLink( $target );
5235 } elseif ( $type === 'link-title' ) {
5236 $link = $target->getLinkURL();
5237 $this->mOutput
->addLink( $target );
5241 // Must be a handler specific parameter.
5242 if ( $handler->validateParam( $paramName, $match ) ) {
5243 $handlerOptions[$paramName] = $match;
5245 // Guess not, consider it as caption.
5246 wfDebug( "$parameterMatch failed parameter validation\n" );
5247 $label = $parameterMatch;
5253 $label = $parameterMatch;
5258 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5260 $html = $ig->toHTML();
5261 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5266 * @param MediaHandler $handler
5269 public function getImageParams( $handler ) {
5271 $handlerClass = get_class( $handler );
5275 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5276 # Initialise static lists
5277 static $internalParamNames = [
5278 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5279 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5280 'bottom', 'text-bottom' ],
5281 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5282 'upright', 'border', 'link', 'alt', 'class' ],
5284 static $internalParamMap;
5285 if ( !$internalParamMap ) {
5286 $internalParamMap = [];
5287 foreach ( $internalParamNames as $type => $names ) {
5288 foreach ( $names as $name ) {
5289 // For grep: img_left, img_right, img_center, img_none,
5290 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5291 // img_bottom, img_text_bottom,
5292 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5293 // img_border, img_link, img_alt, img_class
5294 $magicName = str_replace( '-', '_', "img_$name" );
5295 $internalParamMap[$magicName] = [ $type, $name ];
5300 # Add handler params
5301 $paramMap = $internalParamMap;
5303 $handlerParamMap = $handler->getParamMap();
5304 foreach ( $handlerParamMap as $magic => $paramName ) {
5305 $paramMap[$magic] = [ 'handler', $paramName ];
5308 $this->mImageParams
[$handlerClass] = $paramMap;
5309 $this->mImageParamsMagicArray
[$handlerClass] =
5310 $this->magicWordFactory
->newArray( array_keys( $paramMap ) );
5312 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5316 * Parse image options text and use it to make an image
5318 * @param Title $title
5319 * @param string $options
5320 * @param LinkHolderArray|bool $holders
5321 * @return string HTML
5323 public function makeImage( $title, $options, $holders = false ) {
5324 # Check if the options text is of the form "options|alt text"
5326 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5327 # * left no resizing, just left align. label is used for alt= only
5328 # * right same, but right aligned
5329 # * none same, but not aligned
5330 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5331 # * center center the image
5332 # * frame Keep original image size, no magnify-button.
5333 # * framed Same as "frame"
5334 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5335 # * upright reduce width for upright images, rounded to full __0 px
5336 # * border draw a 1px border around the image
5337 # * alt Text for HTML alt attribute (defaults to empty)
5338 # * class Set a class for img node
5339 # * link Set the target of the image link. Can be external, interwiki, or local
5340 # vertical-align values (no % or length right now):
5350 # Protect LanguageConverter markup when splitting into parts
5351 $parts = StringUtils
::delimiterExplode(
5352 '-{', '}-', '|', $options, true /* allow nesting */
5355 # Give extensions a chance to select the file revision for us
5358 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5359 [ $this, $title, &$options, &$descQuery ] );
5360 # Fetch and register the file (file title may be different via hooks)
5361 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5364 $handler = $file ?
$file->getHandler() : false;
5366 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5369 $this->addTrackingCategory( 'broken-file-category' );
5372 # Process the input parameters
5374 $params = [ 'frame' => [], 'handler' => [],
5375 'horizAlign' => [], 'vertAlign' => [] ];
5376 $seenformat = false;
5377 foreach ( $parts as $part ) {
5378 $part = trim( $part );
5379 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5381 if ( isset( $paramMap[$magicName] ) ) {
5382 list( $type, $paramName ) = $paramMap[$magicName];
5384 # Special case; width and height come in one variable together
5385 if ( $type === 'handler' && $paramName === 'width' ) {
5386 $parsedWidthParam = self
::parseWidthParam( $value );
5387 if ( isset( $parsedWidthParam['width'] ) ) {
5388 $width = $parsedWidthParam['width'];
5389 if ( $handler->validateParam( 'width', $width ) ) {
5390 $params[$type]['width'] = $width;
5394 if ( isset( $parsedWidthParam['height'] ) ) {
5395 $height = $parsedWidthParam['height'];
5396 if ( $handler->validateParam( 'height', $height ) ) {
5397 $params[$type]['height'] = $height;
5401 # else no validation -- T15436
5403 if ( $type === 'handler' ) {
5404 # Validate handler parameter
5405 $validated = $handler->validateParam( $paramName, $value );
5407 # Validate internal parameters
5408 switch ( $paramName ) {
5412 # @todo FIXME: Possibly check validity here for
5413 # manualthumb? downstream behavior seems odd with
5414 # missing manual thumbs.
5416 $value = $this->stripAltText( $value, $holders );
5419 list( $paramName, $value ) =
5420 $this->parseLinkParameter(
5421 $this->stripAltText( $value, $holders )
5425 if ( $paramName === 'no-link' ) {
5428 if ( ( $paramName === 'link-url' ) && $this->mOptions
->getExternalLinkTarget() ) {
5429 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5436 // use first appearing option, discard others.
5437 $validated = !$seenformat;
5441 # Most other things appear to be empty or numeric...
5442 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5447 $params[$type][$paramName] = $value;
5451 if ( !$validated ) {
5456 # Process alignment parameters
5457 if ( $params['horizAlign'] ) {
5458 $params['frame']['align'] = key( $params['horizAlign'] );
5460 if ( $params['vertAlign'] ) {
5461 $params['frame']['valign'] = key( $params['vertAlign'] );
5464 $params['frame']['caption'] = $caption;
5466 # Will the image be presented in a frame, with the caption below?
5467 $imageIsFramed = isset( $params['frame']['frame'] )
5468 ||
isset( $params['frame']['framed'] )
5469 ||
isset( $params['frame']['thumbnail'] )
5470 ||
isset( $params['frame']['manualthumb'] );
5472 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5473 # came to also set the caption, ordinary text after the image -- which
5474 # makes no sense, because that just repeats the text multiple times in
5475 # screen readers. It *also* came to set the title attribute.
5476 # Now that we have an alt attribute, we should not set the alt text to
5477 # equal the caption: that's worse than useless, it just repeats the
5478 # text. This is the framed/thumbnail case. If there's no caption, we
5479 # use the unnamed parameter for alt text as well, just for the time be-
5480 # ing, if the unnamed param is set and the alt param is not.
5481 # For the future, we need to figure out if we want to tweak this more,
5482 # e.g., introducing a title= parameter for the title; ignoring the un-
5483 # named parameter entirely for images without a caption; adding an ex-
5484 # plicit caption= parameter and preserving the old magic unnamed para-
5486 if ( $imageIsFramed ) { # Framed image
5487 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5488 # No caption or alt text, add the filename as the alt text so
5489 # that screen readers at least get some description of the image
5490 $params['frame']['alt'] = $title->getText();
5492 # Do not set $params['frame']['title'] because tooltips don't make sense
5494 } else { # Inline image
5495 if ( !isset( $params['frame']['alt'] ) ) {
5496 # No alt text, use the "caption" for the alt text
5497 if ( $caption !== '' ) {
5498 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5500 # No caption, fall back to using the filename for the
5502 $params['frame']['alt'] = $title->getText();
5505 # Use the "caption" for the tooltip text
5506 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5508 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5510 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5512 # Linker does the rest
5513 $time = $options['time'] ??
false;
5514 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5515 $time, $descQuery, $this->mOptions
->getThumbSize() );
5517 # Give the handler a chance to modify the parser object
5519 $handler->parserTransformHook( $this, $file );
5526 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5528 * Adds an entry to appropriate link tables.
5531 * @param string $value
5532 * @return array of `[ type, target ]`, where:
5533 * - `type` is one of:
5534 * - `null`: Given value is not a valid link target, use default
5535 * - `'no-link'`: Given value is empty, do not generate a link
5536 * - `'link-url'`: Given value is a valid external link
5537 * - `'link-title'`: Given value is a valid internal link
5539 * - When `type` is `null` or `'no-link'`: `false`
5540 * - When `type` is `'link-url'`: URL string corresponding to given value
5541 * - When `type` is `'link-title'`: Title object corresponding to given value
5543 public function parseLinkParameter( $value ) {
5544 $chars = self
::EXT_LINK_URL_CLASS
;
5545 $addr = self
::EXT_LINK_ADDR
;
5546 $prots = $this->mUrlProtocols
;
5549 if ( $value === '' ) {
5551 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5552 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5553 $this->mOutput
->addExternalLink( $value );
5558 $linkTitle = Title
::newFromText( $value );
5560 $this->mOutput
->addLink( $linkTitle );
5561 $type = 'link-title';
5562 $target = $linkTitle;
5565 return [ $type, $target ];
5569 * @param string $caption
5570 * @param LinkHolderArray|bool $holders
5571 * @return mixed|string
5573 protected function stripAltText( $caption, $holders ) {
5574 # Strip bad stuff out of the title (tooltip). We can't just use
5575 # replaceLinkHoldersText() here, because if this function is called
5576 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5578 $tooltip = $holders->replaceText( $caption );
5580 $tooltip = $this->replaceLinkHoldersText( $caption );
5583 # make sure there are no placeholders in thumbnail attributes
5584 # that are later expanded to html- so expand them now and
5586 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5587 # Compatibility hack! In HTML certain entity references not terminated
5588 # by a semicolon are decoded (but not if we're in an attribute; that's
5589 # how link URLs get away without properly escaping & in queries).
5590 # But wikitext has always required semicolon-termination of entities,
5591 # so encode & where needed to avoid decode of semicolon-less entities.
5593 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5594 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5595 $tooltip = preg_replace( "/
5596 & # 1. entity prefix
5597 (?= # 2. followed by:
5598 (?: # a. one of the legacy semicolon-less named entities
5599 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5600 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5601 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5602 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5603 U(?:acute|circ|grave|uml)|Yacute|
5604 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5605 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5606 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5607 frac(?:1(?:2|4)|34)|
5608 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5609 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5610 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5611 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5612 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5613 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5614 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5615 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5616 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5618 (?:[^;]|$)) # b. and not followed by a semicolon
5619 # S = study, for efficiency
5620 /Sx", '&', $tooltip );
5621 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5627 * Set a flag in the output object indicating that the content is dynamic and
5628 * shouldn't be cached.
5629 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5631 public function disableCache() {
5632 wfDebug( "Parser output marked as uncacheable.\n" );
5633 if ( !$this->mOutput
) {
5634 throw new MWException( __METHOD__
.
5635 " can only be called when actually parsing something" );
5637 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5641 * Callback from the Sanitizer for expanding items found in HTML attribute
5642 * values, so they can be safely tested and escaped.
5644 * @param string &$text
5645 * @param bool|PPFrame $frame
5648 public function attributeStripCallback( &$text, $frame = false ) {
5649 $text = $this->replaceVariables( $text, $frame );
5650 $text = $this->mStripState
->unstripBoth( $text );
5659 public function getTags() {
5660 $this->firstCallInit();
5662 array_keys( $this->mTransparentTagHooks
),
5663 array_keys( $this->mTagHooks
),
5664 array_keys( $this->mFunctionTagHooks
)
5672 public function getFunctionSynonyms() {
5673 $this->firstCallInit();
5674 return $this->mFunctionSynonyms
;
5681 public function getUrlProtocols() {
5682 return $this->mUrlProtocols
;
5686 * Replace transparent tags in $text with the values given by the callbacks.
5688 * Transparent tag hooks are like regular XML-style tag hooks, except they
5689 * operate late in the transformation sequence, on HTML instead of wikitext.
5691 * @param string $text
5695 public function replaceTransparentTags( $text ) {
5697 $elements = array_keys( $this->mTransparentTagHooks
);
5698 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5701 foreach ( $matches as $marker => $data ) {
5702 list( $element, $content, $params, $tag ) = $data;
5703 $tagName = strtolower( $element );
5704 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5705 $output = call_user_func_array(
5706 $this->mTransparentTagHooks
[$tagName],
5707 [ $content, $params, $this ]
5712 $replacements[$marker] = $output;
5714 return strtr( $text, $replacements );
5718 * Break wikitext input into sections, and either pull or replace
5719 * some particular section's text.
5721 * External callers should use the getSection and replaceSection methods.
5723 * @param string $text Page wikitext
5724 * @param string|int $sectionId A section identifier string of the form:
5725 * "<flag1> - <flag2> - ... - <section number>"
5727 * Currently the only recognised flag is "T", which means the target section number
5728 * was derived during a template inclusion parse, in other words this is a template
5729 * section edit link. If no flags are given, it was an ordinary section edit link.
5730 * This flag is required to avoid a section numbering mismatch when a section is
5731 * enclosed by "<includeonly>" (T8563).
5733 * The section number 0 pulls the text before the first heading; other numbers will
5734 * pull the given section along with its lower-level subsections. If the section is
5735 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5737 * Section 0 is always considered to exist, even if it only contains the empty
5738 * string. If $text is the empty string and section 0 is replaced, $newText is
5741 * @param string $mode One of "get" or "replace"
5742 * @param string $newText Replacement text for section data.
5743 * @return string For "get", the extracted section text.
5744 * for "replace", the whole page with the section replaced.
5746 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5747 global $wgTitle; # not generally used but removes an ugly failure mode
5749 $magicScopeVariable = $this->lock();
5750 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5752 $frame = $this->getPreprocessor()->newFrame();
5754 # Process section extraction flags
5756 $sectionParts = explode( '-', $sectionId );
5757 $sectionIndex = array_pop( $sectionParts );
5758 foreach ( $sectionParts as $part ) {
5759 if ( $part === 'T' ) {
5760 $flags |
= self
::PTD_FOR_INCLUSION
;
5764 # Check for empty input
5765 if ( strval( $text ) === '' ) {
5766 # Only sections 0 and T-0 exist in an empty document
5767 if ( $sectionIndex == 0 ) {
5768 if ( $mode === 'get' ) {
5774 if ( $mode === 'get' ) {
5782 # Preprocess the text
5783 $root = $this->preprocessToDom( $text, $flags );
5785 # <h> nodes indicate section breaks
5786 # They can only occur at the top level, so we can find them by iterating the root's children
5787 $node = $root->getFirstChild();
5789 # Find the target section
5790 if ( $sectionIndex == 0 ) {
5791 # Section zero doesn't nest, level=big
5792 $targetLevel = 1000;
5795 if ( $node->getName() === 'h' ) {
5796 $bits = $node->splitHeading();
5797 if ( $bits['i'] == $sectionIndex ) {
5798 $targetLevel = $bits['level'];
5802 if ( $mode === 'replace' ) {
5803 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5805 $node = $node->getNextSibling();
5811 if ( $mode === 'get' ) {
5818 # Find the end of the section, including nested sections
5820 if ( $node->getName() === 'h' ) {
5821 $bits = $node->splitHeading();
5822 $curLevel = $bits['level'];
5823 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5827 if ( $mode === 'get' ) {
5828 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5830 $node = $node->getNextSibling();
5833 # Write out the remainder (in replace mode only)
5834 if ( $mode === 'replace' ) {
5835 # Output the replacement text
5836 # Add two newlines on -- trailing whitespace in $newText is conventionally
5837 # stripped by the editor, so we need both newlines to restore the paragraph gap
5838 # Only add trailing whitespace if there is newText
5839 if ( $newText != "" ) {
5840 $outText .= $newText . "\n\n";
5844 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5845 $node = $node->getNextSibling();
5849 if ( is_string( $outText ) ) {
5850 # Re-insert stripped tags
5851 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5858 * This function returns the text of a section, specified by a number ($section).
5859 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5860 * the first section before any such heading (section 0).
5862 * If a section contains subsections, these are also returned.
5864 * @param string $text Text to look in
5865 * @param string|int $sectionId Section identifier as a number or string
5866 * (e.g. 0, 1 or 'T-1').
5867 * @param string $defaultText Default to return if section is not found
5869 * @return string Text of the requested section
5871 public function getSection( $text, $sectionId, $defaultText = '' ) {
5872 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5876 * This function returns $oldtext after the content of the section
5877 * specified by $section has been replaced with $text. If the target
5878 * section does not exist, $oldtext is returned unchanged.
5880 * @param string $oldText Former text of the article
5881 * @param string|int $sectionId Section identifier as a number or string
5882 * (e.g. 0, 1 or 'T-1').
5883 * @param string $newText Replacing text
5885 * @return string Modified text
5887 public function replaceSection( $oldText, $sectionId, $newText ) {
5888 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5892 * Get the ID of the revision we are parsing
5894 * The return value will be either:
5895 * - a) Positive, indicating a specific revision ID (current or old)
5896 * - b) Zero, meaning the revision ID is specified by getCurrentRevisionCallback()
5897 * - c) Null, meaning the parse is for preview mode and there is no revision
5901 public function getRevisionId() {
5902 return $this->mRevisionId
;
5906 * Get the revision object for $this->mRevisionId
5908 * @return Revision|null Either a Revision object or null
5909 * @since 1.23 (public since 1.23)
5911 public function getRevisionObject() {
5912 if ( !is_null( $this->mRevisionObject
) ) {
5913 return $this->mRevisionObject
;
5916 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5917 // This is useful when parsing revision that has not yet been saved.
5918 // However, if we get back a saved revision even though we are in
5919 // preview mode, we'll have to ignore it, see below.
5920 // NOTE: This callback may be used to inject an OLD revision that was
5921 // already loaded, so "current" is a bit of a misnomer. We can't just
5922 // skip it if mRevisionId is set.
5923 $rev = call_user_func(
5924 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5927 if ( $this->mRevisionId
=== null && $rev && $rev->getId() ) {
5928 // We are in preview mode (mRevisionId is null), and the current revision callback
5929 // returned an existing revision. Ignore it and return null, it's probably the page's
5930 // current revision, which is not what we want here. Note that we do want to call the
5931 // callback to allow the unsaved revision to be injected here, e.g. for
5932 // self-transclusion previews.
5936 // If the parse is for a new revision, then the callback should have
5937 // already been set to force the object and should match mRevisionId.
5938 // If not, try to fetch by mRevisionId for sanity.
5939 if ( $this->mRevisionId
&& $rev && $rev->getId() != $this->mRevisionId
) {
5940 $rev = Revision
::newFromId( $this->mRevisionId
);
5943 $this->mRevisionObject
= $rev;
5945 return $this->mRevisionObject
;
5949 * Get the timestamp associated with the current revision, adjusted for
5950 * the default server-local timestamp
5951 * @return string TS_MW timestamp
5953 public function getRevisionTimestamp() {
5954 if ( $this->mRevisionTimestamp
!== null ) {
5955 return $this->mRevisionTimestamp
;
5958 # Use specified revision timestamp, falling back to the current timestamp
5959 $revObject = $this->getRevisionObject();
5960 $timestamp = $revObject ?
$revObject->getTimestamp() : $this->mOptions
->getTimestamp();
5961 $this->mOutput
->setRevisionTimestampUsed( $timestamp ); // unadjusted time zone
5963 # The cryptic '' timezone parameter tells to use the site-default
5964 # timezone offset instead of the user settings.
5965 # Since this value will be saved into the parser cache, served
5966 # to other users, and potentially even used inside links and such,
5967 # it needs to be consistent for all visitors.
5968 $this->mRevisionTimestamp
= $this->contLang
->userAdjust( $timestamp, '' );
5970 return $this->mRevisionTimestamp
;
5974 * Get the name of the user that edited the last revision
5976 * @return string User name
5978 public function getRevisionUser() {
5979 if ( is_null( $this->mRevisionUser
) ) {
5980 $revObject = $this->getRevisionObject();
5982 # if this template is subst: the revision id will be blank,
5983 # so just use the current user's name
5985 $this->mRevisionUser
= $revObject->getUserText();
5986 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5987 $this->mRevisionUser
= $this->getUser()->getName();
5990 return $this->mRevisionUser
;
5994 * Get the size of the revision
5996 * @return int|null Revision size
5998 public function getRevisionSize() {
5999 if ( is_null( $this->mRevisionSize
) ) {
6000 $revObject = $this->getRevisionObject();
6002 # if this variable is subst: the revision id will be blank,
6003 # so just use the parser input size, because the own substituation
6004 # will change the size.
6006 $this->mRevisionSize
= $revObject->getSize();
6008 $this->mRevisionSize
= $this->mInputSize
;
6011 return $this->mRevisionSize
;
6015 * Mutator for $mDefaultSort
6017 * @param string $sort New value
6019 public function setDefaultSort( $sort ) {
6020 $this->mDefaultSort
= $sort;
6021 $this->mOutput
->setProperty( 'defaultsort', $sort );
6025 * Accessor for $mDefaultSort
6026 * Will use the empty string if none is set.
6028 * This value is treated as a prefix, so the
6029 * empty string is equivalent to sorting by
6034 public function getDefaultSort() {
6035 if ( $this->mDefaultSort
!== false ) {
6036 return $this->mDefaultSort
;
6043 * Accessor for $mDefaultSort
6044 * Unlike getDefaultSort(), will return false if none is set
6046 * @return string|bool
6048 public function getCustomDefaultSort() {
6049 return $this->mDefaultSort
;
6052 private static function getSectionNameFromStrippedText( $text ) {
6053 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6054 $text = Sanitizer
::decodeCharReferences( $text );
6055 $text = self
::normalizeSectionName( $text );
6059 private static function makeAnchor( $sectionName ) {
6060 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
6063 private function makeLegacyAnchor( $sectionName ) {
6064 $fragmentMode = $this->svcOptions
->get( 'FragmentMode' );
6065 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
6066 // ForAttribute() and ForLink() are the same for legacy encoding
6067 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
6069 $id = Sanitizer
::escapeIdForLink( $sectionName );
6076 * Try to guess the section anchor name based on a wikitext fragment
6077 * presumably extracted from a heading, for example "Header" from
6080 * @param string $text
6081 * @return string Anchor (starting with '#')
6083 public function guessSectionNameFromWikiText( $text ) {
6084 # Strip out wikitext links(they break the anchor)
6085 $text = $this->stripSectionName( $text );
6086 $sectionName = self
::getSectionNameFromStrippedText( $text );
6087 return self
::makeAnchor( $sectionName );
6091 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6092 * instead, if possible. For use in redirects, since various versions
6093 * of Microsoft browsers interpret Location: headers as something other
6094 * than UTF-8, resulting in breakage.
6096 * @param string $text The section name
6097 * @return string Anchor (starting with '#')
6099 public function guessLegacySectionNameFromWikiText( $text ) {
6100 # Strip out wikitext links(they break the anchor)
6101 $text = $this->stripSectionName( $text );
6102 $sectionName = self
::getSectionNameFromStrippedText( $text );
6103 return $this->makeLegacyAnchor( $sectionName );
6107 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6108 * @param string $text Section name (plain text)
6109 * @return string Anchor (starting with '#')
6111 public static function guessSectionNameFromStrippedText( $text ) {
6112 $sectionName = self
::getSectionNameFromStrippedText( $text );
6113 return self
::makeAnchor( $sectionName );
6117 * Apply the same normalization as code making links to this section would
6119 * @param string $text
6122 private static function normalizeSectionName( $text ) {
6123 # T90902: ensure the same normalization is applied for IDs as to links
6124 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
6127 $parts = $titleParser->splitTitleString( "#$text" );
6128 } catch ( MalformedTitleException
$ex ) {
6131 return $parts['fragment'];
6135 * Strips a text string of wikitext for use in a section anchor
6137 * Accepts a text string and then removes all wikitext from the
6138 * string and leaves only the resultant text (i.e. the result of
6139 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6140 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6141 * to create valid section anchors by mimicing the output of the
6142 * parser when headings are parsed.
6144 * @param string $text Text string to be stripped of wikitext
6145 * for use in a Section anchor
6146 * @return string Filtered text string
6148 public function stripSectionName( $text ) {
6149 # Strip internal link markup
6150 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6151 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6153 # Strip external link markup
6154 # @todo FIXME: Not tolerant to blank link text
6155 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6156 # on how many empty links there are on the page - need to figure that out.
6157 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6159 # Parse wikitext quotes (italics & bold)
6160 $text = $this->doQuotes( $text );
6163 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6168 * strip/replaceVariables/unstrip for preprocessor regression testing
6170 * @param string $text
6171 * @param Title $title
6172 * @param ParserOptions $options
6173 * @param int $outputType
6177 public function testSrvus( $text, Title
$title, ParserOptions
$options,
6178 $outputType = self
::OT_HTML
6180 $magicScopeVariable = $this->lock();
6181 $this->startParse( $title, $options, $outputType, true );
6183 $text = $this->replaceVariables( $text );
6184 $text = $this->mStripState
->unstripBoth( $text );
6185 $text = Sanitizer
::removeHTMLtags( $text );
6190 * @param string $text
6191 * @param Title $title
6192 * @param ParserOptions $options
6195 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6196 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6200 * @param string $text
6201 * @param Title $title
6202 * @param ParserOptions $options
6205 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6206 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6210 * Call a callback function on all regions of the given text that are not
6211 * inside strip markers, and replace those regions with the return value
6212 * of the callback. For example, with input:
6216 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6217 * two strings will be replaced with the value returned by the callback in
6221 * @param callable $callback
6225 public function markerSkipCallback( $s, $callback ) {
6228 while ( $i < strlen( $s ) ) {
6229 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6230 if ( $markerStart === false ) {
6231 $out .= call_user_func( $callback, substr( $s, $i ) );
6234 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6235 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6236 if ( $markerEnd === false ) {
6237 $out .= substr( $s, $markerStart );
6240 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6241 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6250 * Remove any strip markers found in the given text.
6252 * @param string $text
6255 public function killMarkers( $text ) {
6256 return $this->mStripState
->killMarkers( $text );
6260 * Save the parser state required to convert the given half-parsed text to
6261 * HTML. "Half-parsed" in this context means the output of
6262 * recursiveTagParse() or internalParse(). This output has strip markers
6263 * from replaceVariables (extensionSubstitution() etc.), and link
6264 * placeholders from replaceLinkHolders().
6266 * Returns an array which can be serialized and stored persistently. This
6267 * array can later be loaded into another parser instance with
6268 * unserializeHalfParsedText(). The text can then be safely incorporated into
6269 * the return value of a parser hook.
6271 * @deprecated since 1.31
6272 * @param string $text
6276 public function serializeHalfParsedText( $text ) {
6277 wfDeprecated( __METHOD__
, '1.31' );
6280 'version' => self
::HALF_PARSED_VERSION
,
6281 'stripState' => $this->mStripState
->getSubState( $text ),
6282 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6288 * Load the parser state given in the $data array, which is assumed to
6289 * have been generated by serializeHalfParsedText(). The text contents is
6290 * extracted from the array, and its markers are transformed into markers
6291 * appropriate for the current Parser instance. This transformed text is
6292 * returned, and can be safely included in the return value of a parser
6295 * If the $data array has been stored persistently, the caller should first
6296 * check whether it is still valid, by calling isValidHalfParsedText().
6298 * @deprecated since 1.31
6299 * @param array $data Serialized data
6300 * @throws MWException
6303 public function unserializeHalfParsedText( $data ) {
6304 wfDeprecated( __METHOD__
, '1.31' );
6305 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6306 throw new MWException( __METHOD__
. ': invalid version' );
6309 # First, extract the strip state.
6310 $texts = [ $data['text'] ];
6311 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6313 # Now renumber links
6314 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6316 # Should be good to go.
6321 * Returns true if the given array, presumed to be generated by
6322 * serializeHalfParsedText(), is compatible with the current version of the
6325 * @deprecated since 1.31
6326 * @param array $data
6330 public function isValidHalfParsedText( $data ) {
6331 wfDeprecated( __METHOD__
, '1.31' );
6332 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6336 * Parsed a width param of imagelink like 300px or 200x300px
6338 * @param string $value
6339 * @param bool $parseHeight
6344 public static function parseWidthParam( $value, $parseHeight = true ) {
6345 $parsedWidthParam = [];
6346 if ( $value === '' ) {
6347 return $parsedWidthParam;
6350 # (T15500) In both cases (width/height and width only),
6351 # permit trailing "px" for backward compatibility.
6352 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6353 $width = intval( $m[1] );
6354 $height = intval( $m[2] );
6355 $parsedWidthParam['width'] = $width;
6356 $parsedWidthParam['height'] = $height;
6357 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6358 $width = intval( $value );
6359 $parsedWidthParam['width'] = $width;
6361 return $parsedWidthParam;
6365 * Lock the current instance of the parser.
6367 * This is meant to stop someone from calling the parser
6368 * recursively and messing up all the strip state.
6370 * @throws MWException If parser is in a parse
6371 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6373 protected function lock() {
6374 if ( $this->mInParse
) {
6375 throw new MWException( "Parser state cleared while parsing. "
6376 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6379 // Save the backtrace when locking, so that if some code tries locking again,
6380 // we can print the lock owner's backtrace for easier debugging
6382 $this->mInParse
= $e->getTraceAsString();
6384 $recursiveCheck = new ScopedCallback( function () {
6385 $this->mInParse
= false;
6388 return $recursiveCheck;
6392 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6394 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6395 * or if there is more than one <p/> tag in the input HTML.
6397 * @param string $html
6401 public static function stripOuterParagraph( $html ) {
6403 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '</p>' ) === false ) {
6411 * Return this parser if it is not doing anything, otherwise
6412 * get a fresh parser. You can use this method by doing
6413 * $newParser = $oldParser->getFreshParser(), or more simply
6414 * $oldParser->getFreshParser()->parse( ... );
6415 * if you're unsure if $oldParser is safe to use.
6418 * @return Parser A parser object that is not parsing anything
6420 public function getFreshParser() {
6421 if ( $this->mInParse
) {
6422 return $this->factory
->create();
6429 * Set's up the PHP implementation of OOUI for use in this request
6430 * and instructs OutputPage to enable OOUI for itself.
6434 public function enableOOUI() {
6435 OutputPage
::setupOOUI();
6436 $this->mOutput
->setEnableOOUI( true );