3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @defgroup Parser Parser
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
37 * There are seven main entry points into the Parser class:
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
57 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
60 * $wgNamespacesWithSubpages
62 * @par Settings only within ParserOptions:
63 * $wgAllowExternalImages
64 * $wgAllowSpecialInclusion
72 * Update this version number when the ParserOutput format
73 * changes in an incompatible way, so the parser cache
74 * can automatically discard old data.
76 const VERSION
= '1.6.4';
79 * Update this version number when the output of serialiseHalfParsedText()
80 * changes in an incompatible way
82 const HALF_PARSED_VERSION
= 2;
84 # Flags for Parser::setFunctionHook
85 const SFH_NO_HASH
= 1;
86 const SFH_OBJECT_ARGS
= 2;
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
92 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
93 # uses to replace invalid HTML characters.
94 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
95 # Simplified expression to match an IPv4 or IPv6 address, or
96 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
97 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
98 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
99 // phpcs:ignore Generic.Files.LineLength
100 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
101 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
103 # Regular expression for a non-newline space
104 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
118 * @var string Prefix and suffix for temporary replacement strings
119 * for the multipass parser.
121 * \x7f should never appear in input as it's disallowed in XML.
122 * Using it at the front also gives us a little extra robustness
123 * since it shouldn't match when butted up against identifier-like
126 * Must not consist of all title characters, or else it will change
127 * the behavior of <nowiki> in a link.
129 * Must have a character that needs escaping in attributes, otherwise
130 * someone could put a strip marker in an attribute, to get around
131 * escaping quote marks, and break out of the attribute. Thus we add
134 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
135 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
137 # Markers used for wrapping the table of contents
138 const TOC_START
= '<mw:toc>';
139 const TOC_END
= '</mw:toc>';
142 public $mTagHooks = [];
143 public $mTransparentTagHooks = [];
144 public $mFunctionHooks = [];
145 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
146 public $mFunctionTagHooks = [];
147 public $mStripList = [];
148 public $mDefaultStripList = [];
149 public $mVarCache = [];
150 public $mImageParams = [];
151 public $mImageParamsMagicArray = [];
152 public $mMarkerIndex = 0;
153 public $mFirstCall = true;
155 # Initialised by initialiseVariables()
158 * @var MagicWordArray
163 * @var MagicWordArray
166 # Initialised in constructor
167 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
169 # Initialized in getPreprocessor()
170 /** @var Preprocessor */
171 public $mPreprocessor;
173 # Cleared with clearState():
185 public $mIncludeCount;
187 * @var LinkHolderArray
189 public $mLinkHolders;
192 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
193 public $mDefaultSort;
194 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
195 public $mExpensiveFunctionCount; # number of expensive parser function calls
196 public $mShowToc, $mForceTocPosition;
201 public $mUser; # User object; only used when doing pre-save transform
204 # These are variables reset at least once per parse regardless of $clearState
214 public $mTitle; # Title context, used for self-link rendering and similar things
215 public $mOutputType; # Output type, one of the OT_xxx constants
216 public $ot; # Shortcut alias, see setOutputType()
217 public $mRevisionObject; # The revision object of the specified revision ID
218 public $mRevisionId; # ID to display in {{REVISIONID}} tags
219 public $mRevisionTimestamp; # The timestamp of the specified revision ID
220 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
221 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
222 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
223 public $mInputSize = false; # For {{PAGESIZE}} on current page.
226 * @var string Deprecated accessor for the strip marker prefix.
227 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
229 public $mUniqPrefix = self
::MARKER_PREFIX
;
232 * @var array Array with the language name of each language link (i.e. the
233 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
234 * duplicate language links to the ParserOutput.
236 public $mLangLinkLanguages;
239 * @var MapCacheLRU|null
242 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
244 public $currentRevisionCache;
247 * @var bool|string Recursive call protection.
248 * This variable should be treated as if it were private.
250 public $mInParse = false;
252 /** @var SectionProfiler */
253 protected $mProfiler;
258 protected $mLinkRenderer;
263 public function __construct( $conf = [] ) {
264 $this->mConf
= $conf;
265 $this->mUrlProtocols
= wfUrlProtocols();
266 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
267 self
::EXT_LINK_ADDR
.
268 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
269 if ( isset( $conf['preprocessorClass'] ) ) {
270 $this->mPreprocessorClass
= $conf['preprocessorClass'];
271 } elseif ( defined( 'HPHP_VERSION' ) ) {
272 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
273 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
274 } elseif ( extension_loaded( 'domxml' ) ) {
275 # PECL extension that conflicts with the core DOM extension (T15770)
276 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
277 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
278 } elseif ( extension_loaded( 'dom' ) ) {
279 $this->mPreprocessorClass
= Preprocessor_DOM
::class;
281 $this->mPreprocessorClass
= Preprocessor_Hash
::class;
283 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
287 * Reduce memory usage to reduce the impact of circular references
289 public function __destruct() {
290 if ( isset( $this->mLinkHolders
) ) {
291 unset( $this->mLinkHolders
);
293 foreach ( $this as $name => $value ) {
294 unset( $this->$name );
299 * Allow extensions to clean up when the parser is cloned
301 public function __clone() {
302 $this->mInParse
= false;
304 // T58226: When you create a reference "to" an object field, that
305 // makes the object field itself be a reference too (until the other
306 // reference goes out of scope). When cloning, any field that's a
307 // reference is copied as a reference in the new object. Both of these
308 // are defined PHP5 behaviors, as inconvenient as it is for us when old
309 // hooks from PHP4 days are passing fields by reference.
310 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
311 // Make a non-reference copy of the field, then rebind the field to
312 // reference the new copy.
318 Hooks
::run( 'ParserCloned', [ $this ] );
322 * Do various kinds of initialisation on the first call of the parser
324 public function firstCallInit() {
325 if ( !$this->mFirstCall
) {
328 $this->mFirstCall
= false;
330 CoreParserFunctions
::register( $this );
331 CoreTagHooks
::register( $this );
332 $this->initialiseVariables();
334 // Avoid PHP 7.1 warning from passing $this by reference
336 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
344 public function clearState() {
345 if ( $this->mFirstCall
) {
346 $this->firstCallInit();
348 $this->mOutput
= new ParserOutput
;
349 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
350 $this->mAutonumber
= 0;
351 $this->mIncludeCount
= [];
352 $this->mLinkHolders
= new LinkHolderArray( $this );
354 $this->mRevisionObject
= $this->mRevisionTimestamp
=
355 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
356 $this->mVarCache
= [];
358 $this->mLangLinkLanguages
= [];
359 $this->currentRevisionCache
= null;
361 $this->mStripState
= new StripState( $this );
363 # Clear these on every parse, T6549
364 $this->mTplRedirCache
= $this->mTplDomCache
= [];
366 $this->mShowToc
= true;
367 $this->mForceTocPosition
= false;
368 $this->mIncludeSizes
= [
372 $this->mPPNodeCount
= 0;
373 $this->mGeneratedPPNodeCount
= 0;
374 $this->mHighestExpansionDepth
= 0;
375 $this->mDefaultSort
= false;
376 $this->mHeadings
= [];
377 $this->mDoubleUnderscores
= [];
378 $this->mExpensiveFunctionCount
= 0;
381 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
382 $this->mPreprocessor
= null;
385 $this->mProfiler
= new SectionProfiler();
387 // Avoid PHP 7.1 warning from passing $this by reference
389 Hooks
::run( 'ParserClearState', [ &$parser ] );
393 * Convert wikitext to HTML
394 * Do not call this function recursively.
396 * @param string $text Text we want to parse
397 * @param Title $title
398 * @param ParserOptions $options
399 * @param bool $linestart
400 * @param bool $clearState
401 * @param int $revid Number to pass in {{REVISIONID}}
402 * @return ParserOutput A ParserOutput
404 public function parse(
405 $text, Title
$title, ParserOptions
$options,
406 $linestart = true, $clearState = true, $revid = null
409 // We use U+007F DELETE to construct strip markers, so we have to make
410 // sure that this character does not occur in the input text.
411 $text = strtr( $text, "\x7f", "?" );
412 $magicScopeVariable = $this->lock();
414 // Strip U+0000 NULL (T159174)
415 $text = str_replace( "\000", '', $text );
417 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
419 $this->currentRevisionCache
= null;
420 $this->mInputSize
= strlen( $text );
421 if ( $this->mOptions
->getEnableLimitReport() ) {
422 $this->mOutput
->resetParseStartTime();
425 $oldRevisionId = $this->mRevisionId
;
426 $oldRevisionObject = $this->mRevisionObject
;
427 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
428 $oldRevisionUser = $this->mRevisionUser
;
429 $oldRevisionSize = $this->mRevisionSize
;
430 if ( $revid !== null ) {
431 $this->mRevisionId
= $revid;
432 $this->mRevisionObject
= null;
433 $this->mRevisionTimestamp
= null;
434 $this->mRevisionUser
= null;
435 $this->mRevisionSize
= null;
438 // Avoid PHP 7.1 warning from passing $this by reference
440 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
442 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
443 $text = $this->internalParse( $text );
444 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
446 $text = $this->internalParseHalfParsed( $text, true, $linestart );
449 * A converted title will be provided in the output object if title and
450 * content conversion are enabled, the article text does not contain
451 * a conversion-suppressing double-underscore tag, and no
452 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
453 * automatic link conversion.
455 if ( !( $options->getDisableTitleConversion()
456 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
457 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
458 ||
$this->mOutput
->getDisplayTitle() !== false )
460 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
461 if ( $convruletitle ) {
462 $this->mOutput
->setTitleText( $convruletitle );
464 $titleText = $this->getConverterLanguage()->convertTitle( $title );
465 $this->mOutput
->setTitleText( $titleText );
469 # Compute runtime adaptive expiry if set
470 $this->mOutput
->finalizeAdaptiveCacheExpiry();
472 # Warn if too many heavyweight parser functions were used
473 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
474 $this->limitationWarn( 'expensive-parserfunction',
475 $this->mExpensiveFunctionCount
,
476 $this->mOptions
->getExpensiveParserFunctionLimit()
480 # Information on limits, for the benefit of users who try to skirt them
481 if ( $this->mOptions
->getEnableLimitReport() ) {
482 $text .= $this->makeLimitReport();
485 # Wrap non-interface parser output in a <div> so it can be targeted
487 $class = $this->mOptions
->getWrapOutputClass();
488 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
489 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
492 $this->mOutput
->setText( $text );
494 $this->mRevisionId
= $oldRevisionId;
495 $this->mRevisionObject
= $oldRevisionObject;
496 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
497 $this->mRevisionUser
= $oldRevisionUser;
498 $this->mRevisionSize
= $oldRevisionSize;
499 $this->mInputSize
= false;
500 $this->currentRevisionCache
= null;
502 return $this->mOutput
;
506 * Set the limit report data in the current ParserOutput, and return the
507 * limit report HTML comment.
511 protected function makeLimitReport() {
512 global $wgShowHostnames;
514 $maxIncludeSize = $this->mOptions
->getMaxIncludeSize();
516 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
517 if ( $cpuTime !== null ) {
518 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
519 sprintf( "%.3f", $cpuTime )
523 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
524 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
525 sprintf( "%.3f", $wallTime )
528 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
529 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
531 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
532 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
534 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
535 [ $this->mIncludeSizes
['post-expand'], $maxIncludeSize ]
537 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
538 [ $this->mIncludeSizes
['arg'], $maxIncludeSize ]
540 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
541 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
543 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
544 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
547 foreach ( $this->mStripState
->getLimitReport() as list( $key, $value ) ) {
548 $this->mOutput
->setLimitReportData( $key, $value );
551 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
553 $limitReport = "NewPP limit report\n";
554 if ( $wgShowHostnames ) {
555 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
557 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
558 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
559 $limitReport .= 'Dynamic content: ' .
560 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
563 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
564 if ( Hooks
::run( 'ParserLimitReportFormat',
565 [ $key, &$value, &$limitReport, false, false ]
567 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
568 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
569 ->inLanguage( 'en' )->useDatabase( false );
570 if ( !$valueMsg->exists() ) {
571 $valueMsg = new RawMessage( '$1' );
573 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
574 $valueMsg->params( $value );
575 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
579 // Since we're not really outputting HTML, decode the entities and
580 // then re-encode the things that need hiding inside HTML comments.
581 $limitReport = htmlspecialchars_decode( $limitReport );
582 // Run deprecated hook
583 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
585 // Sanitize for comment. Note '‐' in the replacement is U+2010,
586 // which looks much like the problematic '-'.
587 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
588 $text = "\n<!-- \n$limitReport-->\n";
590 // Add on template profiling data in human/machine readable way
591 $dataByFunc = $this->mProfiler
->getFunctionStats();
592 uasort( $dataByFunc, function ( $a, $b ) {
593 return $a['real'] < $b['real']; // descending order
596 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
597 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
598 $item['%real'], $item['real'], $item['calls'],
599 htmlspecialchars( $item['name'] ) );
601 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
602 $text .= implode( "\n", $profileReport ) . "\n-->\n";
604 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
606 // Add other cache related metadata
607 if ( $wgShowHostnames ) {
608 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
610 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
611 $this->mOutput
->getCacheTime() );
612 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
613 $this->mOutput
->getCacheExpiry() );
614 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
615 $this->mOutput
->hasDynamicContent() );
617 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
618 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
619 $this->mTitle
->getPrefixedDBkey() );
625 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
626 * can be called from an extension tag hook.
628 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
629 * instead, which means that lists and links have not been fully parsed yet,
630 * and strip markers are still present.
632 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
634 * Use this function if you're a parser tag hook and you want to parse
635 * wikitext before or after applying additional transformations, and you
636 * intend to *return the result as hook output*, which will cause it to go
637 * through the rest of parsing process automatically.
639 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
640 * $text are not expanded
642 * @param string $text Text extension wants to have parsed
643 * @param bool|PPFrame $frame The frame to use for expanding any template variables
644 * @return string UNSAFE half-parsed HTML
646 public function recursiveTagParse( $text, $frame = false ) {
647 // Avoid PHP 7.1 warning from passing $this by reference
649 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
650 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
651 $text = $this->internalParse( $text, false, $frame );
656 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
657 * point can be called from an extension tag hook.
659 * The output of this function is fully-parsed HTML that is safe for output.
660 * If you're a parser tag hook, you might want to use recursiveTagParse()
663 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
664 * $text are not expanded
668 * @param string $text Text extension wants to have parsed
669 * @param bool|PPFrame $frame The frame to use for expanding any template variables
670 * @return string Fully parsed HTML
672 public function recursiveTagParseFully( $text, $frame = false ) {
673 $text = $this->recursiveTagParse( $text, $frame );
674 $text = $this->internalParseHalfParsed( $text, false );
679 * Expand templates and variables in the text, producing valid, static wikitext.
680 * Also removes comments.
681 * Do not call this function recursively.
682 * @param string $text
683 * @param Title $title
684 * @param ParserOptions $options
685 * @param int|null $revid
686 * @param bool|PPFrame $frame
687 * @return mixed|string
689 public function preprocess( $text, Title
$title = null,
690 ParserOptions
$options, $revid = null, $frame = false
692 $magicScopeVariable = $this->lock();
693 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
694 if ( $revid !== null ) {
695 $this->mRevisionId
= $revid;
697 // Avoid PHP 7.1 warning from passing $this by reference
699 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
700 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
701 $text = $this->replaceVariables( $text, $frame );
702 $text = $this->mStripState
->unstripBoth( $text );
707 * Recursive parser entry point that can be called from an extension tag
710 * @param string $text Text to be expanded
711 * @param bool|PPFrame $frame The frame to use for expanding any template variables
715 public function recursivePreprocess( $text, $frame = false ) {
716 $text = $this->replaceVariables( $text, $frame );
717 $text = $this->mStripState
->unstripBoth( $text );
722 * Process the wikitext for the "?preload=" feature. (T7210)
724 * "<noinclude>", "<includeonly>" etc. are parsed as for template
725 * transclusion, comments, templates, arguments, tags hooks and parser
726 * functions are untouched.
728 * @param string $text
729 * @param Title $title
730 * @param ParserOptions $options
731 * @param array $params
734 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
735 $msg = new RawMessage( $text );
736 $text = $msg->params( $params )->plain();
738 # Parser (re)initialisation
739 $magicScopeVariable = $this->lock();
740 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
742 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
743 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
744 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
745 $text = $this->mStripState
->unstripBoth( $text );
750 * Set the current user.
751 * Should only be used when doing pre-save transform.
753 * @param User|null $user User object or null (to reset)
755 public function setUser( $user ) {
756 $this->mUser
= $user;
760 * Set the context title
764 public function setTitle( $t ) {
766 $t = Title
::newFromText( 'NO TITLE' );
769 if ( $t->hasFragment() ) {
770 # Strip the fragment to avoid various odd effects
771 $this->mTitle
= $t->createFragmentTarget( '' );
778 * Accessor for the Title object
782 public function getTitle() {
783 return $this->mTitle
;
787 * Accessor/mutator for the Title object
789 * @param Title $x Title object or null to just get the current one
792 public function Title( $x = null ) {
793 return wfSetVar( $this->mTitle
, $x );
797 * Set the output type
799 * @param int $ot New value
801 public function setOutputType( $ot ) {
802 $this->mOutputType
= $ot;
805 'html' => $ot == self
::OT_HTML
,
806 'wiki' => $ot == self
::OT_WIKI
,
807 'pre' => $ot == self
::OT_PREPROCESS
,
808 'plain' => $ot == self
::OT_PLAIN
,
813 * Accessor/mutator for the output type
815 * @param int|null $x New value or null to just get the current one
818 public function OutputType( $x = null ) {
819 return wfSetVar( $this->mOutputType
, $x );
823 * Get the ParserOutput object
825 * @return ParserOutput
827 public function getOutput() {
828 return $this->mOutput
;
832 * Get the ParserOptions object
834 * @return ParserOptions
836 public function getOptions() {
837 return $this->mOptions
;
841 * Accessor/mutator for the ParserOptions object
843 * @param ParserOptions $x New value or null to just get the current one
844 * @return ParserOptions Current ParserOptions object
846 public function Options( $x = null ) {
847 return wfSetVar( $this->mOptions
, $x );
853 public function nextLinkID() {
854 return $this->mLinkID++
;
860 public function setLinkID( $id ) {
861 $this->mLinkID
= $id;
865 * Get a language object for use in parser functions such as {{FORMATNUM:}}
868 public function getFunctionLang() {
869 return $this->getTargetLanguage();
873 * Get the target language for the content being parsed. This is usually the
874 * language that the content is in.
878 * @throws MWException
881 public function getTargetLanguage() {
882 $target = $this->mOptions
->getTargetLanguage();
884 if ( $target !== null ) {
886 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
887 return $this->mOptions
->getUserLangObj();
888 } elseif ( is_null( $this->mTitle
) ) {
889 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
892 return $this->mTitle
->getPageLanguage();
896 * Get the language object for language conversion
897 * @return Language|null
899 public function getConverterLanguage() {
900 return $this->getTargetLanguage();
904 * Get a User object either from $this->mUser, if set, or from the
905 * ParserOptions object otherwise
909 public function getUser() {
910 if ( !is_null( $this->mUser
) ) {
913 return $this->mOptions
->getUser();
917 * Get a preprocessor object
919 * @return Preprocessor
921 public function getPreprocessor() {
922 if ( !isset( $this->mPreprocessor
) ) {
923 $class = $this->mPreprocessorClass
;
924 $this->mPreprocessor
= new $class( $this );
926 return $this->mPreprocessor
;
930 * Get a LinkRenderer instance to make links with
933 * @return LinkRenderer
935 public function getLinkRenderer() {
936 if ( !$this->mLinkRenderer
) {
937 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
938 ->getLinkRendererFactory()->create();
939 $this->mLinkRenderer
->setStubThreshold(
940 $this->getOptions()->getStubThreshold()
944 return $this->mLinkRenderer
;
948 * Replaces all occurrences of HTML-style comments and the given tags
949 * in the text with a random marker and returns the next text. The output
950 * parameter $matches will be an associative array filled with data in
957 * [ 'param' => 'x' ],
958 * '<element param="x">tag content</element>' ]
961 * @param array $elements List of element names. Comments are always extracted.
962 * @param string $text Source text string.
963 * @param array &$matches Out parameter, Array: extracted tags
964 * @return string Stripped text
966 public static function extractTagsAndParams( $elements, $text, &$matches ) {
971 $taglist = implode( '|', $elements );
972 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
974 while ( $text != '' ) {
975 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
977 if ( count( $p ) < 5 ) {
980 if ( count( $p ) > 5 ) {
994 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
995 $stripped .= $marker;
997 if ( $close === '/>' ) {
998 # Empty element tag, <tag />
1003 if ( $element === '!--' ) {
1006 $end = "/(<\\/$element\\s*>)/i";
1008 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1010 if ( count( $q ) < 3 ) {
1011 # No end tag -- let it run out to the end of the text.
1020 $matches[$marker] = [ $element,
1022 Sanitizer
::decodeTagAttributes( $attributes ),
1023 "<$element$attributes$close$content$tail" ];
1029 * Get a list of strippable XML-like elements
1033 public function getStripList() {
1034 return $this->mStripList
;
1038 * Add an item to the strip state
1039 * Returns the unique tag which must be inserted into the stripped text
1040 * The tag will be replaced with the original text in unstrip()
1042 * @param string $text
1046 public function insertStripItem( $text ) {
1047 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1048 $this->mMarkerIndex++
;
1049 $this->mStripState
->addGeneral( $marker, $text );
1054 * parse the wiki syntax used to render tables
1057 * @param string $text
1060 public function doTableStuff( $text ) {
1061 $lines = StringUtils
::explode( "\n", $text );
1063 $td_history = []; # Is currently a td tag open?
1064 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1065 $tr_history = []; # Is currently a tr tag open?
1066 $tr_attributes = []; # history of tr attributes
1067 $has_opened_tr = []; # Did this table open a <tr> element?
1068 $indent_level = 0; # indent level of the table
1070 foreach ( $lines as $outLine ) {
1071 $line = trim( $outLine );
1073 if ( $line === '' ) { # empty line, go to next line
1074 $out .= $outLine . "\n";
1078 $first_character = $line[0];
1079 $first_two = substr( $line, 0, 2 );
1082 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1083 # First check if we are starting a new table
1084 $indent_level = strlen( $matches[1] );
1086 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1087 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1089 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1090 array_push( $td_history, false );
1091 array_push( $last_tag_history, '' );
1092 array_push( $tr_history, false );
1093 array_push( $tr_attributes, '' );
1094 array_push( $has_opened_tr, false );
1095 } elseif ( count( $td_history ) == 0 ) {
1096 # Don't do any of the following
1097 $out .= $outLine . "\n";
1099 } elseif ( $first_two === '|}' ) {
1100 # We are ending a table
1101 $line = '</table>' . substr( $line, 2 );
1102 $last_tag = array_pop( $last_tag_history );
1104 if ( !array_pop( $has_opened_tr ) ) {
1105 $line = "<tr><td></td></tr>{$line}";
1108 if ( array_pop( $tr_history ) ) {
1109 $line = "</tr>{$line}";
1112 if ( array_pop( $td_history ) ) {
1113 $line = "</{$last_tag}>{$line}";
1115 array_pop( $tr_attributes );
1116 if ( $indent_level > 0 ) {
1117 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1121 } elseif ( $first_two === '|-' ) {
1122 # Now we have a table row
1123 $line = preg_replace( '#^\|-+#', '', $line );
1125 # Whats after the tag is now only attributes
1126 $attributes = $this->mStripState
->unstripBoth( $line );
1127 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1128 array_pop( $tr_attributes );
1129 array_push( $tr_attributes, $attributes );
1132 $last_tag = array_pop( $last_tag_history );
1133 array_pop( $has_opened_tr );
1134 array_push( $has_opened_tr, true );
1136 if ( array_pop( $tr_history ) ) {
1140 if ( array_pop( $td_history ) ) {
1141 $line = "</{$last_tag}>{$line}";
1145 array_push( $tr_history, false );
1146 array_push( $td_history, false );
1147 array_push( $last_tag_history, '' );
1148 } elseif ( $first_character === '|'
1149 ||
$first_character === '!'
1150 ||
$first_two === '|+'
1152 # This might be cell elements, td, th or captions
1153 if ( $first_two === '|+' ) {
1154 $first_character = '+';
1155 $line = substr( $line, 2 );
1157 $line = substr( $line, 1 );
1160 // Implies both are valid for table headings.
1161 if ( $first_character === '!' ) {
1162 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1165 # Split up multiple cells on the same line.
1166 # FIXME : This can result in improper nesting of tags processed
1167 # by earlier parser steps.
1168 $cells = explode( '||', $line );
1172 # Loop through each table cell
1173 foreach ( $cells as $cell ) {
1175 if ( $first_character !== '+' ) {
1176 $tr_after = array_pop( $tr_attributes );
1177 if ( !array_pop( $tr_history ) ) {
1178 $previous = "<tr{$tr_after}>\n";
1180 array_push( $tr_history, true );
1181 array_push( $tr_attributes, '' );
1182 array_pop( $has_opened_tr );
1183 array_push( $has_opened_tr, true );
1186 $last_tag = array_pop( $last_tag_history );
1188 if ( array_pop( $td_history ) ) {
1189 $previous = "</{$last_tag}>\n{$previous}";
1192 if ( $first_character === '|' ) {
1194 } elseif ( $first_character === '!' ) {
1196 } elseif ( $first_character === '+' ) {
1197 $last_tag = 'caption';
1202 array_push( $last_tag_history, $last_tag );
1204 # A cell could contain both parameters and data
1205 $cell_data = explode( '|', $cell, 2 );
1207 # T2553: Note that a '|' inside an invalid link should not
1208 # be mistaken as delimiting cell parameters
1209 # Bug T153140: Neither should language converter markup.
1210 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1211 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1212 } elseif ( count( $cell_data ) == 1 ) {
1213 // Whitespace in cells is trimmed
1214 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1216 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1217 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1218 // Whitespace in cells is trimmed
1219 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1223 array_push( $td_history, true );
1226 $out .= $outLine . "\n";
1229 # Closing open td, tr && table
1230 while ( count( $td_history ) > 0 ) {
1231 if ( array_pop( $td_history ) ) {
1234 if ( array_pop( $tr_history ) ) {
1237 if ( !array_pop( $has_opened_tr ) ) {
1238 $out .= "<tr><td></td></tr>\n";
1241 $out .= "</table>\n";
1244 # Remove trailing line-ending (b/c)
1245 if ( substr( $out, -1 ) === "\n" ) {
1246 $out = substr( $out, 0, -1 );
1249 # special case: don't return empty table
1250 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1258 * Helper function for parse() that transforms wiki markup into half-parsed
1259 * HTML. Only called for $mOutputType == self::OT_HTML.
1263 * @param string $text The text to parse
1264 * @param bool $isMain Whether this is being called from the main parse() function
1265 * @param PPFrame|bool $frame A pre-processor frame
1269 public function internalParse( $text, $isMain = true, $frame = false ) {
1272 // Avoid PHP 7.1 warning from passing $this by reference
1275 # Hook to suspend the parser in this state
1276 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1280 # if $frame is provided, then use $frame for replacing any variables
1282 # use frame depth to infer how include/noinclude tags should be handled
1283 # depth=0 means this is the top-level document; otherwise it's an included document
1284 if ( !$frame->depth
) {
1287 $flag = self
::PTD_FOR_INCLUSION
;
1289 $dom = $this->preprocessToDom( $text, $flag );
1290 $text = $frame->expand( $dom );
1292 # if $frame is not provided, then use old-style replaceVariables
1293 $text = $this->replaceVariables( $text );
1296 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1297 $text = Sanitizer
::removeHTMLtags(
1299 [ $this, 'attributeStripCallback' ],
1301 array_keys( $this->mTransparentTagHooks
),
1303 [ $this, 'addTrackingCategory' ]
1305 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1307 # Tables need to come after variable replacement for things to work
1308 # properly; putting them before other transformations should keep
1309 # exciting things like link expansions from showing up in surprising
1311 $text = $this->doTableStuff( $text );
1313 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1315 $text = $this->doDoubleUnderscore( $text );
1317 $text = $this->doHeadings( $text );
1318 $text = $this->replaceInternalLinks( $text );
1319 $text = $this->doAllQuotes( $text );
1320 $text = $this->replaceExternalLinks( $text );
1322 # replaceInternalLinks may sometimes leave behind
1323 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1324 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1326 $text = $this->doMagicLinks( $text );
1327 $text = $this->formatHeadings( $text, $origText, $isMain );
1333 * Helper function for parse() that transforms half-parsed HTML into fully
1336 * @param string $text
1337 * @param bool $isMain
1338 * @param bool $linestart
1341 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1342 $text = $this->mStripState
->unstripGeneral( $text );
1344 // Avoid PHP 7.1 warning from passing $this by reference
1348 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1351 # Clean up special characters, only run once, next-to-last before doBlockLevels
1353 # French spaces, last one Guillemet-left
1354 # only if there is something before the space
1355 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1356 # french spaces, Guillemet-right
1357 '/(\\302\\253) /' => '\\1 ',
1358 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1360 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1362 $text = $this->doBlockLevels( $text, $linestart );
1364 $this->replaceLinkHolders( $text );
1367 * The input doesn't get language converted if
1369 * b) Content isn't converted
1370 * c) It's a conversion table
1371 * d) it is an interface message (which is in the user language)
1373 if ( !( $this->mOptions
->getDisableContentConversion()
1374 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1376 if ( !$this->mOptions
->getInterfaceMessage() ) {
1377 # The position of the convert() call should not be changed. it
1378 # assumes that the links are all replaced and the only thing left
1379 # is the <nowiki> mark.
1380 $text = $this->getConverterLanguage()->convert( $text );
1384 $text = $this->mStripState
->unstripNoWiki( $text );
1387 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1390 $text = $this->replaceTransparentTags( $text );
1391 $text = $this->mStripState
->unstripGeneral( $text );
1393 $text = Sanitizer
::normalizeCharReferences( $text );
1395 if ( MWTidy
::isEnabled() ) {
1396 if ( $this->mOptions
->getTidy() ) {
1397 $text = MWTidy
::tidy( $text );
1400 # attempt to sanitize at least some nesting problems
1401 # (T4702 and quite a few others)
1403 # ''Something [http://www.cool.com cool''] -->
1404 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1405 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1406 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1407 # fix up an anchor inside another anchor, only
1408 # at least for a single single nested link (T5695)
1409 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1410 '\\1\\2</a>\\3</a>\\1\\4</a>',
1411 # fix div inside inline elements- doBlockLevels won't wrap a line which
1412 # contains a div, so fix it up here; replace
1413 # div with escaped text
1414 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1415 '\\1\\3<div\\5>\\6</div>\\8\\9',
1416 # remove empty italic or bold tag pairs, some
1417 # introduced by rules above
1418 '/<([bi])><\/\\1>/' => '',
1421 $text = preg_replace(
1422 array_keys( $tidyregs ),
1423 array_values( $tidyregs ),
1428 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1435 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1436 * magic external links.
1441 * @param string $text
1445 public function doMagicLinks( $text ) {
1446 $prots = wfUrlProtocolsWithoutProtRel();
1447 $urlChar = self
::EXT_LINK_URL_CLASS
;
1448 $addr = self
::EXT_LINK_ADDR
;
1449 $space = self
::SPACE_NOT_NL
; # non-newline space
1450 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1451 $spaces = "$space++"; # possessive match of 1 or more spaces
1452 $text = preg_replace_callback(
1454 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1455 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1456 (\b # m[3]: Free external links
1458 ($addr$urlChar*) # m[4]: Post-protocol path
1460 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1462 \bISBN $spaces ( # m[6]: ISBN, capture number
1463 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1464 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1465 [0-9Xx] # check digit
1467 )!xu", [ $this, 'magicLinkCallback' ], $text );
1472 * @throws MWException
1474 * @return HTML|string
1476 public function magicLinkCallback( $m ) {
1477 if ( isset( $m[1] ) && $m[1] !== '' ) {
1480 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1483 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1484 # Free external link
1485 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1486 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1488 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1489 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1494 $cssClass = 'mw-magiclink-rfc';
1495 $trackingCat = 'magiclink-tracking-rfc';
1497 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1498 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1502 $urlmsg = 'pubmedurl';
1503 $cssClass = 'mw-magiclink-pmid';
1504 $trackingCat = 'magiclink-tracking-pmid';
1507 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1508 substr( $m[0], 0, 20 ) . '"' );
1510 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1511 $this->addTrackingCategory( $trackingCat );
1512 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1513 } elseif ( isset( $m[6] ) && $m[6] !== ''
1514 && $this->mOptions
->getMagicISBNLinks()
1518 $space = self
::SPACE_NOT_NL
; # non-newline space
1519 $isbn = preg_replace( "/$space/", ' ', $isbn );
1520 $num = strtr( $isbn, [
1525 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1526 return $this->getLinkRenderer()->makeKnownLink(
1527 SpecialPage
::getTitleFor( 'Booksources', $num ),
1530 'class' => 'internal mw-magiclink-isbn',
1531 'title' => false // suppress title attribute
1540 * Make a free external link, given a user-supplied URL
1542 * @param string $url
1543 * @param int $numPostProto
1544 * The number of characters after the protocol.
1545 * @return string HTML
1548 public function makeFreeExternalLink( $url, $numPostProto ) {
1551 # The characters '<' and '>' (which were escaped by
1552 # removeHTMLtags()) should not be included in
1553 # URLs, per RFC 2396.
1554 # Make terminate a URL as well (bug T84937)
1557 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1562 $trail = substr( $url, $m2[0][1] ) . $trail;
1563 $url = substr( $url, 0, $m2[0][1] );
1566 # Move trailing punctuation to $trail
1568 # If there is no left bracket, then consider right brackets fair game too
1569 if ( strpos( $url, '(' ) === false ) {
1573 $urlRev = strrev( $url );
1574 $numSepChars = strspn( $urlRev, $sep );
1575 # Don't break a trailing HTML entity by moving the ; into $trail
1576 # This is in hot code, so use substr_compare to avoid having to
1577 # create a new string object for the comparison
1578 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1579 # more optimization: instead of running preg_match with a $
1580 # anchor, which can be slow, do the match on the reversed
1581 # string starting at the desired offset.
1582 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1583 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1587 if ( $numSepChars ) {
1588 $trail = substr( $url, -$numSepChars ) . $trail;
1589 $url = substr( $url, 0, -$numSepChars );
1592 # Verify that we still have a real URL after trail removal, and
1593 # not just lone protocol
1594 if ( strlen( $trail ) >= $numPostProto ) {
1595 return $url . $trail;
1598 $url = Sanitizer
::cleanUrl( $url );
1600 # Is this an external image?
1601 $text = $this->maybeMakeExternalImage( $url );
1602 if ( $text === false ) {
1603 # Not an image, make a link
1604 $text = Linker
::makeExternalLink( $url,
1605 $this->getConverterLanguage()->markNoConversion( $url, true ),
1607 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1608 # Register it in the output object...
1609 $this->mOutput
->addExternalLink( $url );
1611 return $text . $trail;
1615 * Parse headers and return html
1619 * @param string $text
1623 public function doHeadings( $text ) {
1624 for ( $i = 6; $i >= 1; --$i ) {
1625 $h = str_repeat( '=', $i );
1626 // Trim non-newline whitespace from headings
1627 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1628 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1634 * Replace single quotes with HTML markup
1637 * @param string $text
1639 * @return string The altered text
1641 public function doAllQuotes( $text ) {
1643 $lines = StringUtils
::explode( "\n", $text );
1644 foreach ( $lines as $line ) {
1645 $outtext .= $this->doQuotes( $line ) . "\n";
1647 $outtext = substr( $outtext, 0, -1 );
1652 * Helper function for doAllQuotes()
1654 * @param string $text
1658 public function doQuotes( $text ) {
1659 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1660 $countarr = count( $arr );
1661 if ( $countarr == 1 ) {
1665 // First, do some preliminary work. This may shift some apostrophes from
1666 // being mark-up to being text. It also counts the number of occurrences
1667 // of bold and italics mark-ups.
1670 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1671 $thislen = strlen( $arr[$i] );
1672 // If there are ever four apostrophes, assume the first is supposed to
1673 // be text, and the remaining three constitute mark-up for bold text.
1674 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1675 if ( $thislen == 4 ) {
1676 $arr[$i - 1] .= "'";
1679 } elseif ( $thislen > 5 ) {
1680 // If there are more than 5 apostrophes in a row, assume they're all
1681 // text except for the last 5.
1682 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1683 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1687 // Count the number of occurrences of bold and italics mark-ups.
1688 if ( $thislen == 2 ) {
1690 } elseif ( $thislen == 3 ) {
1692 } elseif ( $thislen == 5 ) {
1698 // If there is an odd number of both bold and italics, it is likely
1699 // that one of the bold ones was meant to be an apostrophe followed
1700 // by italics. Which one we cannot know for certain, but it is more
1701 // likely to be one that has a single-letter word before it.
1702 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1703 $firstsingleletterword = -1;
1704 $firstmultiletterword = -1;
1706 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1707 if ( strlen( $arr[$i] ) == 3 ) {
1708 $x1 = substr( $arr[$i - 1], -1 );
1709 $x2 = substr( $arr[$i - 1], -2, 1 );
1710 if ( $x1 === ' ' ) {
1711 if ( $firstspace == -1 ) {
1714 } elseif ( $x2 === ' ' ) {
1715 $firstsingleletterword = $i;
1716 // if $firstsingleletterword is set, we don't
1717 // look at the other options, so we can bail early.
1720 if ( $firstmultiletterword == -1 ) {
1721 $firstmultiletterword = $i;
1727 // If there is a single-letter word, use it!
1728 if ( $firstsingleletterword > -1 ) {
1729 $arr[$firstsingleletterword] = "''";
1730 $arr[$firstsingleletterword - 1] .= "'";
1731 } elseif ( $firstmultiletterword > -1 ) {
1732 // If not, but there's a multi-letter word, use that one.
1733 $arr[$firstmultiletterword] = "''";
1734 $arr[$firstmultiletterword - 1] .= "'";
1735 } elseif ( $firstspace > -1 ) {
1736 // ... otherwise use the first one that has neither.
1737 // (notice that it is possible for all three to be -1 if, for example,
1738 // there is only one pentuple-apostrophe in the line)
1739 $arr[$firstspace] = "''";
1740 $arr[$firstspace - 1] .= "'";
1744 // Now let's actually convert our apostrophic mush to HTML!
1749 foreach ( $arr as $r ) {
1750 if ( ( $i %
2 ) == 0 ) {
1751 if ( $state === 'both' ) {
1757 $thislen = strlen( $r );
1758 if ( $thislen == 2 ) {
1759 if ( $state === 'i' ) {
1762 } elseif ( $state === 'bi' ) {
1765 } elseif ( $state === 'ib' ) {
1766 $output .= '</b></i><b>';
1768 } elseif ( $state === 'both' ) {
1769 $output .= '<b><i>' . $buffer . '</i>';
1771 } else { // $state can be 'b' or ''
1775 } elseif ( $thislen == 3 ) {
1776 if ( $state === 'b' ) {
1779 } elseif ( $state === 'bi' ) {
1780 $output .= '</i></b><i>';
1782 } elseif ( $state === 'ib' ) {
1785 } elseif ( $state === 'both' ) {
1786 $output .= '<i><b>' . $buffer . '</b>';
1788 } else { // $state can be 'i' or ''
1792 } elseif ( $thislen == 5 ) {
1793 if ( $state === 'b' ) {
1794 $output .= '</b><i>';
1796 } elseif ( $state === 'i' ) {
1797 $output .= '</i><b>';
1799 } elseif ( $state === 'bi' ) {
1800 $output .= '</i></b>';
1802 } elseif ( $state === 'ib' ) {
1803 $output .= '</b></i>';
1805 } elseif ( $state === 'both' ) {
1806 $output .= '<i><b>' . $buffer . '</b></i>';
1808 } else { // ($state == '')
1816 // Now close all remaining tags. Notice that the order is important.
1817 if ( $state === 'b' ||
$state === 'ib' ) {
1820 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1823 if ( $state === 'bi' ) {
1826 // There might be lonely ''''', so make sure we have a buffer
1827 if ( $state === 'both' && $buffer ) {
1828 $output .= '<b><i>' . $buffer . '</i></b>';
1834 * Replace external links (REL)
1836 * Note: this is all very hackish and the order of execution matters a lot.
1837 * Make sure to run tests/parser/parserTests.php if you change this code.
1841 * @param string $text
1843 * @throws MWException
1846 public function replaceExternalLinks( $text ) {
1847 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1848 if ( $bits === false ) {
1849 throw new MWException( "PCRE needs to be compiled with "
1850 . "--enable-unicode-properties in order for MediaWiki to function" );
1852 $s = array_shift( $bits );
1855 while ( $i < count( $bits ) ) {
1858 $text = $bits[$i++
];
1859 $trail = $bits[$i++
];
1861 # The characters '<' and '>' (which were escaped by
1862 # removeHTMLtags()) should not be included in
1863 # URLs, per RFC 2396.
1865 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1866 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1867 $url = substr( $url, 0, $m2[0][1] );
1870 # If the link text is an image URL, replace it with an <img> tag
1871 # This happened by accident in the original parser, but some people used it extensively
1872 $img = $this->maybeMakeExternalImage( $text );
1873 if ( $img !== false ) {
1879 # Set linktype for CSS
1882 # No link text, e.g. [http://domain.tld/some.link]
1883 if ( $text == '' ) {
1885 $langObj = $this->getTargetLanguage();
1886 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1887 $linktype = 'autonumber';
1889 # Have link text, e.g. [http://domain.tld/some.link text]s
1891 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1894 $text = $this->getConverterLanguage()->markNoConversion( $text );
1896 $url = Sanitizer
::cleanUrl( $url );
1898 # Use the encoded URL
1899 # This means that users can paste URLs directly into the text
1900 # Funny characters like ö aren't valid in URLs anyway
1901 # This was changed in August 2004
1902 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1903 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1905 # Register link in the output object.
1906 $this->mOutput
->addExternalLink( $url );
1913 * Get the rel attribute for a particular external link.
1916 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1917 * nofollow if appropriate
1918 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1919 * @return string|null Rel attribute for $url
1921 public static function getExternalLinkRel( $url = false, $title = null ) {
1922 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1923 $ns = $title ?
$title->getNamespace() : false;
1924 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1925 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1933 * Get an associative array of additional HTML attributes appropriate for a
1934 * particular external link. This currently may include rel => nofollow
1935 * (depending on configuration, namespace, and the URL's domain) and/or a
1936 * target attribute (depending on configuration).
1938 * @param string $url URL to extract the domain from for rel =>
1939 * nofollow if appropriate
1940 * @return array Associative array of HTML attributes
1942 public function getExternalLinkAttribs( $url ) {
1944 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1946 $target = $this->mOptions
->getExternalLinkTarget();
1948 $attribs['target'] = $target;
1949 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1950 // T133507. New windows can navigate parent cross-origin.
1951 // Including noreferrer due to lacking browser
1952 // support of noopener. Eventually noreferrer should be removed.
1953 if ( $rel !== '' ) {
1956 $rel .= 'noreferrer noopener';
1959 $attribs['rel'] = $rel;
1964 * Replace unusual escape codes in a URL with their equivalent characters
1966 * This generally follows the syntax defined in RFC 3986, with special
1967 * consideration for HTTP query strings.
1969 * @param string $url
1972 public static function normalizeLinkUrl( $url ) {
1973 # First, make sure unsafe characters are encoded
1974 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1976 return rawurlencode( $m[0] );
1982 $end = strlen( $url );
1984 # Fragment part - 'fragment'
1985 $start = strpos( $url, '#' );
1986 if ( $start !== false && $start < $end ) {
1987 $ret = self
::normalizeUrlComponent(
1988 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1992 # Query part - 'query' minus &=+;
1993 $start = strpos( $url, '?' );
1994 if ( $start !== false && $start < $end ) {
1995 $ret = self
::normalizeUrlComponent(
1996 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2000 # Scheme and path part - 'pchar'
2001 # (we assume no userinfo or encoded colons in the host)
2002 $ret = self
::normalizeUrlComponent(
2003 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2008 private static function normalizeUrlComponent( $component, $unsafe ) {
2009 $callback = function ( $matches ) use ( $unsafe ) {
2010 $char = urldecode( $matches[0] );
2011 $ord = ord( $char );
2012 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2016 # Leave it escaped, but use uppercase for a-f
2017 return strtoupper( $matches[0] );
2020 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2024 * make an image if it's allowed, either through the global
2025 * option, through the exception, or through the on-wiki whitelist
2027 * @param string $url
2031 private function maybeMakeExternalImage( $url ) {
2032 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2033 $imagesexception = !empty( $imagesfrom );
2035 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2036 if ( $imagesexception && is_array( $imagesfrom ) ) {
2037 $imagematch = false;
2038 foreach ( $imagesfrom as $match ) {
2039 if ( strpos( $url, $match ) === 0 ) {
2044 } elseif ( $imagesexception ) {
2045 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2047 $imagematch = false;
2050 if ( $this->mOptions
->getAllowExternalImages()
2051 ||
( $imagesexception && $imagematch )
2053 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2055 $text = Linker
::makeExternalImage( $url );
2058 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2059 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2061 $whitelist = explode(
2063 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2066 foreach ( $whitelist as $entry ) {
2067 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2068 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2071 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2072 # Image matches a whitelist entry
2073 $text = Linker
::makeExternalImage( $url );
2082 * Process [[ ]] wikilinks
2086 * @return string Processed text
2090 public function replaceInternalLinks( $s ) {
2091 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2096 * Process [[ ]] wikilinks (RIL)
2098 * @throws MWException
2099 * @return LinkHolderArray
2103 public function replaceInternalLinks2( &$s ) {
2104 global $wgExtraInterlanguageLinkPrefixes;
2106 static $tc = false, $e1, $e1_img;
2107 # the % is needed to support urlencoded titles as well
2109 $tc = Title
::legalChars() . '#%';
2110 # Match a link having the form [[namespace:link|alternate]]trail
2111 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2112 # Match cases where there is no "]]", which might still be images
2113 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2116 $holders = new LinkHolderArray( $this );
2118 # split the entire text string on occurrences of [[
2119 $a = StringUtils
::explode( '[[', ' ' . $s );
2120 # get the first element (all text up to first [[), and remove the space we added
2123 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2124 $s = substr( $s, 1 );
2126 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2128 if ( $useLinkPrefixExtension ) {
2129 # Match the end of a line for a word that's not followed by whitespace,
2130 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2132 $charset = $wgContLang->linkPrefixCharset();
2133 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2136 if ( is_null( $this->mTitle
) ) {
2137 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2139 $nottalk = !$this->mTitle
->isTalkPage();
2141 if ( $useLinkPrefixExtension ) {
2143 if ( preg_match( $e2, $s, $m ) ) {
2144 $first_prefix = $m[2];
2146 $first_prefix = false;
2152 $useSubpages = $this->areSubpagesAllowed();
2154 # Loop for each link
2155 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2156 # Check for excessive memory usage
2157 if ( $holders->isBig() ) {
2159 # Do the existence check, replace the link holders and clear the array
2160 $holders->replace( $s );
2164 if ( $useLinkPrefixExtension ) {
2165 if ( preg_match( $e2, $s, $m ) ) {
2172 if ( $first_prefix ) {
2173 $prefix = $first_prefix;
2174 $first_prefix = false;
2178 $might_be_img = false;
2180 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2182 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2183 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2184 # the real problem is with the $e1 regex
2186 # Still some problems for cases where the ] is meant to be outside punctuation,
2187 # and no image is in sight. See T4095.
2189 && substr( $m[3], 0, 1 ) === ']'
2190 && strpos( $text, '[' ) !== false
2192 $text .= ']'; # so that replaceExternalLinks($text) works later
2193 $m[3] = substr( $m[3], 1 );
2195 # fix up urlencoded title texts
2196 if ( strpos( $m[1], '%' ) !== false ) {
2197 # Should anchors '#' also be rejected?
2198 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2201 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2202 # Invalid, but might be an image with a link in its caption
2203 $might_be_img = true;
2205 if ( strpos( $m[1], '%' ) !== false ) {
2206 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2209 } else { # Invalid form; output directly
2210 $s .= $prefix . '[[' . $line;
2214 $origLink = ltrim( $m[1], ' ' );
2216 # Don't allow internal links to pages containing
2217 # PROTO: where PROTO is a valid URL protocol; these
2218 # should be external links.
2219 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2220 $s .= $prefix . '[[' . $line;
2224 # Make subpage if necessary
2225 if ( $useSubpages ) {
2226 $link = $this->maybeDoSubpageLink( $origLink, $text );
2231 // \x7f isn't a default legal title char, so most likely strip
2232 // markers will force us into the "invalid form" path above. But,
2233 // just in case, let's assert that xmlish tags aren't valid in
2234 // the title position.
2235 $unstrip = $this->mStripState
->killMarkers( $link );
2236 $noMarkers = ( $unstrip === $link );
2238 $nt = $noMarkers ? Title
::newFromText( $link ) : null;
2239 if ( $nt === null ) {
2240 $s .= $prefix . '[[' . $line;
2244 $ns = $nt->getNamespace();
2245 $iw = $nt->getInterwiki();
2247 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2249 if ( $might_be_img ) { # if this is actually an invalid link
2250 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2253 # look at the next 'line' to see if we can close it there
2255 $next_line = $a->current();
2256 if ( $next_line === false ||
$next_line === null ) {
2259 $m = explode( ']]', $next_line, 3 );
2260 if ( count( $m ) == 3 ) {
2261 # the first ]] closes the inner link, the second the image
2263 $text .= "[[{$m[0]}]]{$m[1]}";
2266 } elseif ( count( $m ) == 2 ) {
2267 # if there's exactly one ]] that's fine, we'll keep looking
2268 $text .= "[[{$m[0]}]]{$m[1]}";
2270 # if $next_line is invalid too, we need look no further
2271 $text .= '[[' . $next_line;
2276 # we couldn't find the end of this imageLink, so output it raw
2277 # but don't ignore what might be perfectly normal links in the text we've examined
2278 $holders->merge( $this->replaceInternalLinks2( $text ) );
2279 $s .= "{$prefix}[[$link|$text";
2280 # note: no $trail, because without an end, there *is* no trail
2283 } else { # it's not an image, so output it raw
2284 $s .= "{$prefix}[[$link|$text";
2285 # note: no $trail, because without an end, there *is* no trail
2290 $wasblank = ( $text == '' );
2294 # Strip off leading ':'
2295 $text = substr( $text, 1 );
2298 # T6598 madness. Handle the quotes only if they come from the alternate part
2299 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2300 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2301 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2302 $text = $this->doQuotes( $text );
2305 # Link not escaped by : , create the various objects
2306 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2309 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2310 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2311 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2314 # T26502: filter duplicates
2315 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2316 $this->mLangLinkLanguages
[$iw] = true;
2317 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2321 * Strip the whitespace interwiki links produce, see T10897
2323 $s = rtrim( $s . $prefix ) . $trail; # T175416
2327 if ( $ns == NS_FILE
) {
2328 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2330 # if no parameters were passed, $text
2331 # becomes something like "File:Foo.png",
2332 # which we don't want to pass on to the
2336 # recursively parse links inside the image caption
2337 # actually, this will parse them in any other parameters, too,
2338 # but it might be hard to fix that, and it doesn't matter ATM
2339 $text = $this->replaceExternalLinks( $text );
2340 $holders->merge( $this->replaceInternalLinks2( $text ) );
2342 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2343 $s .= $prefix . $this->armorLinks(
2344 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2347 } elseif ( $ns == NS_CATEGORY
) {
2349 * Strip the whitespace Category links produce, see T2087
2351 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2354 $sortkey = $this->getDefaultSort();
2358 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2359 $sortkey = str_replace( "\n", '', $sortkey );
2360 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2361 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2367 # Self-link checking. For some languages, variants of the title are checked in
2368 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2369 # for linking to a different variant.
2370 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2371 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2375 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2376 # @todo FIXME: Should do batch file existence checks, see comment below
2377 if ( $ns == NS_MEDIA
) {
2378 # Give extensions a chance to select the file revision for us
2381 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2382 [ $this, $nt, &$options, &$descQuery ] );
2383 # Fetch and register the file (file title may be different via hooks)
2384 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2385 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2386 $s .= $prefix . $this->armorLinks(
2387 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2391 # Some titles, such as valid special pages or files in foreign repos, should
2392 # be shown as bluelinks even though they're not included in the page table
2393 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2394 # batch file existence checks for NS_FILE and NS_MEDIA
2395 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2396 $this->mOutput
->addLink( $nt );
2397 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2399 # Links will be added to the output link list after checking
2400 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2407 * Render a forced-blue link inline; protect against double expansion of
2408 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2409 * Since this little disaster has to split off the trail text to avoid
2410 * breaking URLs in the following text without breaking trails on the
2411 * wiki links, it's been made into a horrible function.
2414 * @param string $text
2415 * @param string $trail
2416 * @param string $prefix
2417 * @return string HTML-wikitext mix oh yuck
2419 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2420 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2422 if ( $text == '' ) {
2423 $text = htmlspecialchars( $nt->getPrefixedText() );
2426 $link = $this->getLinkRenderer()->makeKnownLink(
2427 $nt, new HtmlArmor( "$prefix$text$inside" )
2430 return $this->armorLinks( $link ) . $trail;
2434 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2435 * going to go through further parsing steps before inline URL expansion.
2437 * Not needed quite as much as it used to be since free links are a bit
2438 * more sensible these days. But bracketed links are still an issue.
2440 * @param string $text More-or-less HTML
2441 * @return string Less-or-more HTML with NOPARSE bits
2443 public function armorLinks( $text ) {
2444 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2445 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2449 * Return true if subpage links should be expanded on this page.
2452 public function areSubpagesAllowed() {
2453 # Some namespaces don't allow subpages
2454 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2458 * Handle link to subpage if necessary
2460 * @param string $target The source of the link
2461 * @param string &$text The link text, modified as necessary
2462 * @return string The full name of the link
2465 public function maybeDoSubpageLink( $target, &$text ) {
2466 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2470 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2472 * @param string $text
2473 * @param bool $linestart Whether or not this is at the start of a line.
2475 * @return string The lists rendered as HTML
2477 public function doBlockLevels( $text, $linestart ) {
2478 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2482 * Return value of a magic variable (like PAGENAME)
2486 * @param string $index Magic variable identifier as mapped in MagicWord::$mVariableIDs
2487 * @param bool|PPFrame $frame
2489 * @throws MWException
2492 public function getVariableValue( $index, $frame = false ) {
2493 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2494 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2496 if ( is_null( $this->mTitle
) ) {
2497 // If no title set, bad things are going to happen
2498 // later. Title should always be set since this
2499 // should only be called in the middle of a parse
2500 // operation (but the unit-tests do funky stuff)
2501 throw new MWException( __METHOD__
. ' Should only be '
2502 . ' called while parsing (no title set)' );
2505 // Avoid PHP 7.1 warning from passing $this by reference
2509 * Some of these require message or data lookups and can be
2510 * expensive to check many times.
2512 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2513 if ( isset( $this->mVarCache
[$index] ) ) {
2514 return $this->mVarCache
[$index];
2518 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2519 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2521 $pageLang = $this->getFunctionLang();
2527 case 'currentmonth':
2528 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2530 case 'currentmonth1':
2531 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2533 case 'currentmonthname':
2534 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2536 case 'currentmonthnamegen':
2537 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2539 case 'currentmonthabbrev':
2540 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2543 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2546 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2549 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2552 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2554 case 'localmonthname':
2555 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2557 case 'localmonthnamegen':
2558 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2560 case 'localmonthabbrev':
2561 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2564 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2567 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2570 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2573 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2575 case 'fullpagename':
2576 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2578 case 'fullpagenamee':
2579 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2582 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2584 case 'subpagenamee':
2585 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2587 case 'rootpagename':
2588 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2590 case 'rootpagenamee':
2591 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2594 $this->mTitle
->getRootText()
2597 case 'basepagename':
2598 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2600 case 'basepagenamee':
2601 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2604 $this->mTitle
->getBaseText()
2607 case 'talkpagename':
2608 if ( $this->mTitle
->canHaveTalkPage() ) {
2609 $talkPage = $this->mTitle
->getTalkPage();
2610 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2615 case 'talkpagenamee':
2616 if ( $this->mTitle
->canHaveTalkPage() ) {
2617 $talkPage = $this->mTitle
->getTalkPage();
2618 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2623 case 'subjectpagename':
2624 $subjPage = $this->mTitle
->getSubjectPage();
2625 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2627 case 'subjectpagenamee':
2628 $subjPage = $this->mTitle
->getSubjectPage();
2629 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2631 case 'pageid': // requested in T25427
2632 $pageid = $this->getTitle()->getArticleID();
2633 if ( $pageid == 0 ) {
2634 # 0 means the page doesn't exist in the database,
2635 # which means the user is previewing a new page.
2636 # The vary-revision flag must be set, because the magic word
2637 # will have a different value once the page is saved.
2638 $this->mOutput
->setFlag( 'vary-revision' );
2639 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2641 $value = $pageid ?
$pageid : null;
2644 # Let the edit saving system know we should parse the page
2645 # *after* a revision ID has been assigned.
2646 $this->mOutput
->setFlag( 'vary-revision-id' );
2647 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2648 $value = $this->mRevisionId
;
2649 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2650 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2651 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2655 # Let the edit saving system know we should parse the page
2656 # *after* a revision ID has been assigned. This is for null edits.
2657 $this->mOutput
->setFlag( 'vary-revision' );
2658 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2659 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2661 case 'revisionday2':
2662 # Let the edit saving system know we should parse the page
2663 # *after* a revision ID has been assigned. This is for null edits.
2664 $this->mOutput
->setFlag( 'vary-revision' );
2665 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2666 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2668 case 'revisionmonth':
2669 # Let the edit saving system know we should parse the page
2670 # *after* a revision ID has been assigned. This is for null edits.
2671 $this->mOutput
->setFlag( 'vary-revision' );
2672 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2673 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2675 case 'revisionmonth1':
2676 # Let the edit saving system know we should parse the page
2677 # *after* a revision ID has been assigned. This is for null edits.
2678 $this->mOutput
->setFlag( 'vary-revision' );
2679 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2680 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2682 case 'revisionyear':
2683 # Let the edit saving system know we should parse the page
2684 # *after* a revision ID has been assigned. This is for null edits.
2685 $this->mOutput
->setFlag( 'vary-revision' );
2686 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2687 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2689 case 'revisiontimestamp':
2690 # Let the edit saving system know we should parse the page
2691 # *after* a revision ID has been assigned. This is for null edits.
2692 $this->mOutput
->setFlag( 'vary-revision' );
2693 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2694 $value = $this->getRevisionTimestamp();
2696 case 'revisionuser':
2697 # Let the edit saving system know we should parse the page
2698 # *after* a revision ID has been assigned for null edits.
2699 $this->mOutput
->setFlag( 'vary-user' );
2700 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2701 $value = $this->getRevisionUser();
2703 case 'revisionsize':
2704 $value = $this->getRevisionSize();
2707 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2710 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2712 case 'namespacenumber':
2713 $value = $this->mTitle
->getNamespace();
2716 $value = $this->mTitle
->canHaveTalkPage()
2717 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2721 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2723 case 'subjectspace':
2724 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2726 case 'subjectspacee':
2727 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2729 case 'currentdayname':
2730 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2733 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2736 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2739 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2742 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2743 # int to remove the padding
2744 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2747 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2749 case 'localdayname':
2750 $value = $pageLang->getWeekdayName(
2751 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2755 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2758 $value = $pageLang->time(
2759 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2765 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2768 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2769 # int to remove the padding
2770 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2773 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2775 case 'numberofarticles':
2776 $value = $pageLang->formatNum( SiteStats
::articles() );
2778 case 'numberoffiles':
2779 $value = $pageLang->formatNum( SiteStats
::images() );
2781 case 'numberofusers':
2782 $value = $pageLang->formatNum( SiteStats
::users() );
2784 case 'numberofactiveusers':
2785 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2787 case 'numberofpages':
2788 $value = $pageLang->formatNum( SiteStats
::pages() );
2790 case 'numberofadmins':
2791 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2793 case 'numberofedits':
2794 $value = $pageLang->formatNum( SiteStats
::edits() );
2796 case 'currenttimestamp':
2797 $value = wfTimestamp( TS_MW
, $ts );
2799 case 'localtimestamp':
2800 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2802 case 'currentversion':
2803 $value = SpecialVersion
::getVersion();
2806 return $wgArticlePath;
2812 return $wgServerName;
2814 return $wgScriptPath;
2816 return $wgStylePath;
2817 case 'directionmark':
2818 return $pageLang->getDirMark();
2819 case 'contentlanguage':
2820 global $wgLanguageCode;
2821 return $wgLanguageCode;
2822 case 'pagelanguage':
2823 $value = $pageLang->getCode();
2825 case 'cascadingsources':
2826 $value = CoreParserFunctions
::cascadingsources( $this );
2831 'ParserGetVariableValueSwitch',
2832 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2839 $this->mVarCache
[$index] = $value;
2846 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2850 public function initialiseVariables() {
2851 $variableIDs = MagicWord
::getVariableIDs();
2852 $substIDs = MagicWord
::getSubstIDs();
2854 $this->mVariables
= new MagicWordArray( $variableIDs );
2855 $this->mSubstWords
= new MagicWordArray( $substIDs );
2859 * Preprocess some wikitext and return the document tree.
2860 * This is the ghost of replace_variables().
2862 * @param string $text The text to parse
2863 * @param int $flags Bitwise combination of:
2864 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2865 * included. Default is to assume a direct page view.
2867 * The generated DOM tree must depend only on the input text and the flags.
2868 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2870 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2871 * change in the DOM tree for a given text, must be passed through the section identifier
2872 * in the section edit link and thus back to extractSections().
2874 * The output of this function is currently only cached in process memory, but a persistent
2875 * cache may be implemented at a later date which takes further advantage of these strict
2876 * dependency requirements.
2880 public function preprocessToDom( $text, $flags = 0 ) {
2881 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2886 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2892 public static function splitWhitespace( $s ) {
2893 $ltrimmed = ltrim( $s );
2894 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2895 $trimmed = rtrim( $ltrimmed );
2896 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2898 $w2 = substr( $ltrimmed, -$diff );
2902 return [ $w1, $trimmed, $w2 ];
2906 * Replace magic variables, templates, and template arguments
2907 * with the appropriate text. Templates are substituted recursively,
2908 * taking care to avoid infinite loops.
2910 * Note that the substitution depends on value of $mOutputType:
2911 * self::OT_WIKI: only {{subst:}} templates
2912 * self::OT_PREPROCESS: templates but not extension tags
2913 * self::OT_HTML: all templates and extension tags
2915 * @param string $text The text to transform
2916 * @param bool|PPFrame $frame Object describing the arguments passed to the
2917 * template. Arguments may also be provided as an associative array, as
2918 * was the usual case before MW1.12. Providing arguments this way may be
2919 * useful for extensions wishing to perform variable replacement
2921 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2922 * double-brace expansion.
2925 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2926 # Is there any text? Also, Prevent too big inclusions!
2927 $textSize = strlen( $text );
2928 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2932 if ( $frame === false ) {
2933 $frame = $this->getPreprocessor()->newFrame();
2934 } elseif ( !( $frame instanceof PPFrame
) ) {
2935 wfDebug( __METHOD__
. " called using plain parameters instead of "
2936 . "a PPFrame instance. Creating custom frame.\n" );
2937 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2940 $dom = $this->preprocessToDom( $text );
2941 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2942 $text = $frame->expand( $dom, $flags );
2948 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2950 * @param array $args
2954 public static function createAssocArgs( $args ) {
2957 foreach ( $args as $arg ) {
2958 $eqpos = strpos( $arg, '=' );
2959 if ( $eqpos === false ) {
2960 $assocArgs[$index++
] = $arg;
2962 $name = trim( substr( $arg, 0, $eqpos ) );
2963 $value = trim( substr( $arg, $eqpos +
1 ) );
2964 if ( $value === false ) {
2967 if ( $name !== false ) {
2968 $assocArgs[$name] = $value;
2977 * Warn the user when a parser limitation is reached
2978 * Will warn at most once the user per limitation type
2980 * The results are shown during preview and run through the Parser (See EditPage.php)
2982 * @param string $limitationType Should be one of:
2983 * 'expensive-parserfunction' (corresponding messages:
2984 * 'expensive-parserfunction-warning',
2985 * 'expensive-parserfunction-category')
2986 * 'post-expand-template-argument' (corresponding messages:
2987 * 'post-expand-template-argument-warning',
2988 * 'post-expand-template-argument-category')
2989 * 'post-expand-template-inclusion' (corresponding messages:
2990 * 'post-expand-template-inclusion-warning',
2991 * 'post-expand-template-inclusion-category')
2992 * 'node-count-exceeded' (corresponding messages:
2993 * 'node-count-exceeded-warning',
2994 * 'node-count-exceeded-category')
2995 * 'expansion-depth-exceeded' (corresponding messages:
2996 * 'expansion-depth-exceeded-warning',
2997 * 'expansion-depth-exceeded-category')
2998 * @param string|int|null $current Current value
2999 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3000 * exceeded, provide the values (optional)
3002 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3003 # does no harm if $current and $max are present but are unnecessary for the message
3004 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3005 # only during preview, and that would split the parser cache unnecessarily.
3006 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3008 $this->mOutput
->addWarning( $warning );
3009 $this->addTrackingCategory( "$limitationType-category" );
3013 * Return the text of a template, after recursively
3014 * replacing any variables or templates within the template.
3016 * @param array $piece The parts of the template
3017 * $piece['title']: the title, i.e. the part before the |
3018 * $piece['parts']: the parameter array
3019 * $piece['lineStart']: whether the brace was at the start of a line
3020 * @param PPFrame $frame The current frame, contains template arguments
3022 * @return string The text of the template
3024 public function braceSubstitution( $piece, $frame ) {
3027 // $text has been filled
3029 // wiki markup in $text should be escaped
3031 // $text is HTML, armour it against wikitext transformation
3033 // Force interwiki transclusion to be done in raw mode not rendered
3034 $forceRawInterwiki = false;
3035 // $text is a DOM node needing expansion in a child frame
3036 $isChildObj = false;
3037 // $text is a DOM node needing expansion in the current frame
3038 $isLocalObj = false;
3040 # Title object, where $text came from
3043 # $part1 is the bit before the first |, and must contain only title characters.
3044 # Various prefixes will be stripped from it later.
3045 $titleWithSpaces = $frame->expand( $piece['title'] );
3046 $part1 = trim( $titleWithSpaces );
3049 # Original title text preserved for various purposes
3050 $originalTitle = $part1;
3052 # $args is a list of argument nodes, starting from index 0, not including $part1
3053 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3054 # below won't work b/c this $args isn't an object
3055 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3057 $profileSection = null; // profile templates
3061 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3063 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3064 # Decide whether to expand template or keep wikitext as-is.
3065 if ( $this->ot
['wiki'] ) {
3066 if ( $substMatch === false ) {
3067 $literal = true; # literal when in PST with no prefix
3069 $literal = false; # expand when in PST with subst: or safesubst:
3072 if ( $substMatch == 'subst' ) {
3073 $literal = true; # literal when not in PST with plain subst:
3075 $literal = false; # expand when not in PST with safesubst: or no prefix
3079 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3086 if ( !$found && $args->getLength() == 0 ) {
3087 $id = $this->mVariables
->matchStartToEnd( $part1 );
3088 if ( $id !== false ) {
3089 $text = $this->getVariableValue( $id, $frame );
3090 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3091 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3097 # MSG, MSGNW and RAW
3100 $mwMsgnw = MagicWord
::get( 'msgnw' );
3101 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3104 # Remove obsolete MSG:
3105 $mwMsg = MagicWord
::get( 'msg' );
3106 $mwMsg->matchStartAndRemove( $part1 );
3110 $mwRaw = MagicWord
::get( 'raw' );
3111 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3112 $forceRawInterwiki = true;
3118 $colonPos = strpos( $part1, ':' );
3119 if ( $colonPos !== false ) {
3120 $func = substr( $part1, 0, $colonPos );
3121 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3122 $argsLength = $args->getLength();
3123 for ( $i = 0; $i < $argsLength; $i++
) {
3124 $funcArgs[] = $args->item( $i );
3127 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3128 } catch ( Exception
$ex ) {
3132 // Extract any forwarded flags
3133 if ( isset( $result['title'] ) ) {
3134 $title = $result['title'];
3136 if ( isset( $result['found'] ) ) {
3137 $found = $result['found'];
3139 if ( array_key_exists( 'text', $result ) ) {
3141 $text = $result['text'];
3143 if ( isset( $result['nowiki'] ) ) {
3144 $nowiki = $result['nowiki'];
3146 if ( isset( $result['isHTML'] ) ) {
3147 $isHTML = $result['isHTML'];
3149 if ( isset( $result['forceRawInterwiki'] ) ) {
3150 $forceRawInterwiki = $result['forceRawInterwiki'];
3152 if ( isset( $result['isChildObj'] ) ) {
3153 $isChildObj = $result['isChildObj'];
3155 if ( isset( $result['isLocalObj'] ) ) {
3156 $isLocalObj = $result['isLocalObj'];
3161 # Finish mangling title and then check for loops.
3162 # Set $title to a Title object and $titleText to the PDBK
3165 # Split the title into page and subpage
3167 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3168 if ( $part1 !== $relative ) {
3170 $ns = $this->mTitle
->getNamespace();
3172 $title = Title
::newFromText( $part1, $ns );
3174 $titleText = $title->getPrefixedText();
3175 # Check for language variants if the template is not found
3176 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3177 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3179 # Do recursion depth check
3180 $limit = $this->mOptions
->getMaxTemplateDepth();
3181 if ( $frame->depth
>= $limit ) {
3183 $text = '<span class="error">'
3184 . wfMessage( 'parser-template-recursion-depth-warning' )
3185 ->numParams( $limit )->inContentLanguage()->text()
3191 # Load from database
3192 if ( !$found && $title ) {
3193 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3194 if ( !$title->isExternal() ) {
3195 if ( $title->isSpecialPage()
3196 && $this->mOptions
->getAllowSpecialInclusion()
3197 && $this->ot
['html']
3199 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3200 // Pass the template arguments as URL parameters.
3201 // "uselang" will have no effect since the Language object
3202 // is forced to the one defined in ParserOptions.
3204 $argsLength = $args->getLength();
3205 for ( $i = 0; $i < $argsLength; $i++
) {
3206 $bits = $args->item( $i )->splitArg();
3207 if ( strval( $bits['index'] ) === '' ) {
3208 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3209 $value = trim( $frame->expand( $bits['value'] ) );
3210 $pageArgs[$name] = $value;
3214 // Create a new context to execute the special page
3215 $context = new RequestContext
;
3216 $context->setTitle( $title );
3217 $context->setRequest( new FauxRequest( $pageArgs ) );
3218 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3219 $context->setUser( $this->getUser() );
3221 // If this page is cached, then we better not be per user.
3222 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3224 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3225 $ret = SpecialPageFactory
::capturePath(
3226 $title, $context, $this->getLinkRenderer() );
3228 $text = $context->getOutput()->getHTML();
3229 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3232 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3233 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3234 $specialPage->maxIncludeCacheTime()
3238 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3239 $found = false; # access denied
3240 wfDebug( __METHOD__
. ": template inclusion denied for " .
3241 $title->getPrefixedDBkey() . "\n" );
3243 list( $text, $title ) = $this->getTemplateDom( $title );
3244 if ( $text !== false ) {
3250 # If the title is valid but undisplayable, make a link to it
3251 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3252 $text = "[[:$titleText]]";
3255 } elseif ( $title->isTrans() ) {
3256 # Interwiki transclusion
3257 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3258 $text = $this->interwikiTransclude( $title, 'render' );
3261 $text = $this->interwikiTransclude( $title, 'raw' );
3262 # Preprocess it like a template
3263 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3269 # Do infinite loop check
3270 # This has to be done after redirect resolution to avoid infinite loops via redirects
3271 if ( !$frame->loopCheck( $title ) ) {
3273 $text = '<span class="error">'
3274 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3276 $this->addTrackingCategory( 'template-loop-category' );
3277 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3278 wfEscapeWikiText( $titleText ) )->text() );
3279 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3283 # If we haven't found text to substitute by now, we're done
3284 # Recover the source wikitext and return it
3286 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3287 if ( $profileSection ) {
3288 $this->mProfiler
->scopedProfileOut( $profileSection );
3290 return [ 'object' => $text ];
3293 # Expand DOM-style return values in a child frame
3294 if ( $isChildObj ) {
3295 # Clean up argument array
3296 $newFrame = $frame->newChild( $args, $title );
3299 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3300 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3301 # Expansion is eligible for the empty-frame cache
3302 $text = $newFrame->cachedExpand( $titleText, $text );
3304 # Uncached expansion
3305 $text = $newFrame->expand( $text );
3308 if ( $isLocalObj && $nowiki ) {
3309 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3310 $isLocalObj = false;
3313 if ( $profileSection ) {
3314 $this->mProfiler
->scopedProfileOut( $profileSection );
3317 # Replace raw HTML by a placeholder
3319 $text = $this->insertStripItem( $text );
3320 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3321 # Escape nowiki-style return values
3322 $text = wfEscapeWikiText( $text );
3323 } elseif ( is_string( $text )
3324 && !$piece['lineStart']
3325 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3327 # T2529: if the template begins with a table or block-level
3328 # element, it should be treated as beginning a new line.
3329 # This behavior is somewhat controversial.
3330 $text = "\n" . $text;
3333 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3334 # Error, oversize inclusion
3335 if ( $titleText !== false ) {
3336 # Make a working, properly escaped link if possible (T25588)
3337 $text = "[[:$titleText]]";
3339 # This will probably not be a working link, but at least it may
3340 # provide some hint of where the problem is
3341 preg_replace( '/^:/', '', $originalTitle );
3342 $text = "[[:$originalTitle]]";
3344 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3345 . 'post-expand include size too large -->' );
3346 $this->limitationWarn( 'post-expand-template-inclusion' );
3349 if ( $isLocalObj ) {
3350 $ret = [ 'object' => $text ];
3352 $ret = [ 'text' => $text ];
3359 * Call a parser function and return an array with text and flags.
3361 * The returned array will always contain a boolean 'found', indicating
3362 * whether the parser function was found or not. It may also contain the
3364 * text: string|object, resulting wikitext or PP DOM object
3365 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3366 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3367 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3368 * nowiki: bool, wiki markup in $text should be escaped
3371 * @param PPFrame $frame The current frame, contains template arguments
3372 * @param string $function Function name
3373 * @param array $args Arguments to the function
3374 * @throws MWException
3377 public function callParserFunction( $frame, $function, array $args = [] ) {
3380 # Case sensitive functions
3381 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3382 $function = $this->mFunctionSynonyms
[1][$function];
3384 # Case insensitive functions
3385 $function = $wgContLang->lc( $function );
3386 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3387 $function = $this->mFunctionSynonyms
[0][$function];
3389 return [ 'found' => false ];
3393 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3395 // Avoid PHP 7.1 warning from passing $this by reference
3398 $allArgs = [ &$parser ];
3399 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3400 # Convert arguments to PPNodes and collect for appending to $allArgs
3402 foreach ( $args as $k => $v ) {
3403 if ( $v instanceof PPNode ||
$k === 0 ) {
3406 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3410 # Add a frame parameter, and pass the arguments as an array
3411 $allArgs[] = $frame;
3412 $allArgs[] = $funcArgs;
3414 # Convert arguments to plain text and append to $allArgs
3415 foreach ( $args as $k => $v ) {
3416 if ( $v instanceof PPNode
) {
3417 $allArgs[] = trim( $frame->expand( $v ) );
3418 } elseif ( is_int( $k ) && $k >= 0 ) {
3419 $allArgs[] = trim( $v );
3421 $allArgs[] = trim( "$k=$v" );
3426 $result = call_user_func_array( $callback, $allArgs );
3428 # The interface for function hooks allows them to return a wikitext
3429 # string or an array containing the string and any flags. This mungs
3430 # things around to match what this method should return.
3431 if ( !is_array( $result ) ) {
3437 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3438 $result['text'] = $result[0];
3440 unset( $result[0] );
3447 $preprocessFlags = 0;
3448 if ( isset( $result['noparse'] ) ) {
3449 $noparse = $result['noparse'];
3451 if ( isset( $result['preprocessFlags'] ) ) {
3452 $preprocessFlags = $result['preprocessFlags'];
3456 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3457 $result['isChildObj'] = true;
3464 * Get the semi-parsed DOM representation of a template with a given title,
3465 * and its redirect destination title. Cached.
3467 * @param Title $title
3471 public function getTemplateDom( $title ) {
3472 $cacheTitle = $title;
3473 $titleText = $title->getPrefixedDBkey();
3475 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3476 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3477 $title = Title
::makeTitle( $ns, $dbk );
3478 $titleText = $title->getPrefixedDBkey();
3480 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3481 return [ $this->mTplDomCache
[$titleText], $title ];
3484 # Cache miss, go to the database
3485 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3487 if ( $text === false ) {
3488 $this->mTplDomCache
[$titleText] = false;
3489 return [ false, $title ];
3492 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3493 $this->mTplDomCache
[$titleText] = $dom;
3495 if ( !$title->equals( $cacheTitle ) ) {
3496 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3497 [ $title->getNamespace(), $title->getDBkey() ];
3500 return [ $dom, $title ];
3504 * Fetch the current revision of a given title. Note that the revision
3505 * (and even the title) may not exist in the database, so everything
3506 * contributing to the output of the parser should use this method
3507 * where possible, rather than getting the revisions themselves. This
3508 * method also caches its results, so using it benefits performance.
3511 * @param Title $title
3514 public function fetchCurrentRevisionOfTitle( $title ) {
3515 $cacheKey = $title->getPrefixedDBkey();
3516 if ( !$this->currentRevisionCache
) {
3517 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3519 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3520 $this->currentRevisionCache
->set( $cacheKey,
3521 // Defaults to Parser::statelessFetchRevision()
3522 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3525 return $this->currentRevisionCache
->get( $cacheKey );
3529 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3530 * without passing them on to it.
3533 * @param Title $title
3534 * @param Parser|bool $parser
3535 * @return Revision|bool False if missing
3537 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3538 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3544 * Fetch the unparsed text of a template and register a reference to it.
3545 * @param Title $title
3546 * @return array ( string or false, Title )
3548 public function fetchTemplateAndTitle( $title ) {
3549 // Defaults to Parser::statelessFetchTemplate()
3550 $templateCb = $this->mOptions
->getTemplateCallback();
3551 $stuff = call_user_func( $templateCb, $title, $this );
3552 // We use U+007F DELETE to distinguish strip markers from regular text.
3553 $text = $stuff['text'];
3554 if ( is_string( $stuff['text'] ) ) {
3555 $text = strtr( $text, "\x7f", "?" );
3557 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3558 if ( isset( $stuff['deps'] ) ) {
3559 foreach ( $stuff['deps'] as $dep ) {
3560 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3561 if ( $dep['title']->equals( $this->getTitle() ) ) {
3562 // If we transclude ourselves, the final result
3563 // will change based on the new version of the page
3564 $this->mOutput
->setFlag( 'vary-revision' );
3568 return [ $text, $finalTitle ];
3572 * Fetch the unparsed text of a template and register a reference to it.
3573 * @param Title $title
3574 * @return string|bool
3576 public function fetchTemplate( $title ) {
3577 return $this->fetchTemplateAndTitle( $title )[0];
3581 * Static function to get a template
3582 * Can be overridden via ParserOptions::setTemplateCallback().
3584 * @param Title $title
3585 * @param bool|Parser $parser
3589 public static function statelessFetchTemplate( $title, $parser = false ) {
3590 $text = $skip = false;
3591 $finalTitle = $title;
3594 # Loop to fetch the article, with up to 1 redirect
3595 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3596 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3597 # Give extensions a chance to select the revision instead
3598 $id = false; # Assume current
3599 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3600 [ $parser, $title, &$skip, &$id ] );
3606 'page_id' => $title->getArticleID(),
3613 $rev = Revision
::newFromId( $id );
3614 } elseif ( $parser ) {
3615 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3617 $rev = Revision
::newFromTitle( $title );
3619 $rev_id = $rev ?
$rev->getId() : 0;
3620 # If there is no current revision, there is no page
3621 if ( $id === false && !$rev ) {
3622 $linkCache = LinkCache
::singleton();
3623 $linkCache->addBadLinkObj( $title );
3628 'page_id' => $title->getArticleID(),
3629 'rev_id' => $rev_id ];
3630 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3631 # We fetched a rev from a different title; register it too...
3633 'title' => $rev->getTitle(),
3634 'page_id' => $rev->getPage(),
3635 'rev_id' => $rev_id ];
3639 $content = $rev->getContent();
3640 $text = $content ?
$content->getWikitextForTransclusion() : null;
3642 Hooks
::run( 'ParserFetchTemplate',
3643 [ $parser, $title, $rev, &$text, &$deps ] );
3645 if ( $text === false ||
$text === null ) {
3649 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3651 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3652 if ( !$message->exists() ) {
3656 $content = $message->content();
3657 $text = $message->plain();
3665 $finalTitle = $title;
3666 $title = $content->getRedirectTarget();
3670 'finalTitle' => $finalTitle,
3675 * Fetch a file and its title and register a reference to it.
3676 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3677 * @param Title $title
3678 * @param array $options Array of options to RepoGroup::findFile
3681 public function fetchFile( $title, $options = [] ) {
3682 return $this->fetchFileAndTitle( $title, $options )[0];
3686 * Fetch a file and its title and register a reference to it.
3687 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3688 * @param Title $title
3689 * @param array $options Array of options to RepoGroup::findFile
3690 * @return array ( File or false, Title of file )
3692 public function fetchFileAndTitle( $title, $options = [] ) {
3693 $file = $this->fetchFileNoRegister( $title, $options );
3695 $time = $file ?
$file->getTimestamp() : false;
3696 $sha1 = $file ?
$file->getSha1() : false;
3697 # Register the file as a dependency...
3698 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3699 if ( $file && !$title->equals( $file->getTitle() ) ) {
3700 # Update fetched file title
3701 $title = $file->getTitle();
3702 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3704 return [ $file, $title ];
3708 * Helper function for fetchFileAndTitle.
3710 * Also useful if you need to fetch a file but not use it yet,
3711 * for example to get the file's handler.
3713 * @param Title $title
3714 * @param array $options Array of options to RepoGroup::findFile
3717 protected function fetchFileNoRegister( $title, $options = [] ) {
3718 if ( isset( $options['broken'] ) ) {
3719 $file = false; // broken thumbnail forced by hook
3720 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3721 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3722 } else { // get by (name,timestamp)
3723 $file = wfFindFile( $title, $options );
3729 * Transclude an interwiki link.
3731 * @param Title $title
3732 * @param string $action
3736 public function interwikiTransclude( $title, $action ) {
3737 global $wgEnableScaryTranscluding;
3739 if ( !$wgEnableScaryTranscluding ) {
3740 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3743 $url = $title->getFullURL( [ 'action' => $action ] );
3745 if ( strlen( $url ) > 255 ) {
3746 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3748 return $this->fetchScaryTemplateMaybeFromCache( $url );
3752 * @param string $url
3753 * @return mixed|string
3755 public function fetchScaryTemplateMaybeFromCache( $url ) {
3756 global $wgTranscludeCacheExpiry;
3757 $dbr = wfGetDB( DB_REPLICA
);
3758 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3759 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3760 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3762 return $obj->tc_contents
;
3765 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3766 $status = $req->execute(); // Status object
3767 if ( $status->isOK() ) {
3768 $text = $req->getContent();
3769 } elseif ( $req->getStatus() != 200 ) {
3770 // Though we failed to fetch the content, this status is useless.
3771 return wfMessage( 'scarytranscludefailed-httpstatus' )
3772 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3774 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3777 $dbw = wfGetDB( DB_MASTER
);
3778 $dbw->replace( 'transcache', [ 'tc_url' ], [
3780 'tc_time' => $dbw->timestamp( time() ),
3781 'tc_contents' => $text
3787 * Triple brace replacement -- used for template arguments
3790 * @param array $piece
3791 * @param PPFrame $frame
3795 public function argSubstitution( $piece, $frame ) {
3797 $parts = $piece['parts'];
3798 $nameWithSpaces = $frame->expand( $piece['title'] );
3799 $argName = trim( $nameWithSpaces );
3801 $text = $frame->getArgument( $argName );
3802 if ( $text === false && $parts->getLength() > 0
3803 && ( $this->ot
['html']
3805 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3808 # No match in frame, use the supplied default
3809 $object = $parts->item( 0 )->getChildren();
3811 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3812 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3813 $this->limitationWarn( 'post-expand-template-argument' );
3816 if ( $text === false && $object === false ) {
3818 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3820 if ( $error !== false ) {
3823 if ( $object !== false ) {
3824 $ret = [ 'object' => $object ];
3826 $ret = [ 'text' => $text ];
3833 * Return the text to be used for a given extension tag.
3834 * This is the ghost of strip().
3836 * @param array $params Associative array of parameters:
3837 * name PPNode for the tag name
3838 * attr PPNode for unparsed text where tag attributes are thought to be
3839 * attributes Optional associative array of parsed attributes
3840 * inner Contents of extension element
3841 * noClose Original text did not have a close tag
3842 * @param PPFrame $frame
3844 * @throws MWException
3847 public function extensionSubstitution( $params, $frame ) {
3848 static $errorStr = '<span class="error">';
3849 static $errorLen = 20;
3851 $name = $frame->expand( $params['name'] );
3852 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3853 // Probably expansion depth or node count exceeded. Just punt the
3858 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3859 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3864 // We can't safely check if the expansion for $content resulted in an
3865 // error, because the content could happen to be the error string
3867 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3869 $marker = self
::MARKER_PREFIX
. "-$name-"
3870 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3872 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3873 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3874 if ( $isFunctionTag ) {
3875 $markerType = 'none';
3877 $markerType = 'general';
3879 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3880 $name = strtolower( $name );
3881 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3882 if ( isset( $params['attributes'] ) ) {
3883 $attributes = $attributes +
$params['attributes'];
3886 if ( isset( $this->mTagHooks
[$name] ) ) {
3887 $output = call_user_func_array( $this->mTagHooks
[$name],
3888 [ $content, $attributes, $this, $frame ] );
3889 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3890 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3892 // Avoid PHP 7.1 warning from passing $this by reference
3894 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3896 $output = '<span class="error">Invalid tag extension name: ' .
3897 htmlspecialchars( $name ) . '</span>';
3900 if ( is_array( $output ) ) {
3903 $output = $flags[0];
3904 if ( isset( $flags['markerType'] ) ) {
3905 $markerType = $flags['markerType'];
3909 if ( is_null( $attrText ) ) {
3912 if ( isset( $params['attributes'] ) ) {
3913 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3914 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3915 htmlspecialchars( $attrValue ) . '"';
3918 if ( $content === null ) {
3919 $output = "<$name$attrText/>";
3921 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3922 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3926 $output = "<$name$attrText>$content$close";
3930 if ( $markerType === 'none' ) {
3932 } elseif ( $markerType === 'nowiki' ) {
3933 $this->mStripState
->addNoWiki( $marker, $output );
3934 } elseif ( $markerType === 'general' ) {
3935 $this->mStripState
->addGeneral( $marker, $output );
3937 throw new MWException( __METHOD__
. ': invalid marker type' );
3943 * Increment an include size counter
3945 * @param string $type The type of expansion
3946 * @param int $size The size of the text
3947 * @return bool False if this inclusion would take it over the maximum, true otherwise
3949 public function incrementIncludeSize( $type, $size ) {
3950 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3953 $this->mIncludeSizes
[$type] +
= $size;
3959 * Increment the expensive function count
3961 * @return bool False if the limit has been exceeded
3963 public function incrementExpensiveFunctionCount() {
3964 $this->mExpensiveFunctionCount++
;
3965 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3969 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3970 * Fills $this->mDoubleUnderscores, returns the modified text
3972 * @param string $text
3976 public function doDoubleUnderscore( $text ) {
3977 # The position of __TOC__ needs to be recorded
3978 $mw = MagicWord
::get( 'toc' );
3979 if ( $mw->match( $text ) ) {
3980 $this->mShowToc
= true;
3981 $this->mForceTocPosition
= true;
3983 # Set a placeholder. At the end we'll fill it in with the TOC.
3984 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
3986 # Only keep the first one.
3987 $text = $mw->replace( '', $text );
3990 # Now match and remove the rest of them
3991 $mwa = MagicWord
::getDoubleUnderscoreArray();
3992 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3994 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3995 $this->mOutput
->mNoGallery
= true;
3997 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3998 $this->mShowToc
= false;
4000 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4001 && $this->mTitle
->getNamespace() == NS_CATEGORY
4003 $this->addTrackingCategory( 'hidden-category-category' );
4005 # (T10068) Allow control over whether robots index a page.
4006 # __INDEX__ always overrides __NOINDEX__, see T16899
4007 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4008 $this->mOutput
->setIndexPolicy( 'noindex' );
4009 $this->addTrackingCategory( 'noindex-category' );
4011 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4012 $this->mOutput
->setIndexPolicy( 'index' );
4013 $this->addTrackingCategory( 'index-category' );
4016 # Cache all double underscores in the database
4017 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4018 $this->mOutput
->setProperty( $key, '' );
4025 * @see ParserOutput::addTrackingCategory()
4026 * @param string $msg Message key
4027 * @return bool Whether the addition was successful
4029 public function addTrackingCategory( $msg ) {
4030 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4034 * This function accomplishes several tasks:
4035 * 1) Auto-number headings if that option is enabled
4036 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4037 * 3) Add a Table of contents on the top for users who have enabled the option
4038 * 4) Auto-anchor headings
4040 * It loops through all headlines, collects the necessary data, then splits up the
4041 * string and re-inserts the newly formatted headlines.
4043 * @param string $text
4044 * @param string $origText Original, untouched wikitext
4045 * @param bool $isMain
4046 * @return mixed|string
4049 public function formatHeadings( $text, $origText, $isMain = true ) {
4050 global $wgMaxTocLevel;
4052 # Inhibit editsection links if requested in the page
4053 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4054 $maybeShowEditLink = false;
4056 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4059 # Get all headlines for numbering them and adding funky stuff like [edit]
4060 # links - this is for later, but we need the number of headlines right now
4061 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4062 # be trimmed here since whitespace in HTML headings is significant.
4064 $numMatches = preg_match_all(
4065 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4070 # if there are fewer than 4 headlines in the article, do not show TOC
4071 # unless it's been explicitly enabled.
4072 $enoughToc = $this->mShowToc
&&
4073 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4075 # Allow user to stipulate that a page should have a "new section"
4076 # link added via __NEWSECTIONLINK__
4077 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4078 $this->mOutput
->setNewSection( true );
4081 # Allow user to remove the "new section"
4082 # link via __NONEWSECTIONLINK__
4083 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4084 $this->mOutput
->hideNewSection( true );
4087 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4088 # override above conditions and always show TOC above first header
4089 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4090 $this->mShowToc
= true;
4098 # Ugh .. the TOC should have neat indentation levels which can be
4099 # passed to the skin functions. These are determined here
4103 $sublevelCount = [];
4109 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4110 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4111 $oldType = $this->mOutputType
;
4112 $this->setOutputType( self
::OT_WIKI
);
4113 $frame = $this->getPreprocessor()->newFrame();
4114 $root = $this->preprocessToDom( $origText );
4115 $node = $root->getFirstChild();
4120 $headlines = $numMatches !== false ?
$matches[3] : [];
4122 foreach ( $headlines as $headline ) {
4123 $isTemplate = false;
4125 $sectionIndex = false;
4127 $markerMatches = [];
4128 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4129 $serial = $markerMatches[1];
4130 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4131 $isTemplate = ( $titleText != $baseTitleText );
4132 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4136 $prevlevel = $level;
4138 $level = $matches[1][$headlineCount];
4140 if ( $level > $prevlevel ) {
4141 # Increase TOC level
4143 $sublevelCount[$toclevel] = 0;
4144 if ( $toclevel < $wgMaxTocLevel ) {
4145 $prevtoclevel = $toclevel;
4146 $toc .= Linker
::tocIndent();
4149 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4150 # Decrease TOC level, find level to jump to
4152 for ( $i = $toclevel; $i > 0; $i-- ) {
4153 if ( $levelCount[$i] == $level ) {
4154 # Found last matching level
4157 } elseif ( $levelCount[$i] < $level ) {
4158 # Found first matching level below current level
4166 if ( $toclevel < $wgMaxTocLevel ) {
4167 if ( $prevtoclevel < $wgMaxTocLevel ) {
4168 # Unindent only if the previous toc level was shown :p
4169 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4170 $prevtoclevel = $toclevel;
4172 $toc .= Linker
::tocLineEnd();
4176 # No change in level, end TOC line
4177 if ( $toclevel < $wgMaxTocLevel ) {
4178 $toc .= Linker
::tocLineEnd();
4182 $levelCount[$toclevel] = $level;
4184 # count number of headlines for each level
4185 $sublevelCount[$toclevel]++
;
4187 for ( $i = 1; $i <= $toclevel; $i++
) {
4188 if ( !empty( $sublevelCount[$i] ) ) {
4192 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4197 # The safe header is a version of the header text safe to use for links
4199 # Remove link placeholders by the link text.
4200 # <!--LINK number-->
4202 # link text with suffix
4203 # Do this before unstrip since link text can contain strip markers
4204 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4206 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4207 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4209 # Strip out HTML (first regex removes any tag not allowed)
4211 # * <sup> and <sub> (T10393)
4215 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4216 # * <s> and <strike> (T35715)
4217 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4218 # to allow setting directionality in toc items.
4219 $tocline = preg_replace(
4221 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4222 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4228 # Strip '<span></span>', which is the result from the above if
4229 # <span id="foo"></span> is used to produce an additional anchor
4231 $tocline = str_replace( '<span></span>', '', $tocline );
4233 $tocline = trim( $tocline );
4235 # For the anchor, strip out HTML-y stuff period
4236 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4237 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4239 # Save headline for section edit hint before it's escaped
4240 $headlineHint = $safeHeadline;
4242 # Decode HTML entities
4243 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4245 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4247 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4248 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4249 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4250 if ( $fallbackHeadline === $safeHeadline ) {
4251 # No reason to have both (in fact, we can't)
4252 $fallbackHeadline = false;
4255 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4256 # @todo FIXME: We may be changing them depending on the current locale.
4257 $arrayKey = strtolower( $safeHeadline );
4258 if ( $fallbackHeadline === false ) {
4259 $fallbackArrayKey = false;
4261 $fallbackArrayKey = strtolower( $fallbackHeadline );
4264 # Create the anchor for linking from the TOC to the section
4265 $anchor = $safeHeadline;
4266 $fallbackAnchor = $fallbackHeadline;
4267 if ( isset( $refers[$arrayKey] ) ) {
4268 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4269 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4271 $linkAnchor .= "_$i";
4272 $refers["${arrayKey}_$i"] = true;
4274 $refers[$arrayKey] = true;
4276 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4277 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4278 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4279 $fallbackAnchor .= "_$i";
4280 $refers["${fallbackArrayKey}_$i"] = true;
4282 $refers[$fallbackArrayKey] = true;
4285 # Don't number the heading if it is the only one (looks silly)
4286 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4287 # the two are different if the line contains a link
4288 $headline = Html
::element(
4290 [ 'class' => 'mw-headline-number' ],
4292 ) . ' ' . $headline;
4295 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4296 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4297 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4300 # Add the section to the section tree
4301 # Find the DOM node for this header
4302 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4303 while ( $node && !$noOffset ) {
4304 if ( $node->getName() === 'h' ) {
4305 $bits = $node->splitHeading();
4306 if ( $bits['i'] == $sectionIndex ) {
4310 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4311 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4312 $node = $node->getNextSibling();
4315 'toclevel' => $toclevel,
4318 'number' => $numbering,
4319 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4320 'fromtitle' => $titleText,
4321 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4322 'anchor' => $anchor,
4325 # give headline the correct <h#> tag
4326 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4327 // Output edit section links as markers with styles that can be customized by skins
4328 if ( $isTemplate ) {
4329 # Put a T flag in the section identifier, to indicate to extractSections()
4330 # that sections inside <includeonly> should be counted.
4331 $editsectionPage = $titleText;
4332 $editsectionSection = "T-$sectionIndex";
4333 $editsectionContent = null;
4335 $editsectionPage = $this->mTitle
->getPrefixedText();
4336 $editsectionSection = $sectionIndex;
4337 $editsectionContent = $headlineHint;
4339 // We use a bit of pesudo-xml for editsection markers. The
4340 // language converter is run later on. Using a UNIQ style marker
4341 // leads to the converter screwing up the tokens when it
4342 // converts stuff. And trying to insert strip tags fails too. At
4343 // this point all real inputted tags have already been escaped,
4344 // so we don't have to worry about a user trying to input one of
4345 // these markers directly. We use a page and section attribute
4346 // to stop the language converter from converting these
4347 // important bits of data, but put the headline hint inside a
4348 // content block because the language converter is supposed to
4349 // be able to convert that piece of data.
4350 // Gets replaced with html in ParserOutput::getText
4351 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4352 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4353 if ( $editsectionContent !== null ) {
4354 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4361 $head[$headlineCount] = Linker
::makeHeadline( $level,
4362 $matches['attrib'][$headlineCount], $anchor, $headline,
4363 $editlink, $fallbackAnchor );
4368 $this->setOutputType( $oldType );
4370 # Never ever show TOC if no headers
4371 if ( $numVisible < 1 ) {
4376 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4377 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4379 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4380 $this->mOutput
->setTOCHTML( $toc );
4381 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4385 $this->mOutput
->setSections( $tocraw );
4388 # split up and insert constructed headlines
4389 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4392 // build an array of document sections
4394 foreach ( $blocks as $block ) {
4395 // $head is zero-based, sections aren't.
4396 if ( empty( $head[$i - 1] ) ) {
4397 $sections[$i] = $block;
4399 $sections[$i] = $head[$i - 1] . $block;
4403 * Send a hook, one per section.
4404 * The idea here is to be able to make section-level DIVs, but to do so in a
4405 * lower-impact, more correct way than r50769
4408 * $section : the section number
4409 * &$sectionContent : ref to the content of the section
4410 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4412 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4417 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4418 // append the TOC at the beginning
4419 // Top anchor now in skin
4420 $sections[0] = $sections[0] . $toc . "\n";
4423 $full .= implode( '', $sections );
4425 if ( $this->mForceTocPosition
) {
4426 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4433 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4434 * conversion, substituting signatures, {{subst:}} templates, etc.
4436 * @param string $text The text to transform
4437 * @param Title $title The Title object for the current article
4438 * @param User $user The User object describing the current user
4439 * @param ParserOptions $options Parsing options
4440 * @param bool $clearState Whether to clear the parser state first
4441 * @return string The altered wiki markup
4443 public function preSaveTransform( $text, Title
$title, User
$user,
4444 ParserOptions
$options, $clearState = true
4446 if ( $clearState ) {
4447 $magicScopeVariable = $this->lock();
4449 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4450 $this->setUser( $user );
4452 // Strip U+0000 NULL (T159174)
4453 $text = str_replace( "\000", '', $text );
4455 // We still normalize line endings for backwards-compatibility
4456 // with other code that just calls PST, but this should already
4457 // be handled in TextContent subclasses
4458 $text = TextContent
::normalizeLineEndings( $text );
4460 if ( $options->getPreSaveTransform() ) {
4461 $text = $this->pstPass2( $text, $user );
4463 $text = $this->mStripState
->unstripBoth( $text );
4465 $this->setUser( null ); # Reset
4471 * Pre-save transform helper function
4473 * @param string $text
4478 private function pstPass2( $text, $user ) {
4481 # Note: This is the timestamp saved as hardcoded wikitext to
4482 # the database, we use $wgContLang here in order to give
4483 # everyone the same signature and use the default one rather
4484 # than the one selected in each user's preferences.
4486 $ts = $this->mOptions
->getTimestamp();
4487 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4488 $ts = $timestamp->format( 'YmdHis' );
4489 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4491 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4493 # Variable replacement
4494 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4495 $text = $this->replaceVariables( $text );
4497 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4498 # which may corrupt this parser instance via its wfMessage()->text() call-
4501 if ( strpos( $text, '~~~' ) !== false ) {
4502 $sigText = $this->getUserSig( $user );
4503 $text = strtr( $text, [
4505 '~~~~' => "$sigText $d",
4508 # The main two signature forms used above are time-sensitive
4509 $this->mOutput
->setFlag( 'user-signature' );
4512 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4513 $tc = '[' . Title
::legalChars() . ']';
4514 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4516 // [[ns:page (context)|]]
4517 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4518 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4519 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4520 // [[ns:page (context), context|]] (using either single or double-width comma)
4521 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4522 // [[|page]] (reverse pipe trick: add context from page title)
4523 $p2 = "/\[\[\\|($tc+)]]/";
4525 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4526 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4527 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4528 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4530 $t = $this->mTitle
->getText();
4532 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4533 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4534 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4535 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4537 # if there's no context, don't bother duplicating the title
4538 $text = preg_replace( $p2, '[[\\1]]', $text );
4545 * Fetch the user's signature text, if any, and normalize to
4546 * validated, ready-to-insert wikitext.
4547 * If you have pre-fetched the nickname or the fancySig option, you can
4548 * specify them here to save a database query.
4549 * Do not reuse this parser instance after calling getUserSig(),
4550 * as it may have changed if it's the $wgParser.
4552 * @param User &$user
4553 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4554 * @param bool|null $fancySig whether the nicknname is the complete signature
4555 * or null to use default value
4558 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4559 global $wgMaxSigChars;
4561 $username = $user->getName();
4563 # If not given, retrieve from the user object.
4564 if ( $nickname === false ) {
4565 $nickname = $user->getOption( 'nickname' );
4568 if ( is_null( $fancySig ) ) {
4569 $fancySig = $user->getBoolOption( 'fancysig' );
4572 $nickname = $nickname == null ?
$username : $nickname;
4574 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4575 $nickname = $username;
4576 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4577 } elseif ( $fancySig !== false ) {
4578 # Sig. might contain markup; validate this
4579 if ( $this->validateSig( $nickname ) !== false ) {
4580 # Validated; clean up (if needed) and return it
4581 return $this->cleanSig( $nickname, true );
4583 # Failed to validate; fall back to the default
4584 $nickname = $username;
4585 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4589 # Make sure nickname doesnt get a sig in a sig
4590 $nickname = self
::cleanSigInSig( $nickname );
4592 # If we're still here, make it a link to the user page
4593 $userText = wfEscapeWikiText( $username );
4594 $nickText = wfEscapeWikiText( $nickname );
4595 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4597 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4598 ->title( $this->getTitle() )->text();
4602 * Check that the user's signature contains no bad XML
4604 * @param string $text
4605 * @return string|bool An expanded string, or false if invalid.
4607 public function validateSig( $text ) {
4608 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4612 * Clean up signature text
4614 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4615 * 2) Substitute all transclusions
4617 * @param string $text
4618 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4619 * @return string Signature text
4621 public function cleanSig( $text, $parsing = false ) {
4624 $magicScopeVariable = $this->lock();
4625 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4628 # Option to disable this feature
4629 if ( !$this->mOptions
->getCleanSignatures() ) {
4633 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4634 # => Move this logic to braceSubstitution()
4635 $substWord = MagicWord
::get( 'subst' );
4636 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4637 $substText = '{{' . $substWord->getSynonym( 0 );
4639 $text = preg_replace( $substRegex, $substText, $text );
4640 $text = self
::cleanSigInSig( $text );
4641 $dom = $this->preprocessToDom( $text );
4642 $frame = $this->getPreprocessor()->newFrame();
4643 $text = $frame->expand( $dom );
4646 $text = $this->mStripState
->unstripBoth( $text );
4653 * Strip 3, 4 or 5 tildes out of signatures.
4655 * @param string $text
4656 * @return string Signature text with /~{3,5}/ removed
4658 public static function cleanSigInSig( $text ) {
4659 $text = preg_replace( '/~{3,5}/', '', $text );
4664 * Set up some variables which are usually set up in parse()
4665 * so that an external function can call some class members with confidence
4667 * @param Title|null $title
4668 * @param ParserOptions $options
4669 * @param int $outputType
4670 * @param bool $clearState
4672 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4673 $outputType, $clearState = true
4675 $this->startParse( $title, $options, $outputType, $clearState );
4679 * @param Title|null $title
4680 * @param ParserOptions $options
4681 * @param int $outputType
4682 * @param bool $clearState
4684 private function startParse( Title
$title = null, ParserOptions
$options,
4685 $outputType, $clearState = true
4687 $this->setTitle( $title );
4688 $this->mOptions
= $options;
4689 $this->setOutputType( $outputType );
4690 if ( $clearState ) {
4691 $this->clearState();
4696 * Wrapper for preprocess()
4698 * @param string $text The text to preprocess
4699 * @param ParserOptions $options
4700 * @param Title|null $title Title object or null to use $wgTitle
4703 public function transformMsg( $text, $options, $title = null ) {
4704 static $executing = false;
4706 # Guard against infinite recursion
4717 $text = $this->preprocess( $text, $title, $options );
4724 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4725 * The callback should have the following form:
4726 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4728 * Transform and return $text. Use $parser for any required context, e.g. use
4729 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4731 * Hooks may return extended information by returning an array, of which the
4732 * first numbered element (index 0) must be the return string, and all other
4733 * entries are extracted into local variables within an internal function
4734 * in the Parser class.
4736 * This interface (introduced r61913) appears to be undocumented, but
4737 * 'markerType' is used by some core tag hooks to override which strip
4738 * array their results are placed in. **Use great caution if attempting
4739 * this interface, as it is not documented and injudicious use could smash
4740 * private variables.**
4742 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4743 * @param callable $callback The callback function (and object) to use for the tag
4744 * @throws MWException
4745 * @return callable|null The old value of the mTagHooks array associated with the hook
4747 public function setHook( $tag, callable
$callback ) {
4748 $tag = strtolower( $tag );
4749 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4750 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4752 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4753 $this->mTagHooks
[$tag] = $callback;
4754 if ( !in_array( $tag, $this->mStripList
) ) {
4755 $this->mStripList
[] = $tag;
4762 * As setHook(), but letting the contents be parsed.
4764 * Transparent tag hooks are like regular XML-style tag hooks, except they
4765 * operate late in the transformation sequence, on HTML instead of wikitext.
4767 * This is probably obsoleted by things dealing with parser frames?
4768 * The only extension currently using it is geoserver.
4771 * @todo better document or deprecate this
4773 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4774 * @param callable $callback The callback function (and object) to use for the tag
4775 * @throws MWException
4776 * @return callable|null The old value of the mTagHooks array associated with the hook
4778 public function setTransparentTagHook( $tag, callable
$callback ) {
4779 $tag = strtolower( $tag );
4780 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4781 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4783 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4784 $this->mTransparentTagHooks
[$tag] = $callback;
4790 * Remove all tag hooks
4792 public function clearTagHooks() {
4793 $this->mTagHooks
= [];
4794 $this->mFunctionTagHooks
= [];
4795 $this->mStripList
= $this->mDefaultStripList
;
4799 * Create a function, e.g. {{sum:1|2|3}}
4800 * The callback function should have the form:
4801 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4803 * Or with Parser::SFH_OBJECT_ARGS:
4804 * function myParserFunction( $parser, $frame, $args ) { ... }
4806 * The callback may either return the text result of the function, or an array with the text
4807 * in element 0, and a number of flags in the other elements. The names of the flags are
4808 * specified in the keys. Valid flags are:
4809 * found The text returned is valid, stop processing the template. This
4811 * nowiki Wiki markup in the return value should be escaped
4812 * isHTML The returned text is HTML, armour it against wikitext transformation
4814 * @param string $id The magic word ID
4815 * @param callable $callback The callback function (and object) to use
4816 * @param int $flags A combination of the following flags:
4817 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4819 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4820 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4821 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4822 * the arguments, and to control the way they are expanded.
4824 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4825 * arguments, for instance:
4826 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4828 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4829 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4830 * working if/when this is changed.
4832 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4835 * Please read the documentation in includes/parser/Preprocessor.php for more information
4836 * about the methods available in PPFrame and PPNode.
4838 * @throws MWException
4839 * @return string|callable The old callback function for this name, if any
4841 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4844 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4845 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4847 # Add to function cache
4848 $mw = MagicWord
::get( $id );
4850 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4853 $synonyms = $mw->getSynonyms();
4854 $sensitive = intval( $mw->isCaseSensitive() );
4856 foreach ( $synonyms as $syn ) {
4858 if ( !$sensitive ) {
4859 $syn = $wgContLang->lc( $syn );
4862 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4865 # Remove trailing colon
4866 if ( substr( $syn, -1, 1 ) === ':' ) {
4867 $syn = substr( $syn, 0, -1 );
4869 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4875 * Get all registered function hook identifiers
4879 public function getFunctionHooks() {
4880 return array_keys( $this->mFunctionHooks
);
4884 * Create a tag function, e.g. "<test>some stuff</test>".
4885 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4886 * Unlike parser functions, their content is not preprocessed.
4887 * @param string $tag
4888 * @param callable $callback
4890 * @throws MWException
4893 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4894 $tag = strtolower( $tag );
4895 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4896 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4898 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4899 $this->mFunctionTagHooks
[$tag] : null;
4900 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4902 if ( !in_array( $tag, $this->mStripList
) ) {
4903 $this->mStripList
[] = $tag;
4910 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4911 * Placeholders created in Linker::link()
4913 * @param string &$text
4914 * @param int $options
4916 public function replaceLinkHolders( &$text, $options = 0 ) {
4917 $this->mLinkHolders
->replace( $text );
4921 * Replace "<!--LINK-->" link placeholders with plain text of links
4922 * (not HTML-formatted).
4924 * @param string $text
4927 public function replaceLinkHoldersText( $text ) {
4928 return $this->mLinkHolders
->replaceText( $text );
4932 * Renders an image gallery from a text with one line per image.
4933 * text labels may be given by using |-style alternative text. E.g.
4934 * Image:one.jpg|The number "1"
4935 * Image:tree.jpg|A tree
4936 * given as text will return the HTML of a gallery with two images,
4937 * labeled 'The number "1"' and
4940 * @param string $text
4941 * @param array $params
4942 * @return string HTML
4944 public function renderImageGallery( $text, $params ) {
4946 if ( isset( $params['mode'] ) ) {
4947 $mode = $params['mode'];
4951 $ig = ImageGalleryBase
::factory( $mode );
4952 } catch ( Exception
$e ) {
4953 // If invalid type set, fallback to default.
4954 $ig = ImageGalleryBase
::factory( false );
4957 $ig->setContextTitle( $this->mTitle
);
4958 $ig->setShowBytes( false );
4959 $ig->setShowDimensions( false );
4960 $ig->setShowFilename( false );
4961 $ig->setParser( $this );
4962 $ig->setHideBadImages();
4963 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
4965 if ( isset( $params['showfilename'] ) ) {
4966 $ig->setShowFilename( true );
4968 $ig->setShowFilename( false );
4970 if ( isset( $params['caption'] ) ) {
4971 $caption = $params['caption'];
4972 $caption = htmlspecialchars( $caption );
4973 $caption = $this->replaceInternalLinks( $caption );
4974 $ig->setCaptionHtml( $caption );
4976 if ( isset( $params['perrow'] ) ) {
4977 $ig->setPerRow( $params['perrow'] );
4979 if ( isset( $params['widths'] ) ) {
4980 $ig->setWidths( $params['widths'] );
4982 if ( isset( $params['heights'] ) ) {
4983 $ig->setHeights( $params['heights'] );
4985 $ig->setAdditionalOptions( $params );
4987 // Avoid PHP 7.1 warning from passing $this by reference
4989 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
4991 $lines = StringUtils
::explode( "\n", $text );
4992 foreach ( $lines as $line ) {
4993 # match lines like these:
4994 # Image:someimage.jpg|This is some image
4996 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4998 if ( count( $matches ) == 0 ) {
5002 if ( strpos( $matches[0], '%' ) !== false ) {
5003 $matches[1] = rawurldecode( $matches[1] );
5005 $title = Title
::newFromText( $matches[1], NS_FILE
);
5006 if ( is_null( $title ) ) {
5007 # Bogus title. Ignore these so we don't bomb out later.
5011 # We need to get what handler the file uses, to figure out parameters.
5012 # Note, a hook can overide the file name, and chose an entirely different
5013 # file (which potentially could be of a different type and have different handler).
5016 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5017 [ $this, $title, &$options, &$descQuery ] );
5018 # Don't register it now, as TraditionalImageGallery does that later.
5019 $file = $this->fetchFileNoRegister( $title, $options );
5020 $handler = $file ?
$file->getHandler() : false;
5023 'img_alt' => 'gallery-internal-alt',
5024 'img_link' => 'gallery-internal-link',
5027 $paramMap = $paramMap +
$handler->getParamMap();
5028 // We don't want people to specify per-image widths.
5029 // Additionally the width parameter would need special casing anyhow.
5030 unset( $paramMap['img_width'] );
5033 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5038 $handlerOptions = [];
5039 if ( isset( $matches[3] ) ) {
5040 // look for an |alt= definition while trying not to break existing
5041 // captions with multiple pipes (|) in it, until a more sensible grammar
5042 // is defined for images in galleries
5044 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5045 // splitting on '|' is a bit odd, and different from makeImage.
5046 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5047 // Protect LanguageConverter markup
5048 $parameterMatches = StringUtils
::delimiterExplode(
5049 '-{', '}-', '|', $matches[3], true /* nested */
5052 foreach ( $parameterMatches as $parameterMatch ) {
5053 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5055 $paramName = $paramMap[$magicName];
5057 switch ( $paramName ) {
5058 case 'gallery-internal-alt':
5059 $alt = $this->stripAltText( $match, false );
5061 case 'gallery-internal-link':
5062 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5063 $chars = self
::EXT_LINK_URL_CLASS
;
5064 $addr = self
::EXT_LINK_ADDR
;
5065 $prots = $this->mUrlProtocols
;
5066 // check to see if link matches an absolute url, if not then it must be a wiki link.
5067 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5068 // Result of LanguageConverter::markNoConversion
5069 // invoked on an external link.
5070 $linkValue = substr( $linkValue, 4, -2 );
5072 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5074 $this->mOutput
->addExternalLink( $link );
5076 $localLinkTitle = Title
::newFromText( $linkValue );
5077 if ( $localLinkTitle !== null ) {
5078 $this->mOutput
->addLink( $localLinkTitle );
5079 $link = $localLinkTitle->getLinkURL();
5084 // Must be a handler specific parameter.
5085 if ( $handler->validateParam( $paramName, $match ) ) {
5086 $handlerOptions[$paramName] = $match;
5088 // Guess not, consider it as caption.
5089 wfDebug( "$parameterMatch failed parameter validation\n" );
5090 $label = '|' . $parameterMatch;
5096 $label = '|' . $parameterMatch;
5100 $label = substr( $label, 1 );
5103 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5105 $html = $ig->toHTML();
5106 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5111 * @param MediaHandler $handler
5114 public function getImageParams( $handler ) {
5116 $handlerClass = get_class( $handler );
5120 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5121 # Initialise static lists
5122 static $internalParamNames = [
5123 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5124 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5125 'bottom', 'text-bottom' ],
5126 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5127 'upright', 'border', 'link', 'alt', 'class' ],
5129 static $internalParamMap;
5130 if ( !$internalParamMap ) {
5131 $internalParamMap = [];
5132 foreach ( $internalParamNames as $type => $names ) {
5133 foreach ( $names as $name ) {
5134 // For grep: img_left, img_right, img_center, img_none,
5135 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5136 // img_bottom, img_text_bottom,
5137 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5138 // img_border, img_link, img_alt, img_class
5139 $magicName = str_replace( '-', '_', "img_$name" );
5140 $internalParamMap[$magicName] = [ $type, $name ];
5145 # Add handler params
5146 $paramMap = $internalParamMap;
5148 $handlerParamMap = $handler->getParamMap();
5149 foreach ( $handlerParamMap as $magic => $paramName ) {
5150 $paramMap[$magic] = [ 'handler', $paramName ];
5153 $this->mImageParams
[$handlerClass] = $paramMap;
5154 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5156 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5160 * Parse image options text and use it to make an image
5162 * @param Title $title
5163 * @param string $options
5164 * @param LinkHolderArray|bool $holders
5165 * @return string HTML
5167 public function makeImage( $title, $options, $holders = false ) {
5168 # Check if the options text is of the form "options|alt text"
5170 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5171 # * left no resizing, just left align. label is used for alt= only
5172 # * right same, but right aligned
5173 # * none same, but not aligned
5174 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5175 # * center center the image
5176 # * frame Keep original image size, no magnify-button.
5177 # * framed Same as "frame"
5178 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5179 # * upright reduce width for upright images, rounded to full __0 px
5180 # * border draw a 1px border around the image
5181 # * alt Text for HTML alt attribute (defaults to empty)
5182 # * class Set a class for img node
5183 # * link Set the target of the image link. Can be external, interwiki, or local
5184 # vertical-align values (no % or length right now):
5194 # Protect LanguageConverter markup when splitting into parts
5195 $parts = StringUtils
::delimiterExplode(
5196 '-{', '}-', '|', $options, true /* allow nesting */
5199 # Give extensions a chance to select the file revision for us
5202 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5203 [ $this, $title, &$options, &$descQuery ] );
5204 # Fetch and register the file (file title may be different via hooks)
5205 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5208 $handler = $file ?
$file->getHandler() : false;
5210 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5213 $this->addTrackingCategory( 'broken-file-category' );
5216 # Process the input parameters
5218 $params = [ 'frame' => [], 'handler' => [],
5219 'horizAlign' => [], 'vertAlign' => [] ];
5220 $seenformat = false;
5221 foreach ( $parts as $part ) {
5222 $part = trim( $part );
5223 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5225 if ( isset( $paramMap[$magicName] ) ) {
5226 list( $type, $paramName ) = $paramMap[$magicName];
5228 # Special case; width and height come in one variable together
5229 if ( $type === 'handler' && $paramName === 'width' ) {
5230 $parsedWidthParam = self
::parseWidthParam( $value );
5231 if ( isset( $parsedWidthParam['width'] ) ) {
5232 $width = $parsedWidthParam['width'];
5233 if ( $handler->validateParam( 'width', $width ) ) {
5234 $params[$type]['width'] = $width;
5238 if ( isset( $parsedWidthParam['height'] ) ) {
5239 $height = $parsedWidthParam['height'];
5240 if ( $handler->validateParam( 'height', $height ) ) {
5241 $params[$type]['height'] = $height;
5245 # else no validation -- T15436
5247 if ( $type === 'handler' ) {
5248 # Validate handler parameter
5249 $validated = $handler->validateParam( $paramName, $value );
5251 # Validate internal parameters
5252 switch ( $paramName ) {
5256 # @todo FIXME: Possibly check validity here for
5257 # manualthumb? downstream behavior seems odd with
5258 # missing manual thumbs.
5260 $value = $this->stripAltText( $value, $holders );
5263 $chars = self
::EXT_LINK_URL_CLASS
;
5264 $addr = self
::EXT_LINK_ADDR
;
5265 $prots = $this->mUrlProtocols
;
5266 if ( $value === '' ) {
5267 $paramName = 'no-link';
5270 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5271 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5272 $paramName = 'link-url';
5273 $this->mOutput
->addExternalLink( $value );
5274 if ( $this->mOptions
->getExternalLinkTarget() ) {
5275 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5280 $linkTitle = Title
::newFromText( $value );
5282 $paramName = 'link-title';
5283 $value = $linkTitle;
5284 $this->mOutput
->addLink( $linkTitle );
5292 // use first appearing option, discard others.
5293 $validated = !$seenformat;
5297 # Most other things appear to be empty or numeric...
5298 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5303 $params[$type][$paramName] = $value;
5307 if ( !$validated ) {
5312 # Process alignment parameters
5313 if ( $params['horizAlign'] ) {
5314 $params['frame']['align'] = key( $params['horizAlign'] );
5316 if ( $params['vertAlign'] ) {
5317 $params['frame']['valign'] = key( $params['vertAlign'] );
5320 $params['frame']['caption'] = $caption;
5322 # Will the image be presented in a frame, with the caption below?
5323 $imageIsFramed = isset( $params['frame']['frame'] )
5324 ||
isset( $params['frame']['framed'] )
5325 ||
isset( $params['frame']['thumbnail'] )
5326 ||
isset( $params['frame']['manualthumb'] );
5328 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5329 # came to also set the caption, ordinary text after the image -- which
5330 # makes no sense, because that just repeats the text multiple times in
5331 # screen readers. It *also* came to set the title attribute.
5332 # Now that we have an alt attribute, we should not set the alt text to
5333 # equal the caption: that's worse than useless, it just repeats the
5334 # text. This is the framed/thumbnail case. If there's no caption, we
5335 # use the unnamed parameter for alt text as well, just for the time be-
5336 # ing, if the unnamed param is set and the alt param is not.
5337 # For the future, we need to figure out if we want to tweak this more,
5338 # e.g., introducing a title= parameter for the title; ignoring the un-
5339 # named parameter entirely for images without a caption; adding an ex-
5340 # plicit caption= parameter and preserving the old magic unnamed para-
5342 if ( $imageIsFramed ) { # Framed image
5343 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5344 # No caption or alt text, add the filename as the alt text so
5345 # that screen readers at least get some description of the image
5346 $params['frame']['alt'] = $title->getText();
5348 # Do not set $params['frame']['title'] because tooltips don't make sense
5350 } else { # Inline image
5351 if ( !isset( $params['frame']['alt'] ) ) {
5352 # No alt text, use the "caption" for the alt text
5353 if ( $caption !== '' ) {
5354 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5356 # No caption, fall back to using the filename for the
5358 $params['frame']['alt'] = $title->getText();
5361 # Use the "caption" for the tooltip text
5362 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5365 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5367 # Linker does the rest
5368 $time = isset( $options['time'] ) ?
$options['time'] : false;
5369 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5370 $time, $descQuery, $this->mOptions
->getThumbSize() );
5372 # Give the handler a chance to modify the parser object
5374 $handler->parserTransformHook( $this, $file );
5381 * @param string $caption
5382 * @param LinkHolderArray|bool $holders
5383 * @return mixed|string
5385 protected function stripAltText( $caption, $holders ) {
5386 # Strip bad stuff out of the title (tooltip). We can't just use
5387 # replaceLinkHoldersText() here, because if this function is called
5388 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5390 $tooltip = $holders->replaceText( $caption );
5392 $tooltip = $this->replaceLinkHoldersText( $caption );
5395 # make sure there are no placeholders in thumbnail attributes
5396 # that are later expanded to html- so expand them now and
5398 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5399 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5405 * Set a flag in the output object indicating that the content is dynamic and
5406 * shouldn't be cached.
5407 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5409 public function disableCache() {
5410 wfDebug( "Parser output marked as uncacheable.\n" );
5411 if ( !$this->mOutput
) {
5412 throw new MWException( __METHOD__
.
5413 " can only be called when actually parsing something" );
5415 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5419 * Callback from the Sanitizer for expanding items found in HTML attribute
5420 * values, so they can be safely tested and escaped.
5422 * @param string &$text
5423 * @param bool|PPFrame $frame
5426 public function attributeStripCallback( &$text, $frame = false ) {
5427 $text = $this->replaceVariables( $text, $frame );
5428 $text = $this->mStripState
->unstripBoth( $text );
5437 public function getTags() {
5439 array_keys( $this->mTransparentTagHooks
),
5440 array_keys( $this->mTagHooks
),
5441 array_keys( $this->mFunctionTagHooks
)
5446 * Replace transparent tags in $text with the values given by the callbacks.
5448 * Transparent tag hooks are like regular XML-style tag hooks, except they
5449 * operate late in the transformation sequence, on HTML instead of wikitext.
5451 * @param string $text
5455 public function replaceTransparentTags( $text ) {
5457 $elements = array_keys( $this->mTransparentTagHooks
);
5458 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5461 foreach ( $matches as $marker => $data ) {
5462 list( $element, $content, $params, $tag ) = $data;
5463 $tagName = strtolower( $element );
5464 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5465 $output = call_user_func_array(
5466 $this->mTransparentTagHooks
[$tagName],
5467 [ $content, $params, $this ]
5472 $replacements[$marker] = $output;
5474 return strtr( $text, $replacements );
5478 * Break wikitext input into sections, and either pull or replace
5479 * some particular section's text.
5481 * External callers should use the getSection and replaceSection methods.
5483 * @param string $text Page wikitext
5484 * @param string|int $sectionId A section identifier string of the form:
5485 * "<flag1> - <flag2> - ... - <section number>"
5487 * Currently the only recognised flag is "T", which means the target section number
5488 * was derived during a template inclusion parse, in other words this is a template
5489 * section edit link. If no flags are given, it was an ordinary section edit link.
5490 * This flag is required to avoid a section numbering mismatch when a section is
5491 * enclosed by "<includeonly>" (T8563).
5493 * The section number 0 pulls the text before the first heading; other numbers will
5494 * pull the given section along with its lower-level subsections. If the section is
5495 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5497 * Section 0 is always considered to exist, even if it only contains the empty
5498 * string. If $text is the empty string and section 0 is replaced, $newText is
5501 * @param string $mode One of "get" or "replace"
5502 * @param string $newText Replacement text for section data.
5503 * @return string For "get", the extracted section text.
5504 * for "replace", the whole page with the section replaced.
5506 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5507 global $wgTitle; # not generally used but removes an ugly failure mode
5509 $magicScopeVariable = $this->lock();
5510 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5512 $frame = $this->getPreprocessor()->newFrame();
5514 # Process section extraction flags
5516 $sectionParts = explode( '-', $sectionId );
5517 $sectionIndex = array_pop( $sectionParts );
5518 foreach ( $sectionParts as $part ) {
5519 if ( $part === 'T' ) {
5520 $flags |
= self
::PTD_FOR_INCLUSION
;
5524 # Check for empty input
5525 if ( strval( $text ) === '' ) {
5526 # Only sections 0 and T-0 exist in an empty document
5527 if ( $sectionIndex == 0 ) {
5528 if ( $mode === 'get' ) {
5534 if ( $mode === 'get' ) {
5542 # Preprocess the text
5543 $root = $this->preprocessToDom( $text, $flags );
5545 # <h> nodes indicate section breaks
5546 # They can only occur at the top level, so we can find them by iterating the root's children
5547 $node = $root->getFirstChild();
5549 # Find the target section
5550 if ( $sectionIndex == 0 ) {
5551 # Section zero doesn't nest, level=big
5552 $targetLevel = 1000;
5555 if ( $node->getName() === 'h' ) {
5556 $bits = $node->splitHeading();
5557 if ( $bits['i'] == $sectionIndex ) {
5558 $targetLevel = $bits['level'];
5562 if ( $mode === 'replace' ) {
5563 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5565 $node = $node->getNextSibling();
5571 if ( $mode === 'get' ) {
5578 # Find the end of the section, including nested sections
5580 if ( $node->getName() === 'h' ) {
5581 $bits = $node->splitHeading();
5582 $curLevel = $bits['level'];
5583 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5587 if ( $mode === 'get' ) {
5588 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5590 $node = $node->getNextSibling();
5593 # Write out the remainder (in replace mode only)
5594 if ( $mode === 'replace' ) {
5595 # Output the replacement text
5596 # Add two newlines on -- trailing whitespace in $newText is conventionally
5597 # stripped by the editor, so we need both newlines to restore the paragraph gap
5598 # Only add trailing whitespace if there is newText
5599 if ( $newText != "" ) {
5600 $outText .= $newText . "\n\n";
5604 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5605 $node = $node->getNextSibling();
5609 if ( is_string( $outText ) ) {
5610 # Re-insert stripped tags
5611 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5618 * This function returns the text of a section, specified by a number ($section).
5619 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5620 * the first section before any such heading (section 0).
5622 * If a section contains subsections, these are also returned.
5624 * @param string $text Text to look in
5625 * @param string|int $sectionId Section identifier as a number or string
5626 * (e.g. 0, 1 or 'T-1').
5627 * @param string $defaultText Default to return if section is not found
5629 * @return string Text of the requested section
5631 public function getSection( $text, $sectionId, $defaultText = '' ) {
5632 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5636 * This function returns $oldtext after the content of the section
5637 * specified by $section has been replaced with $text. If the target
5638 * section does not exist, $oldtext is returned unchanged.
5640 * @param string $oldText Former text of the article
5641 * @param string|int $sectionId Section identifier as a number or string
5642 * (e.g. 0, 1 or 'T-1').
5643 * @param string $newText Replacing text
5645 * @return string Modified text
5647 public function replaceSection( $oldText, $sectionId, $newText ) {
5648 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5652 * Get the ID of the revision we are parsing
5656 public function getRevisionId() {
5657 return $this->mRevisionId
;
5661 * Get the revision object for $this->mRevisionId
5663 * @return Revision|null Either a Revision object or null
5664 * @since 1.23 (public since 1.23)
5666 public function getRevisionObject() {
5667 if ( !is_null( $this->mRevisionObject
) ) {
5668 return $this->mRevisionObject
;
5670 if ( is_null( $this->mRevisionId
) ) {
5674 $rev = call_user_func(
5675 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5678 # If the parse is for a new revision, then the callback should have
5679 # already been set to force the object and should match mRevisionId.
5680 # If not, try to fetch by mRevisionId for sanity.
5681 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5682 $rev = Revision
::newFromId( $this->mRevisionId
);
5685 $this->mRevisionObject
= $rev;
5687 return $this->mRevisionObject
;
5691 * Get the timestamp associated with the current revision, adjusted for
5692 * the default server-local timestamp
5695 public function getRevisionTimestamp() {
5696 if ( is_null( $this->mRevisionTimestamp
) ) {
5699 $revObject = $this->getRevisionObject();
5700 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5702 # The cryptic '' timezone parameter tells to use the site-default
5703 # timezone offset instead of the user settings.
5704 # Since this value will be saved into the parser cache, served
5705 # to other users, and potentially even used inside links and such,
5706 # it needs to be consistent for all visitors.
5707 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5710 return $this->mRevisionTimestamp
;
5714 * Get the name of the user that edited the last revision
5716 * @return string User name
5718 public function getRevisionUser() {
5719 if ( is_null( $this->mRevisionUser
) ) {
5720 $revObject = $this->getRevisionObject();
5722 # if this template is subst: the revision id will be blank,
5723 # so just use the current user's name
5725 $this->mRevisionUser
= $revObject->getUserText();
5726 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5727 $this->mRevisionUser
= $this->getUser()->getName();
5730 return $this->mRevisionUser
;
5734 * Get the size of the revision
5736 * @return int|null Revision size
5738 public function getRevisionSize() {
5739 if ( is_null( $this->mRevisionSize
) ) {
5740 $revObject = $this->getRevisionObject();
5742 # if this variable is subst: the revision id will be blank,
5743 # so just use the parser input size, because the own substituation
5744 # will change the size.
5746 $this->mRevisionSize
= $revObject->getSize();
5748 $this->mRevisionSize
= $this->mInputSize
;
5751 return $this->mRevisionSize
;
5755 * Mutator for $mDefaultSort
5757 * @param string $sort New value
5759 public function setDefaultSort( $sort ) {
5760 $this->mDefaultSort
= $sort;
5761 $this->mOutput
->setProperty( 'defaultsort', $sort );
5765 * Accessor for $mDefaultSort
5766 * Will use the empty string if none is set.
5768 * This value is treated as a prefix, so the
5769 * empty string is equivalent to sorting by
5774 public function getDefaultSort() {
5775 if ( $this->mDefaultSort
!== false ) {
5776 return $this->mDefaultSort
;
5783 * Accessor for $mDefaultSort
5784 * Unlike getDefaultSort(), will return false if none is set
5786 * @return string|bool
5788 public function getCustomDefaultSort() {
5789 return $this->mDefaultSort
;
5792 private static function getSectionNameFromStrippedText( $text ) {
5793 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5794 $text = Sanitizer
::decodeCharReferences( $text );
5795 $text = self
::normalizeSectionName( $text );
5799 private static function makeAnchor( $sectionName ) {
5800 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5803 private static function makeLegacyAnchor( $sectionName ) {
5804 global $wgFragmentMode;
5805 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5806 // ForAttribute() and ForLink() are the same for legacy encoding
5807 $id = Sanitizer
::escapeIdForAttribute( $sectionName, Sanitizer
::ID_FALLBACK
);
5809 $id = Sanitizer
::escapeIdForLink( $sectionName );
5816 * Try to guess the section anchor name based on a wikitext fragment
5817 * presumably extracted from a heading, for example "Header" from
5820 * @param string $text
5821 * @return string Anchor (starting with '#')
5823 public function guessSectionNameFromWikiText( $text ) {
5824 # Strip out wikitext links(they break the anchor)
5825 $text = $this->stripSectionName( $text );
5826 $sectionName = self
::getSectionNameFromStrippedText( $text );
5827 return self
::makeAnchor( $sectionName );
5831 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5832 * instead, if possible. For use in redirects, since various versions
5833 * of Microsoft browsers interpret Location: headers as something other
5834 * than UTF-8, resulting in breakage.
5836 * @param string $text The section name
5837 * @return string Anchor (starting with '#')
5839 public function guessLegacySectionNameFromWikiText( $text ) {
5840 # Strip out wikitext links(they break the anchor)
5841 $text = $this->stripSectionName( $text );
5842 $sectionName = self
::getSectionNameFromStrippedText( $text );
5843 return self
::makeLegacyAnchor( $sectionName );
5847 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5848 * @param string $text Section name (plain text)
5849 * @return string Anchor (starting with '#')
5851 public static function guessSectionNameFromStrippedText( $text ) {
5852 $sectionName = self
::getSectionNameFromStrippedText( $text );
5853 return self
::makeAnchor( $sectionName );
5857 * Apply the same normalization as code making links to this section would
5859 * @param string $text
5862 private static function normalizeSectionName( $text ) {
5863 # T90902: ensure the same normalization is applied for IDs as to links
5864 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5867 $parts = $titleParser->splitTitleString( "#$text" );
5868 } catch ( MalformedTitleException
$ex ) {
5871 return $parts['fragment'];
5875 * Strips a text string of wikitext for use in a section anchor
5877 * Accepts a text string and then removes all wikitext from the
5878 * string and leaves only the resultant text (i.e. the result of
5879 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5880 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5881 * to create valid section anchors by mimicing the output of the
5882 * parser when headings are parsed.
5884 * @param string $text Text string to be stripped of wikitext
5885 * for use in a Section anchor
5886 * @return string Filtered text string
5888 public function stripSectionName( $text ) {
5889 # Strip internal link markup
5890 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5891 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5893 # Strip external link markup
5894 # @todo FIXME: Not tolerant to blank link text
5895 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5896 # on how many empty links there are on the page - need to figure that out.
5897 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5899 # Parse wikitext quotes (italics & bold)
5900 $text = $this->doQuotes( $text );
5903 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5908 * strip/replaceVariables/unstrip for preprocessor regression testing
5910 * @param string $text
5911 * @param Title $title
5912 * @param ParserOptions $options
5913 * @param int $outputType
5917 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5918 $outputType = self
::OT_HTML
5920 $magicScopeVariable = $this->lock();
5921 $this->startParse( $title, $options, $outputType, true );
5923 $text = $this->replaceVariables( $text );
5924 $text = $this->mStripState
->unstripBoth( $text );
5925 $text = Sanitizer
::removeHTMLtags( $text );
5930 * @param string $text
5931 * @param Title $title
5932 * @param ParserOptions $options
5935 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5936 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5940 * @param string $text
5941 * @param Title $title
5942 * @param ParserOptions $options
5945 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5946 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5950 * Call a callback function on all regions of the given text that are not
5951 * inside strip markers, and replace those regions with the return value
5952 * of the callback. For example, with input:
5956 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5957 * two strings will be replaced with the value returned by the callback in
5961 * @param callable $callback
5965 public function markerSkipCallback( $s, $callback ) {
5968 while ( $i < strlen( $s ) ) {
5969 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
5970 if ( $markerStart === false ) {
5971 $out .= call_user_func( $callback, substr( $s, $i ) );
5974 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5975 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5976 if ( $markerEnd === false ) {
5977 $out .= substr( $s, $markerStart );
5980 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5981 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5990 * Remove any strip markers found in the given text.
5992 * @param string $text
5995 public function killMarkers( $text ) {
5996 return $this->mStripState
->killMarkers( $text );
6000 * Save the parser state required to convert the given half-parsed text to
6001 * HTML. "Half-parsed" in this context means the output of
6002 * recursiveTagParse() or internalParse(). This output has strip markers
6003 * from replaceVariables (extensionSubstitution() etc.), and link
6004 * placeholders from replaceLinkHolders().
6006 * Returns an array which can be serialized and stored persistently. This
6007 * array can later be loaded into another parser instance with
6008 * unserializeHalfParsedText(). The text can then be safely incorporated into
6009 * the return value of a parser hook.
6011 * @deprecated since 1.31
6012 * @param string $text
6016 public function serializeHalfParsedText( $text ) {
6017 wfDeprecated( __METHOD__
, '1.31' );
6020 'version' => self
::HALF_PARSED_VERSION
,
6021 'stripState' => $this->mStripState
->getSubState( $text ),
6022 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6028 * Load the parser state given in the $data array, which is assumed to
6029 * have been generated by serializeHalfParsedText(). The text contents is
6030 * extracted from the array, and its markers are transformed into markers
6031 * appropriate for the current Parser instance. This transformed text is
6032 * returned, and can be safely included in the return value of a parser
6035 * If the $data array has been stored persistently, the caller should first
6036 * check whether it is still valid, by calling isValidHalfParsedText().
6038 * @deprecated since 1.31
6039 * @param array $data Serialized data
6040 * @throws MWException
6043 public function unserializeHalfParsedText( $data ) {
6044 wfDeprecated( __METHOD__
, '1.31' );
6045 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6046 throw new MWException( __METHOD__
. ': invalid version' );
6049 # First, extract the strip state.
6050 $texts = [ $data['text'] ];
6051 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6053 # Now renumber links
6054 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6056 # Should be good to go.
6061 * Returns true if the given array, presumed to be generated by
6062 * serializeHalfParsedText(), is compatible with the current version of the
6065 * @deprecated since 1.31
6066 * @param array $data
6070 public function isValidHalfParsedText( $data ) {
6071 wfDeprecated( __METHOD__
, '1.31' );
6072 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6076 * Parsed a width param of imagelink like 300px or 200x300px
6078 * @param string $value
6079 * @param bool $parseHeight
6084 public static function parseWidthParam( $value, $parseHeight = true ) {
6085 $parsedWidthParam = [];
6086 if ( $value === '' ) {
6087 return $parsedWidthParam;
6090 # (T15500) In both cases (width/height and width only),
6091 # permit trailing "px" for backward compatibility.
6092 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6093 $width = intval( $m[1] );
6094 $height = intval( $m[2] );
6095 $parsedWidthParam['width'] = $width;
6096 $parsedWidthParam['height'] = $height;
6097 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6098 $width = intval( $value );
6099 $parsedWidthParam['width'] = $width;
6101 return $parsedWidthParam;
6105 * Lock the current instance of the parser.
6107 * This is meant to stop someone from calling the parser
6108 * recursively and messing up all the strip state.
6110 * @throws MWException If parser is in a parse
6111 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6113 protected function lock() {
6114 if ( $this->mInParse
) {
6115 throw new MWException( "Parser state cleared while parsing. "
6116 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6119 // Save the backtrace when locking, so that if some code tries locking again,
6120 // we can print the lock owner's backtrace for easier debugging
6122 $this->mInParse
= $e->getTraceAsString();
6124 $recursiveCheck = new ScopedCallback( function () {
6125 $this->mInParse
= false;
6128 return $recursiveCheck;
6132 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6134 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6135 * or if there is more than one <p/> tag in the input HTML.
6137 * @param string $html
6141 public static function stripOuterParagraph( $html ) {
6143 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6144 if ( strpos( $m[1], '</p>' ) === false ) {
6153 * Return this parser if it is not doing anything, otherwise
6154 * get a fresh parser. You can use this method by doing
6155 * $myParser = $wgParser->getFreshParser(), or more simply
6156 * $wgParser->getFreshParser()->parse( ... );
6157 * if you're unsure if $wgParser is safe to use.
6160 * @return Parser A parser object that is not parsing anything
6162 public function getFreshParser() {
6163 global $wgParserConf;
6164 if ( $this->mInParse
) {
6165 return new $wgParserConf['class']( $wgParserConf );
6172 * Set's up the PHP implementation of OOUI for use in this request
6173 * and instructs OutputPage to enable OOUI for itself.
6177 public function enableOOUI() {
6178 OutputPage
::setupOOUI();
6179 $this->mOutput
->setEnableOOUI( true );