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';
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';
278 } elseif ( extension_loaded( 'dom' ) ) {
279 $this->mPreprocessorClass
= 'Preprocessor_DOM';
281 $this->mPreprocessorClass
= 'Preprocessor_Hash';
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
;
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() ]
546 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
548 $limitReport = "NewPP limit report\n";
549 if ( $wgShowHostnames ) {
550 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
552 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
553 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
554 $limitReport .= 'Dynamic content: ' .
555 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
558 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
559 if ( Hooks
::run( 'ParserLimitReportFormat',
560 [ $key, &$value, &$limitReport, false, false ]
562 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
563 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
564 ->inLanguage( 'en' )->useDatabase( false );
565 if ( !$valueMsg->exists() ) {
566 $valueMsg = new RawMessage( '$1' );
568 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
569 $valueMsg->params( $value );
570 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
574 // Since we're not really outputting HTML, decode the entities and
575 // then re-encode the things that need hiding inside HTML comments.
576 $limitReport = htmlspecialchars_decode( $limitReport );
577 // Run deprecated hook
578 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
580 // Sanitize for comment. Note '‐' in the replacement is U+2010,
581 // which looks much like the problematic '-'.
582 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
583 $text = "\n<!-- \n$limitReport-->\n";
585 // Add on template profiling data in human/machine readable way
586 $dataByFunc = $this->mProfiler
->getFunctionStats();
587 uasort( $dataByFunc, function ( $a, $b ) {
588 return $a['real'] < $b['real']; // descending order
591 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
592 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
593 $item['%real'], $item['real'], $item['calls'],
594 htmlspecialchars( $item['name'] ) );
596 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
597 $text .= implode( "\n", $profileReport ) . "\n-->\n";
599 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
601 // Add other cache related metadata
602 if ( $wgShowHostnames ) {
603 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
605 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
606 $this->mOutput
->getCacheTime() );
607 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
608 $this->mOutput
->getCacheExpiry() );
609 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
610 $this->mOutput
->hasDynamicContent() );
612 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
613 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
614 $this->mTitle
->getPrefixedDBkey() );
620 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
621 * can be called from an extension tag hook.
623 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
624 * instead, which means that lists and links have not been fully parsed yet,
625 * and strip markers are still present.
627 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
629 * Use this function if you're a parser tag hook and you want to parse
630 * wikitext before or after applying additional transformations, and you
631 * intend to *return the result as hook output*, which will cause it to go
632 * through the rest of parsing process automatically.
634 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
635 * $text are not expanded
637 * @param string $text Text extension wants to have parsed
638 * @param bool|PPFrame $frame The frame to use for expanding any template variables
639 * @return string UNSAFE half-parsed HTML
641 public function recursiveTagParse( $text, $frame = false ) {
642 // Avoid PHP 7.1 warning from passing $this by reference
644 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
645 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
646 $text = $this->internalParse( $text, false, $frame );
651 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
652 * point can be called from an extension tag hook.
654 * The output of this function is fully-parsed HTML that is safe for output.
655 * If you're a parser tag hook, you might want to use recursiveTagParse()
658 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
659 * $text are not expanded
663 * @param string $text Text extension wants to have parsed
664 * @param bool|PPFrame $frame The frame to use for expanding any template variables
665 * @return string Fully parsed HTML
667 public function recursiveTagParseFully( $text, $frame = false ) {
668 $text = $this->recursiveTagParse( $text, $frame );
669 $text = $this->internalParseHalfParsed( $text, false );
674 * Expand templates and variables in the text, producing valid, static wikitext.
675 * Also removes comments.
676 * Do not call this function recursively.
677 * @param string $text
678 * @param Title $title
679 * @param ParserOptions $options
680 * @param int|null $revid
681 * @param bool|PPFrame $frame
682 * @return mixed|string
684 public function preprocess( $text, Title
$title = null,
685 ParserOptions
$options, $revid = null, $frame = false
687 $magicScopeVariable = $this->lock();
688 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
689 if ( $revid !== null ) {
690 $this->mRevisionId
= $revid;
692 // Avoid PHP 7.1 warning from passing $this by reference
694 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
695 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
696 $text = $this->replaceVariables( $text, $frame );
697 $text = $this->mStripState
->unstripBoth( $text );
702 * Recursive parser entry point that can be called from an extension tag
705 * @param string $text Text to be expanded
706 * @param bool|PPFrame $frame The frame to use for expanding any template variables
710 public function recursivePreprocess( $text, $frame = false ) {
711 $text = $this->replaceVariables( $text, $frame );
712 $text = $this->mStripState
->unstripBoth( $text );
717 * Process the wikitext for the "?preload=" feature. (T7210)
719 * "<noinclude>", "<includeonly>" etc. are parsed as for template
720 * transclusion, comments, templates, arguments, tags hooks and parser
721 * functions are untouched.
723 * @param string $text
724 * @param Title $title
725 * @param ParserOptions $options
726 * @param array $params
729 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
730 $msg = new RawMessage( $text );
731 $text = $msg->params( $params )->plain();
733 # Parser (re)initialisation
734 $magicScopeVariable = $this->lock();
735 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
737 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
738 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
739 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
740 $text = $this->mStripState
->unstripBoth( $text );
745 * Set the current user.
746 * Should only be used when doing pre-save transform.
748 * @param User|null $user User object or null (to reset)
750 public function setUser( $user ) {
751 $this->mUser
= $user;
755 * Set the context title
759 public function setTitle( $t ) {
761 $t = Title
::newFromText( 'NO TITLE' );
764 if ( $t->hasFragment() ) {
765 # Strip the fragment to avoid various odd effects
766 $this->mTitle
= $t->createFragmentTarget( '' );
773 * Accessor for the Title object
777 public function getTitle() {
778 return $this->mTitle
;
782 * Accessor/mutator for the Title object
784 * @param Title $x Title object or null to just get the current one
787 public function Title( $x = null ) {
788 return wfSetVar( $this->mTitle
, $x );
792 * Set the output type
794 * @param int $ot New value
796 public function setOutputType( $ot ) {
797 $this->mOutputType
= $ot;
800 'html' => $ot == self
::OT_HTML
,
801 'wiki' => $ot == self
::OT_WIKI
,
802 'pre' => $ot == self
::OT_PREPROCESS
,
803 'plain' => $ot == self
::OT_PLAIN
,
808 * Accessor/mutator for the output type
810 * @param int|null $x New value or null to just get the current one
813 public function OutputType( $x = null ) {
814 return wfSetVar( $this->mOutputType
, $x );
818 * Get the ParserOutput object
820 * @return ParserOutput
822 public function getOutput() {
823 return $this->mOutput
;
827 * Get the ParserOptions object
829 * @return ParserOptions
831 public function getOptions() {
832 return $this->mOptions
;
836 * Accessor/mutator for the ParserOptions object
838 * @param ParserOptions $x New value or null to just get the current one
839 * @return ParserOptions Current ParserOptions object
841 public function Options( $x = null ) {
842 return wfSetVar( $this->mOptions
, $x );
848 public function nextLinkID() {
849 return $this->mLinkID++
;
855 public function setLinkID( $id ) {
856 $this->mLinkID
= $id;
860 * Get a language object for use in parser functions such as {{FORMATNUM:}}
863 public function getFunctionLang() {
864 return $this->getTargetLanguage();
868 * Get the target language for the content being parsed. This is usually the
869 * language that the content is in.
873 * @throws MWException
876 public function getTargetLanguage() {
877 $target = $this->mOptions
->getTargetLanguage();
879 if ( $target !== null ) {
881 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
882 return $this->mOptions
->getUserLangObj();
883 } elseif ( is_null( $this->mTitle
) ) {
884 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
887 return $this->mTitle
->getPageLanguage();
891 * Get the language object for language conversion
892 * @return Language|null
894 public function getConverterLanguage() {
895 return $this->getTargetLanguage();
899 * Get a User object either from $this->mUser, if set, or from the
900 * ParserOptions object otherwise
904 public function getUser() {
905 if ( !is_null( $this->mUser
) ) {
908 return $this->mOptions
->getUser();
912 * Get a preprocessor object
914 * @return Preprocessor
916 public function getPreprocessor() {
917 if ( !isset( $this->mPreprocessor
) ) {
918 $class = $this->mPreprocessorClass
;
919 $this->mPreprocessor
= new $class( $this );
921 return $this->mPreprocessor
;
925 * Get a LinkRenderer instance to make links with
928 * @return LinkRenderer
930 public function getLinkRenderer() {
931 if ( !$this->mLinkRenderer
) {
932 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
933 ->getLinkRendererFactory()->create();
934 $this->mLinkRenderer
->setStubThreshold(
935 $this->getOptions()->getStubThreshold()
939 return $this->mLinkRenderer
;
943 * Replaces all occurrences of HTML-style comments and the given tags
944 * in the text with a random marker and returns the next text. The output
945 * parameter $matches will be an associative array filled with data in
952 * [ 'param' => 'x' ],
953 * '<element param="x">tag content</element>' ]
956 * @param array $elements List of element names. Comments are always extracted.
957 * @param string $text Source text string.
958 * @param array &$matches Out parameter, Array: extracted tags
959 * @return string Stripped text
961 public static function extractTagsAndParams( $elements, $text, &$matches ) {
966 $taglist = implode( '|', $elements );
967 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
969 while ( $text != '' ) {
970 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
972 if ( count( $p ) < 5 ) {
975 if ( count( $p ) > 5 ) {
989 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
990 $stripped .= $marker;
992 if ( $close === '/>' ) {
993 # Empty element tag, <tag />
998 if ( $element === '!--' ) {
1001 $end = "/(<\\/$element\\s*>)/i";
1003 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1005 if ( count( $q ) < 3 ) {
1006 # No end tag -- let it run out to the end of the text.
1015 $matches[$marker] = [ $element,
1017 Sanitizer
::decodeTagAttributes( $attributes ),
1018 "<$element$attributes$close$content$tail" ];
1024 * Get a list of strippable XML-like elements
1028 public function getStripList() {
1029 return $this->mStripList
;
1033 * Add an item to the strip state
1034 * Returns the unique tag which must be inserted into the stripped text
1035 * The tag will be replaced with the original text in unstrip()
1037 * @param string $text
1041 public function insertStripItem( $text ) {
1042 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1043 $this->mMarkerIndex++
;
1044 $this->mStripState
->addGeneral( $marker, $text );
1049 * parse the wiki syntax used to render tables
1052 * @param string $text
1055 public function doTableStuff( $text ) {
1056 $lines = StringUtils
::explode( "\n", $text );
1058 $td_history = []; # Is currently a td tag open?
1059 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1060 $tr_history = []; # Is currently a tr tag open?
1061 $tr_attributes = []; # history of tr attributes
1062 $has_opened_tr = []; # Did this table open a <tr> element?
1063 $indent_level = 0; # indent level of the table
1065 foreach ( $lines as $outLine ) {
1066 $line = trim( $outLine );
1068 if ( $line === '' ) { # empty line, go to next line
1069 $out .= $outLine . "\n";
1073 $first_character = $line[0];
1074 $first_two = substr( $line, 0, 2 );
1077 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1078 # First check if we are starting a new table
1079 $indent_level = strlen( $matches[1] );
1081 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1082 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1084 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1085 array_push( $td_history, false );
1086 array_push( $last_tag_history, '' );
1087 array_push( $tr_history, false );
1088 array_push( $tr_attributes, '' );
1089 array_push( $has_opened_tr, false );
1090 } elseif ( count( $td_history ) == 0 ) {
1091 # Don't do any of the following
1092 $out .= $outLine . "\n";
1094 } elseif ( $first_two === '|}' ) {
1095 # We are ending a table
1096 $line = '</table>' . substr( $line, 2 );
1097 $last_tag = array_pop( $last_tag_history );
1099 if ( !array_pop( $has_opened_tr ) ) {
1100 $line = "<tr><td></td></tr>{$line}";
1103 if ( array_pop( $tr_history ) ) {
1104 $line = "</tr>{$line}";
1107 if ( array_pop( $td_history ) ) {
1108 $line = "</{$last_tag}>{$line}";
1110 array_pop( $tr_attributes );
1111 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1112 } elseif ( $first_two === '|-' ) {
1113 # Now we have a table row
1114 $line = preg_replace( '#^\|-+#', '', $line );
1116 # Whats after the tag is now only attributes
1117 $attributes = $this->mStripState
->unstripBoth( $line );
1118 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1119 array_pop( $tr_attributes );
1120 array_push( $tr_attributes, $attributes );
1123 $last_tag = array_pop( $last_tag_history );
1124 array_pop( $has_opened_tr );
1125 array_push( $has_opened_tr, true );
1127 if ( array_pop( $tr_history ) ) {
1131 if ( array_pop( $td_history ) ) {
1132 $line = "</{$last_tag}>{$line}";
1136 array_push( $tr_history, false );
1137 array_push( $td_history, false );
1138 array_push( $last_tag_history, '' );
1139 } elseif ( $first_character === '|'
1140 ||
$first_character === '!'
1141 ||
$first_two === '|+'
1143 # This might be cell elements, td, th or captions
1144 if ( $first_two === '|+' ) {
1145 $first_character = '+';
1146 $line = substr( $line, 2 );
1148 $line = substr( $line, 1 );
1151 // Implies both are valid for table headings.
1152 if ( $first_character === '!' ) {
1153 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1156 # Split up multiple cells on the same line.
1157 # FIXME : This can result in improper nesting of tags processed
1158 # by earlier parser steps.
1159 $cells = explode( '||', $line );
1163 # Loop through each table cell
1164 foreach ( $cells as $cell ) {
1166 if ( $first_character !== '+' ) {
1167 $tr_after = array_pop( $tr_attributes );
1168 if ( !array_pop( $tr_history ) ) {
1169 $previous = "<tr{$tr_after}>\n";
1171 array_push( $tr_history, true );
1172 array_push( $tr_attributes, '' );
1173 array_pop( $has_opened_tr );
1174 array_push( $has_opened_tr, true );
1177 $last_tag = array_pop( $last_tag_history );
1179 if ( array_pop( $td_history ) ) {
1180 $previous = "</{$last_tag}>\n{$previous}";
1183 if ( $first_character === '|' ) {
1185 } elseif ( $first_character === '!' ) {
1187 } elseif ( $first_character === '+' ) {
1188 $last_tag = 'caption';
1193 array_push( $last_tag_history, $last_tag );
1195 # A cell could contain both parameters and data
1196 $cell_data = explode( '|', $cell, 2 );
1198 # T2553: Note that a '|' inside an invalid link should not
1199 # be mistaken as delimiting cell parameters
1200 # Bug T153140: Neither should language converter markup.
1201 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1202 $cell = "{$previous}<{$last_tag}>{$cell}";
1203 } elseif ( count( $cell_data ) == 1 ) {
1204 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1206 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1207 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1208 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1212 array_push( $td_history, true );
1215 $out .= $outLine . "\n";
1218 # Closing open td, tr && table
1219 while ( count( $td_history ) > 0 ) {
1220 if ( array_pop( $td_history ) ) {
1223 if ( array_pop( $tr_history ) ) {
1226 if ( !array_pop( $has_opened_tr ) ) {
1227 $out .= "<tr><td></td></tr>\n";
1230 $out .= "</table>\n";
1233 # Remove trailing line-ending (b/c)
1234 if ( substr( $out, -1 ) === "\n" ) {
1235 $out = substr( $out, 0, -1 );
1238 # special case: don't return empty table
1239 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1247 * Helper function for parse() that transforms wiki markup into half-parsed
1248 * HTML. Only called for $mOutputType == self::OT_HTML.
1252 * @param string $text The text to parse
1253 * @param bool $isMain Whether this is being called from the main parse() function
1254 * @param PPFrame|bool $frame A pre-processor frame
1258 public function internalParse( $text, $isMain = true, $frame = false ) {
1261 // Avoid PHP 7.1 warning from passing $this by reference
1264 # Hook to suspend the parser in this state
1265 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1269 # if $frame is provided, then use $frame for replacing any variables
1271 # use frame depth to infer how include/noinclude tags should be handled
1272 # depth=0 means this is the top-level document; otherwise it's an included document
1273 if ( !$frame->depth
) {
1276 $flag = self
::PTD_FOR_INCLUSION
;
1278 $dom = $this->preprocessToDom( $text, $flag );
1279 $text = $frame->expand( $dom );
1281 # if $frame is not provided, then use old-style replaceVariables
1282 $text = $this->replaceVariables( $text );
1285 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1286 $text = Sanitizer
::removeHTMLtags(
1288 [ $this, 'attributeStripCallback' ],
1290 array_keys( $this->mTransparentTagHooks
),
1292 [ $this, 'addTrackingCategory' ]
1294 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1296 # Tables need to come after variable replacement for things to work
1297 # properly; putting them before other transformations should keep
1298 # exciting things like link expansions from showing up in surprising
1300 $text = $this->doTableStuff( $text );
1302 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1304 $text = $this->doDoubleUnderscore( $text );
1306 $text = $this->doHeadings( $text );
1307 $text = $this->replaceInternalLinks( $text );
1308 $text = $this->doAllQuotes( $text );
1309 $text = $this->replaceExternalLinks( $text );
1311 # replaceInternalLinks may sometimes leave behind
1312 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1313 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1315 $text = $this->doMagicLinks( $text );
1316 $text = $this->formatHeadings( $text, $origText, $isMain );
1322 * Helper function for parse() that transforms half-parsed HTML into fully
1325 * @param string $text
1326 * @param bool $isMain
1327 * @param bool $linestart
1330 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1331 $text = $this->mStripState
->unstripGeneral( $text );
1333 // Avoid PHP 7.1 warning from passing $this by reference
1337 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1340 # Clean up special characters, only run once, next-to-last before doBlockLevels
1342 # French spaces, last one Guillemet-left
1343 # only if there is something before the space
1344 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1345 # french spaces, Guillemet-right
1346 '/(\\302\\253) /' => '\\1 ',
1347 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1349 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1351 $text = $this->doBlockLevels( $text, $linestart );
1353 $this->replaceLinkHolders( $text );
1356 * The input doesn't get language converted if
1358 * b) Content isn't converted
1359 * c) It's a conversion table
1360 * d) it is an interface message (which is in the user language)
1362 if ( !( $this->mOptions
->getDisableContentConversion()
1363 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1365 if ( !$this->mOptions
->getInterfaceMessage() ) {
1366 # The position of the convert() call should not be changed. it
1367 # assumes that the links are all replaced and the only thing left
1368 # is the <nowiki> mark.
1369 $text = $this->getConverterLanguage()->convert( $text );
1373 $text = $this->mStripState
->unstripNoWiki( $text );
1376 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1379 $text = $this->replaceTransparentTags( $text );
1380 $text = $this->mStripState
->unstripGeneral( $text );
1382 $text = Sanitizer
::normalizeCharReferences( $text );
1384 if ( MWTidy
::isEnabled() ) {
1385 if ( $this->mOptions
->getTidy() ) {
1386 $text = MWTidy
::tidy( $text );
1389 # attempt to sanitize at least some nesting problems
1390 # (T4702 and quite a few others)
1392 # ''Something [http://www.cool.com cool''] -->
1393 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1394 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1395 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1396 # fix up an anchor inside another anchor, only
1397 # at least for a single single nested link (T5695)
1398 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1399 '\\1\\2</a>\\3</a>\\1\\4</a>',
1400 # fix div inside inline elements- doBlockLevels won't wrap a line which
1401 # contains a div, so fix it up here; replace
1402 # div with escaped text
1403 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1404 '\\1\\3<div\\5>\\6</div>\\8\\9',
1405 # remove empty italic or bold tag pairs, some
1406 # introduced by rules above
1407 '/<([bi])><\/\\1>/' => '',
1410 $text = preg_replace(
1411 array_keys( $tidyregs ),
1412 array_values( $tidyregs ),
1417 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1424 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1425 * magic external links.
1430 * @param string $text
1434 public function doMagicLinks( $text ) {
1435 $prots = wfUrlProtocolsWithoutProtRel();
1436 $urlChar = self
::EXT_LINK_URL_CLASS
;
1437 $addr = self
::EXT_LINK_ADDR
;
1438 $space = self
::SPACE_NOT_NL
; # non-newline space
1439 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1440 $spaces = "$space++"; # possessive match of 1 or more spaces
1441 $text = preg_replace_callback(
1443 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1444 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1445 (\b # m[3]: Free external links
1447 ($addr$urlChar*) # m[4]: Post-protocol path
1449 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1451 \bISBN $spaces ( # m[6]: ISBN, capture number
1452 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1453 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1454 [0-9Xx] # check digit
1456 )!xu", [ $this, 'magicLinkCallback' ], $text );
1461 * @throws MWException
1463 * @return HTML|string
1465 public function magicLinkCallback( $m ) {
1466 if ( isset( $m[1] ) && $m[1] !== '' ) {
1469 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1472 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1473 # Free external link
1474 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1475 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1477 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1478 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1483 $cssClass = 'mw-magiclink-rfc';
1484 $trackingCat = 'magiclink-tracking-rfc';
1486 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1487 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1491 $urlmsg = 'pubmedurl';
1492 $cssClass = 'mw-magiclink-pmid';
1493 $trackingCat = 'magiclink-tracking-pmid';
1496 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1497 substr( $m[0], 0, 20 ) . '"' );
1499 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1500 $this->addTrackingCategory( $trackingCat );
1501 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1502 } elseif ( isset( $m[6] ) && $m[6] !== ''
1503 && $this->mOptions
->getMagicISBNLinks()
1507 $space = self
::SPACE_NOT_NL
; # non-newline space
1508 $isbn = preg_replace( "/$space/", ' ', $isbn );
1509 $num = strtr( $isbn, [
1514 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1515 return $this->getLinkRenderer()->makeKnownLink(
1516 SpecialPage
::getTitleFor( 'Booksources', $num ),
1519 'class' => 'internal mw-magiclink-isbn',
1520 'title' => false // suppress title attribute
1529 * Make a free external link, given a user-supplied URL
1531 * @param string $url
1532 * @param int $numPostProto
1533 * The number of characters after the protocol.
1534 * @return string HTML
1537 public function makeFreeExternalLink( $url, $numPostProto ) {
1540 # The characters '<' and '>' (which were escaped by
1541 # removeHTMLtags()) should not be included in
1542 # URLs, per RFC 2396.
1543 # Make terminate a URL as well (bug T84937)
1546 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1551 $trail = substr( $url, $m2[0][1] ) . $trail;
1552 $url = substr( $url, 0, $m2[0][1] );
1555 # Move trailing punctuation to $trail
1557 # If there is no left bracket, then consider right brackets fair game too
1558 if ( strpos( $url, '(' ) === false ) {
1562 $urlRev = strrev( $url );
1563 $numSepChars = strspn( $urlRev, $sep );
1564 # Don't break a trailing HTML entity by moving the ; into $trail
1565 # This is in hot code, so use substr_compare to avoid having to
1566 # create a new string object for the comparison
1567 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1568 # more optimization: instead of running preg_match with a $
1569 # anchor, which can be slow, do the match on the reversed
1570 # string starting at the desired offset.
1571 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1572 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1576 if ( $numSepChars ) {
1577 $trail = substr( $url, -$numSepChars ) . $trail;
1578 $url = substr( $url, 0, -$numSepChars );
1581 # Verify that we still have a real URL after trail removal, and
1582 # not just lone protocol
1583 if ( strlen( $trail ) >= $numPostProto ) {
1584 return $url . $trail;
1587 $url = Sanitizer
::cleanUrl( $url );
1589 # Is this an external image?
1590 $text = $this->maybeMakeExternalImage( $url );
1591 if ( $text === false ) {
1592 # Not an image, make a link
1593 $text = Linker
::makeExternalLink( $url,
1594 $this->getConverterLanguage()->markNoConversion( $url, true ),
1596 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1597 # Register it in the output object...
1598 $this->mOutput
->addExternalLink( $url );
1600 return $text . $trail;
1604 * Parse headers and return html
1608 * @param string $text
1612 public function doHeadings( $text ) {
1613 for ( $i = 6; $i >= 1; --$i ) {
1614 $h = str_repeat( '=', $i );
1615 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1621 * Replace single quotes with HTML markup
1624 * @param string $text
1626 * @return string The altered text
1628 public function doAllQuotes( $text ) {
1630 $lines = StringUtils
::explode( "\n", $text );
1631 foreach ( $lines as $line ) {
1632 $outtext .= $this->doQuotes( $line ) . "\n";
1634 $outtext = substr( $outtext, 0, -1 );
1639 * Helper function for doAllQuotes()
1641 * @param string $text
1645 public function doQuotes( $text ) {
1646 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1647 $countarr = count( $arr );
1648 if ( $countarr == 1 ) {
1652 // First, do some preliminary work. This may shift some apostrophes from
1653 // being mark-up to being text. It also counts the number of occurrences
1654 // of bold and italics mark-ups.
1657 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1658 $thislen = strlen( $arr[$i] );
1659 // If there are ever four apostrophes, assume the first is supposed to
1660 // be text, and the remaining three constitute mark-up for bold text.
1661 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1662 if ( $thislen == 4 ) {
1663 $arr[$i - 1] .= "'";
1666 } elseif ( $thislen > 5 ) {
1667 // If there are more than 5 apostrophes in a row, assume they're all
1668 // text except for the last 5.
1669 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1670 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1674 // Count the number of occurrences of bold and italics mark-ups.
1675 if ( $thislen == 2 ) {
1677 } elseif ( $thislen == 3 ) {
1679 } elseif ( $thislen == 5 ) {
1685 // If there is an odd number of both bold and italics, it is likely
1686 // that one of the bold ones was meant to be an apostrophe followed
1687 // by italics. Which one we cannot know for certain, but it is more
1688 // likely to be one that has a single-letter word before it.
1689 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1690 $firstsingleletterword = -1;
1691 $firstmultiletterword = -1;
1693 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1694 if ( strlen( $arr[$i] ) == 3 ) {
1695 $x1 = substr( $arr[$i - 1], -1 );
1696 $x2 = substr( $arr[$i - 1], -2, 1 );
1697 if ( $x1 === ' ' ) {
1698 if ( $firstspace == -1 ) {
1701 } elseif ( $x2 === ' ' ) {
1702 $firstsingleletterword = $i;
1703 // if $firstsingleletterword is set, we don't
1704 // look at the other options, so we can bail early.
1707 if ( $firstmultiletterword == -1 ) {
1708 $firstmultiletterword = $i;
1714 // If there is a single-letter word, use it!
1715 if ( $firstsingleletterword > -1 ) {
1716 $arr[$firstsingleletterword] = "''";
1717 $arr[$firstsingleletterword - 1] .= "'";
1718 } elseif ( $firstmultiletterword > -1 ) {
1719 // If not, but there's a multi-letter word, use that one.
1720 $arr[$firstmultiletterword] = "''";
1721 $arr[$firstmultiletterword - 1] .= "'";
1722 } elseif ( $firstspace > -1 ) {
1723 // ... otherwise use the first one that has neither.
1724 // (notice that it is possible for all three to be -1 if, for example,
1725 // there is only one pentuple-apostrophe in the line)
1726 $arr[$firstspace] = "''";
1727 $arr[$firstspace - 1] .= "'";
1731 // Now let's actually convert our apostrophic mush to HTML!
1736 foreach ( $arr as $r ) {
1737 if ( ( $i %
2 ) == 0 ) {
1738 if ( $state === 'both' ) {
1744 $thislen = strlen( $r );
1745 if ( $thislen == 2 ) {
1746 if ( $state === 'i' ) {
1749 } elseif ( $state === 'bi' ) {
1752 } elseif ( $state === 'ib' ) {
1753 $output .= '</b></i><b>';
1755 } elseif ( $state === 'both' ) {
1756 $output .= '<b><i>' . $buffer . '</i>';
1758 } else { // $state can be 'b' or ''
1762 } elseif ( $thislen == 3 ) {
1763 if ( $state === 'b' ) {
1766 } elseif ( $state === 'bi' ) {
1767 $output .= '</i></b><i>';
1769 } elseif ( $state === 'ib' ) {
1772 } elseif ( $state === 'both' ) {
1773 $output .= '<i><b>' . $buffer . '</b>';
1775 } else { // $state can be 'i' or ''
1779 } elseif ( $thislen == 5 ) {
1780 if ( $state === 'b' ) {
1781 $output .= '</b><i>';
1783 } elseif ( $state === 'i' ) {
1784 $output .= '</i><b>';
1786 } elseif ( $state === 'bi' ) {
1787 $output .= '</i></b>';
1789 } elseif ( $state === 'ib' ) {
1790 $output .= '</b></i>';
1792 } elseif ( $state === 'both' ) {
1793 $output .= '<i><b>' . $buffer . '</b></i>';
1795 } else { // ($state == '')
1803 // Now close all remaining tags. Notice that the order is important.
1804 if ( $state === 'b' ||
$state === 'ib' ) {
1807 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1810 if ( $state === 'bi' ) {
1813 // There might be lonely ''''', so make sure we have a buffer
1814 if ( $state === 'both' && $buffer ) {
1815 $output .= '<b><i>' . $buffer . '</i></b>';
1821 * Replace external links (REL)
1823 * Note: this is all very hackish and the order of execution matters a lot.
1824 * Make sure to run tests/parser/parserTests.php if you change this code.
1828 * @param string $text
1830 * @throws MWException
1833 public function replaceExternalLinks( $text ) {
1834 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1835 if ( $bits === false ) {
1836 throw new MWException( "PCRE needs to be compiled with "
1837 . "--enable-unicode-properties in order for MediaWiki to function" );
1839 $s = array_shift( $bits );
1842 while ( $i < count( $bits ) ) {
1845 $text = $bits[$i++
];
1846 $trail = $bits[$i++
];
1848 # The characters '<' and '>' (which were escaped by
1849 # removeHTMLtags()) should not be included in
1850 # URLs, per RFC 2396.
1852 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1853 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1854 $url = substr( $url, 0, $m2[0][1] );
1857 # If the link text is an image URL, replace it with an <img> tag
1858 # This happened by accident in the original parser, but some people used it extensively
1859 $img = $this->maybeMakeExternalImage( $text );
1860 if ( $img !== false ) {
1866 # Set linktype for CSS - if URL==text, link is essentially free
1867 $linktype = ( $text === $url ) ?
'free' : 'text';
1869 # No link text, e.g. [http://domain.tld/some.link]
1870 if ( $text == '' ) {
1872 $langObj = $this->getTargetLanguage();
1873 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1874 $linktype = 'autonumber';
1876 # Have link text, e.g. [http://domain.tld/some.link text]s
1878 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1881 $text = $this->getConverterLanguage()->markNoConversion( $text );
1883 $url = Sanitizer
::cleanUrl( $url );
1885 # Use the encoded URL
1886 # This means that users can paste URLs directly into the text
1887 # Funny characters like ö aren't valid in URLs anyway
1888 # This was changed in August 2004
1889 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1890 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1892 # Register link in the output object.
1893 $this->mOutput
->addExternalLink( $url );
1900 * Get the rel attribute for a particular external link.
1903 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1904 * nofollow if appropriate
1905 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1906 * @return string|null Rel attribute for $url
1908 public static function getExternalLinkRel( $url = false, $title = null ) {
1909 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1910 $ns = $title ?
$title->getNamespace() : false;
1911 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1912 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1920 * Get an associative array of additional HTML attributes appropriate for a
1921 * particular external link. This currently may include rel => nofollow
1922 * (depending on configuration, namespace, and the URL's domain) and/or a
1923 * target attribute (depending on configuration).
1925 * @param string $url URL to extract the domain from for rel =>
1926 * nofollow if appropriate
1927 * @return array Associative array of HTML attributes
1929 public function getExternalLinkAttribs( $url ) {
1931 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1933 $target = $this->mOptions
->getExternalLinkTarget();
1935 $attribs['target'] = $target;
1936 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1937 // T133507. New windows can navigate parent cross-origin.
1938 // Including noreferrer due to lacking browser
1939 // support of noopener. Eventually noreferrer should be removed.
1940 if ( $rel !== '' ) {
1943 $rel .= 'noreferrer noopener';
1946 $attribs['rel'] = $rel;
1951 * Replace unusual escape codes in a URL with their equivalent characters
1953 * This generally follows the syntax defined in RFC 3986, with special
1954 * consideration for HTTP query strings.
1956 * @param string $url
1959 public static function normalizeLinkUrl( $url ) {
1960 # First, make sure unsafe characters are encoded
1961 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1963 return rawurlencode( $m[0] );
1969 $end = strlen( $url );
1971 # Fragment part - 'fragment'
1972 $start = strpos( $url, '#' );
1973 if ( $start !== false && $start < $end ) {
1974 $ret = self
::normalizeUrlComponent(
1975 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1979 # Query part - 'query' minus &=+;
1980 $start = strpos( $url, '?' );
1981 if ( $start !== false && $start < $end ) {
1982 $ret = self
::normalizeUrlComponent(
1983 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1987 # Scheme and path part - 'pchar'
1988 # (we assume no userinfo or encoded colons in the host)
1989 $ret = self
::normalizeUrlComponent(
1990 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1995 private static function normalizeUrlComponent( $component, $unsafe ) {
1996 $callback = function ( $matches ) use ( $unsafe ) {
1997 $char = urldecode( $matches[0] );
1998 $ord = ord( $char );
1999 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2003 # Leave it escaped, but use uppercase for a-f
2004 return strtoupper( $matches[0] );
2007 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2011 * make an image if it's allowed, either through the global
2012 * option, through the exception, or through the on-wiki whitelist
2014 * @param string $url
2018 private function maybeMakeExternalImage( $url ) {
2019 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2020 $imagesexception = !empty( $imagesfrom );
2022 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2023 if ( $imagesexception && is_array( $imagesfrom ) ) {
2024 $imagematch = false;
2025 foreach ( $imagesfrom as $match ) {
2026 if ( strpos( $url, $match ) === 0 ) {
2031 } elseif ( $imagesexception ) {
2032 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2034 $imagematch = false;
2037 if ( $this->mOptions
->getAllowExternalImages()
2038 ||
( $imagesexception && $imagematch )
2040 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2042 $text = Linker
::makeExternalImage( $url );
2045 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2046 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2048 $whitelist = explode(
2050 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2053 foreach ( $whitelist as $entry ) {
2054 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2055 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2058 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2059 # Image matches a whitelist entry
2060 $text = Linker
::makeExternalImage( $url );
2069 * Process [[ ]] wikilinks
2073 * @return string Processed text
2077 public function replaceInternalLinks( $s ) {
2078 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2083 * Process [[ ]] wikilinks (RIL)
2085 * @throws MWException
2086 * @return LinkHolderArray
2090 public function replaceInternalLinks2( &$s ) {
2091 global $wgExtraInterlanguageLinkPrefixes;
2093 static $tc = false, $e1, $e1_img;
2094 # the % is needed to support urlencoded titles as well
2096 $tc = Title
::legalChars() . '#%';
2097 # Match a link having the form [[namespace:link|alternate]]trail
2098 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2099 # Match cases where there is no "]]", which might still be images
2100 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2103 $holders = new LinkHolderArray( $this );
2105 # split the entire text string on occurrences of [[
2106 $a = StringUtils
::explode( '[[', ' ' . $s );
2107 # get the first element (all text up to first [[), and remove the space we added
2110 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2111 $s = substr( $s, 1 );
2113 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2115 if ( $useLinkPrefixExtension ) {
2116 # Match the end of a line for a word that's not followed by whitespace,
2117 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2119 $charset = $wgContLang->linkPrefixCharset();
2120 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2123 if ( is_null( $this->mTitle
) ) {
2124 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2126 $nottalk = !$this->mTitle
->isTalkPage();
2128 if ( $useLinkPrefixExtension ) {
2130 if ( preg_match( $e2, $s, $m ) ) {
2131 $first_prefix = $m[2];
2133 $first_prefix = false;
2139 $useSubpages = $this->areSubpagesAllowed();
2141 # Loop for each link
2142 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2143 # Check for excessive memory usage
2144 if ( $holders->isBig() ) {
2146 # Do the existence check, replace the link holders and clear the array
2147 $holders->replace( $s );
2151 if ( $useLinkPrefixExtension ) {
2152 if ( preg_match( $e2, $s, $m ) ) {
2159 if ( $first_prefix ) {
2160 $prefix = $first_prefix;
2161 $first_prefix = false;
2165 $might_be_img = false;
2167 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2169 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2170 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2171 # the real problem is with the $e1 regex
2173 # Still some problems for cases where the ] is meant to be outside punctuation,
2174 # and no image is in sight. See T4095.
2176 && substr( $m[3], 0, 1 ) === ']'
2177 && strpos( $text, '[' ) !== false
2179 $text .= ']'; # so that replaceExternalLinks($text) works later
2180 $m[3] = substr( $m[3], 1 );
2182 # fix up urlencoded title texts
2183 if ( strpos( $m[1], '%' ) !== false ) {
2184 # Should anchors '#' also be rejected?
2185 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2188 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2189 # Invalid, but might be an image with a link in its caption
2190 $might_be_img = true;
2192 if ( strpos( $m[1], '%' ) !== false ) {
2193 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2196 } else { # Invalid form; output directly
2197 $s .= $prefix . '[[' . $line;
2201 $origLink = ltrim( $m[1], ' ' );
2203 # Don't allow internal links to pages containing
2204 # PROTO: where PROTO is a valid URL protocol; these
2205 # should be external links.
2206 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2207 $s .= $prefix . '[[' . $line;
2211 # Make subpage if necessary
2212 if ( $useSubpages ) {
2213 $link = $this->maybeDoSubpageLink( $origLink, $text );
2218 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2219 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2220 if ( $nt === null ) {
2221 $s .= $prefix . '[[' . $line;
2225 $ns = $nt->getNamespace();
2226 $iw = $nt->getInterwiki();
2228 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2230 if ( $might_be_img ) { # if this is actually an invalid link
2231 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2234 # look at the next 'line' to see if we can close it there
2236 $next_line = $a->current();
2237 if ( $next_line === false ||
$next_line === null ) {
2240 $m = explode( ']]', $next_line, 3 );
2241 if ( count( $m ) == 3 ) {
2242 # the first ]] closes the inner link, the second the image
2244 $text .= "[[{$m[0]}]]{$m[1]}";
2247 } elseif ( count( $m ) == 2 ) {
2248 # if there's exactly one ]] that's fine, we'll keep looking
2249 $text .= "[[{$m[0]}]]{$m[1]}";
2251 # if $next_line is invalid too, we need look no further
2252 $text .= '[[' . $next_line;
2257 # we couldn't find the end of this imageLink, so output it raw
2258 # but don't ignore what might be perfectly normal links in the text we've examined
2259 $holders->merge( $this->replaceInternalLinks2( $text ) );
2260 $s .= "{$prefix}[[$link|$text";
2261 # note: no $trail, because without an end, there *is* no trail
2264 } else { # it's not an image, so output it raw
2265 $s .= "{$prefix}[[$link|$text";
2266 # note: no $trail, because without an end, there *is* no trail
2271 $wasblank = ( $text == '' );
2275 # Strip off leading ':'
2276 $text = substr( $text, 1 );
2279 # T6598 madness. Handle the quotes only if they come from the alternate part
2280 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2281 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2282 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2283 $text = $this->doQuotes( $text );
2286 # Link not escaped by : , create the various objects
2287 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2290 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2291 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2292 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2295 # T26502: filter duplicates
2296 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2297 $this->mLangLinkLanguages
[$iw] = true;
2298 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2302 * Strip the whitespace interwiki links produce, see T10897
2304 $s = rtrim( $s . $prefix ) . $trail; # T175416
2308 if ( $ns == NS_FILE
) {
2309 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2311 # if no parameters were passed, $text
2312 # becomes something like "File:Foo.png",
2313 # which we don't want to pass on to the
2317 # recursively parse links inside the image caption
2318 # actually, this will parse them in any other parameters, too,
2319 # but it might be hard to fix that, and it doesn't matter ATM
2320 $text = $this->replaceExternalLinks( $text );
2321 $holders->merge( $this->replaceInternalLinks2( $text ) );
2323 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2324 $s .= $prefix . $this->armorLinks(
2325 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2328 } elseif ( $ns == NS_CATEGORY
) {
2330 * Strip the whitespace Category links produce, see T2087
2332 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2335 $sortkey = $this->getDefaultSort();
2339 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2340 $sortkey = str_replace( "\n", '', $sortkey );
2341 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2342 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2348 # Self-link checking. For some languages, variants of the title are checked in
2349 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2350 # for linking to a different variant.
2351 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2352 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2356 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2357 # @todo FIXME: Should do batch file existence checks, see comment below
2358 if ( $ns == NS_MEDIA
) {
2359 # Give extensions a chance to select the file revision for us
2362 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2363 [ $this, $nt, &$options, &$descQuery ] );
2364 # Fetch and register the file (file title may be different via hooks)
2365 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2366 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2367 $s .= $prefix . $this->armorLinks(
2368 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2372 # Some titles, such as valid special pages or files in foreign repos, should
2373 # be shown as bluelinks even though they're not included in the page table
2374 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2375 # batch file existence checks for NS_FILE and NS_MEDIA
2376 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2377 $this->mOutput
->addLink( $nt );
2378 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2380 # Links will be added to the output link list after checking
2381 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2388 * Render a forced-blue link inline; protect against double expansion of
2389 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2390 * Since this little disaster has to split off the trail text to avoid
2391 * breaking URLs in the following text without breaking trails on the
2392 * wiki links, it's been made into a horrible function.
2395 * @param string $text
2396 * @param string $trail
2397 * @param string $prefix
2398 * @return string HTML-wikitext mix oh yuck
2400 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2401 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2403 if ( $text == '' ) {
2404 $text = htmlspecialchars( $nt->getPrefixedText() );
2407 $link = $this->getLinkRenderer()->makeKnownLink(
2408 $nt, new HtmlArmor( "$prefix$text$inside" )
2411 return $this->armorLinks( $link ) . $trail;
2415 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2416 * going to go through further parsing steps before inline URL expansion.
2418 * Not needed quite as much as it used to be since free links are a bit
2419 * more sensible these days. But bracketed links are still an issue.
2421 * @param string $text More-or-less HTML
2422 * @return string Less-or-more HTML with NOPARSE bits
2424 public function armorLinks( $text ) {
2425 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2426 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2430 * Return true if subpage links should be expanded on this page.
2433 public function areSubpagesAllowed() {
2434 # Some namespaces don't allow subpages
2435 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2439 * Handle link to subpage if necessary
2441 * @param string $target The source of the link
2442 * @param string &$text The link text, modified as necessary
2443 * @return string The full name of the link
2446 public function maybeDoSubpageLink( $target, &$text ) {
2447 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2451 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2453 * @param string $text
2454 * @param bool $linestart Whether or not this is at the start of a line.
2456 * @return string The lists rendered as HTML
2458 public function doBlockLevels( $text, $linestart ) {
2459 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2463 * Return value of a magic variable (like PAGENAME)
2467 * @param string $index Magic variable identifier as mapped in MagicWord::$mVariableIDs
2468 * @param bool|PPFrame $frame
2470 * @throws MWException
2473 public function getVariableValue( $index, $frame = false ) {
2474 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2475 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2477 if ( is_null( $this->mTitle
) ) {
2478 // If no title set, bad things are going to happen
2479 // later. Title should always be set since this
2480 // should only be called in the middle of a parse
2481 // operation (but the unit-tests do funky stuff)
2482 throw new MWException( __METHOD__
. ' Should only be '
2483 . ' called while parsing (no title set)' );
2486 // Avoid PHP 7.1 warning from passing $this by reference
2490 * Some of these require message or data lookups and can be
2491 * expensive to check many times.
2493 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2494 if ( isset( $this->mVarCache
[$index] ) ) {
2495 return $this->mVarCache
[$index];
2499 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2500 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2502 $pageLang = $this->getFunctionLang();
2508 case 'currentmonth':
2509 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ), true );
2511 case 'currentmonth1':
2512 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ), true );
2514 case 'currentmonthname':
2515 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2517 case 'currentmonthnamegen':
2518 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2520 case 'currentmonthabbrev':
2521 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2524 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ), true );
2527 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ), true );
2530 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ), true );
2533 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ), true );
2535 case 'localmonthname':
2536 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2538 case 'localmonthnamegen':
2539 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2541 case 'localmonthabbrev':
2542 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2545 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ), true );
2548 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ), true );
2551 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2554 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2556 case 'fullpagename':
2557 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2559 case 'fullpagenamee':
2560 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2563 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2565 case 'subpagenamee':
2566 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2568 case 'rootpagename':
2569 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2571 case 'rootpagenamee':
2572 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2575 $this->mTitle
->getRootText()
2578 case 'basepagename':
2579 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2581 case 'basepagenamee':
2582 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2585 $this->mTitle
->getBaseText()
2588 case 'talkpagename':
2589 if ( $this->mTitle
->canHaveTalkPage() ) {
2590 $talkPage = $this->mTitle
->getTalkPage();
2591 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2596 case 'talkpagenamee':
2597 if ( $this->mTitle
->canHaveTalkPage() ) {
2598 $talkPage = $this->mTitle
->getTalkPage();
2599 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2604 case 'subjectpagename':
2605 $subjPage = $this->mTitle
->getSubjectPage();
2606 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2608 case 'subjectpagenamee':
2609 $subjPage = $this->mTitle
->getSubjectPage();
2610 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2612 case 'pageid': // requested in T25427
2613 $pageid = $this->getTitle()->getArticleID();
2614 if ( $pageid == 0 ) {
2615 # 0 means the page doesn't exist in the database,
2616 # which means the user is previewing a new page.
2617 # The vary-revision flag must be set, because the magic word
2618 # will have a different value once the page is saved.
2619 $this->mOutput
->setFlag( 'vary-revision' );
2620 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2622 $value = $pageid ?
$pageid : null;
2625 # Let the edit saving system know we should parse the page
2626 # *after* a revision ID has been assigned.
2627 $this->mOutput
->setFlag( 'vary-revision-id' );
2628 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2629 $value = $this->mRevisionId
;
2630 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2631 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2632 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2636 # Let the edit saving system know we should parse the page
2637 # *after* a revision ID has been assigned. This is for null edits.
2638 $this->mOutput
->setFlag( 'vary-revision' );
2639 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2640 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2642 case 'revisionday2':
2643 # Let the edit saving system know we should parse the page
2644 # *after* a revision ID has been assigned. This is for null edits.
2645 $this->mOutput
->setFlag( 'vary-revision' );
2646 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2647 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2649 case 'revisionmonth':
2650 # Let the edit saving system know we should parse the page
2651 # *after* a revision ID has been assigned. This is for null edits.
2652 $this->mOutput
->setFlag( 'vary-revision' );
2653 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2654 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2656 case 'revisionmonth1':
2657 # Let the edit saving system know we should parse the page
2658 # *after* a revision ID has been assigned. This is for null edits.
2659 $this->mOutput
->setFlag( 'vary-revision' );
2660 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2661 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2663 case 'revisionyear':
2664 # Let the edit saving system know we should parse the page
2665 # *after* a revision ID has been assigned. This is for null edits.
2666 $this->mOutput
->setFlag( 'vary-revision' );
2667 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2668 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2670 case 'revisiontimestamp':
2671 # Let the edit saving system know we should parse the page
2672 # *after* a revision ID has been assigned. This is for null edits.
2673 $this->mOutput
->setFlag( 'vary-revision' );
2674 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2675 $value = $this->getRevisionTimestamp();
2677 case 'revisionuser':
2678 # Let the edit saving system know we should parse the page
2679 # *after* a revision ID has been assigned for null edits.
2680 $this->mOutput
->setFlag( 'vary-user' );
2681 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2682 $value = $this->getRevisionUser();
2684 case 'revisionsize':
2685 $value = $this->getRevisionSize();
2688 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2691 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2693 case 'namespacenumber':
2694 $value = $this->mTitle
->getNamespace();
2697 $value = $this->mTitle
->canHaveTalkPage()
2698 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2702 $value = $this->mTitle
->canHaveTalkPage() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2704 case 'subjectspace':
2705 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2707 case 'subjectspacee':
2708 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2710 case 'currentdayname':
2711 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2714 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2717 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2720 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2723 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2724 # int to remove the padding
2725 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2728 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2730 case 'localdayname':
2731 $value = $pageLang->getWeekdayName(
2732 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2736 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2739 $value = $pageLang->time(
2740 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2746 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2749 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2750 # int to remove the padding
2751 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2754 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2756 case 'numberofarticles':
2757 $value = $pageLang->formatNum( SiteStats
::articles() );
2759 case 'numberoffiles':
2760 $value = $pageLang->formatNum( SiteStats
::images() );
2762 case 'numberofusers':
2763 $value = $pageLang->formatNum( SiteStats
::users() );
2765 case 'numberofactiveusers':
2766 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2768 case 'numberofpages':
2769 $value = $pageLang->formatNum( SiteStats
::pages() );
2771 case 'numberofadmins':
2772 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2774 case 'numberofedits':
2775 $value = $pageLang->formatNum( SiteStats
::edits() );
2777 case 'currenttimestamp':
2778 $value = wfTimestamp( TS_MW
, $ts );
2780 case 'localtimestamp':
2781 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2783 case 'currentversion':
2784 $value = SpecialVersion
::getVersion();
2787 return $wgArticlePath;
2793 return $wgServerName;
2795 return $wgScriptPath;
2797 return $wgStylePath;
2798 case 'directionmark':
2799 return $pageLang->getDirMark();
2800 case 'contentlanguage':
2801 global $wgLanguageCode;
2802 return $wgLanguageCode;
2803 case 'pagelanguage':
2804 $value = $pageLang->getCode();
2806 case 'cascadingsources':
2807 $value = CoreParserFunctions
::cascadingsources( $this );
2812 'ParserGetVariableValueSwitch',
2813 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2820 $this->mVarCache
[$index] = $value;
2827 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2831 public function initialiseVariables() {
2832 $variableIDs = MagicWord
::getVariableIDs();
2833 $substIDs = MagicWord
::getSubstIDs();
2835 $this->mVariables
= new MagicWordArray( $variableIDs );
2836 $this->mSubstWords
= new MagicWordArray( $substIDs );
2840 * Preprocess some wikitext and return the document tree.
2841 * This is the ghost of replace_variables().
2843 * @param string $text The text to parse
2844 * @param int $flags Bitwise combination of:
2845 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2846 * included. Default is to assume a direct page view.
2848 * The generated DOM tree must depend only on the input text and the flags.
2849 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2851 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2852 * change in the DOM tree for a given text, must be passed through the section identifier
2853 * in the section edit link and thus back to extractSections().
2855 * The output of this function is currently only cached in process memory, but a persistent
2856 * cache may be implemented at a later date which takes further advantage of these strict
2857 * dependency requirements.
2861 public function preprocessToDom( $text, $flags = 0 ) {
2862 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2867 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2873 public static function splitWhitespace( $s ) {
2874 $ltrimmed = ltrim( $s );
2875 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2876 $trimmed = rtrim( $ltrimmed );
2877 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2879 $w2 = substr( $ltrimmed, -$diff );
2883 return [ $w1, $trimmed, $w2 ];
2887 * Replace magic variables, templates, and template arguments
2888 * with the appropriate text. Templates are substituted recursively,
2889 * taking care to avoid infinite loops.
2891 * Note that the substitution depends on value of $mOutputType:
2892 * self::OT_WIKI: only {{subst:}} templates
2893 * self::OT_PREPROCESS: templates but not extension tags
2894 * self::OT_HTML: all templates and extension tags
2896 * @param string $text The text to transform
2897 * @param bool|PPFrame $frame Object describing the arguments passed to the
2898 * template. Arguments may also be provided as an associative array, as
2899 * was the usual case before MW1.12. Providing arguments this way may be
2900 * useful for extensions wishing to perform variable replacement
2902 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2903 * double-brace expansion.
2906 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2907 # Is there any text? Also, Prevent too big inclusions!
2908 $textSize = strlen( $text );
2909 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2913 if ( $frame === false ) {
2914 $frame = $this->getPreprocessor()->newFrame();
2915 } elseif ( !( $frame instanceof PPFrame
) ) {
2916 wfDebug( __METHOD__
. " called using plain parameters instead of "
2917 . "a PPFrame instance. Creating custom frame.\n" );
2918 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2921 $dom = $this->preprocessToDom( $text );
2922 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2923 $text = $frame->expand( $dom, $flags );
2929 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2931 * @param array $args
2935 public static function createAssocArgs( $args ) {
2938 foreach ( $args as $arg ) {
2939 $eqpos = strpos( $arg, '=' );
2940 if ( $eqpos === false ) {
2941 $assocArgs[$index++
] = $arg;
2943 $name = trim( substr( $arg, 0, $eqpos ) );
2944 $value = trim( substr( $arg, $eqpos +
1 ) );
2945 if ( $value === false ) {
2948 if ( $name !== false ) {
2949 $assocArgs[$name] = $value;
2958 * Warn the user when a parser limitation is reached
2959 * Will warn at most once the user per limitation type
2961 * The results are shown during preview and run through the Parser (See EditPage.php)
2963 * @param string $limitationType Should be one of:
2964 * 'expensive-parserfunction' (corresponding messages:
2965 * 'expensive-parserfunction-warning',
2966 * 'expensive-parserfunction-category')
2967 * 'post-expand-template-argument' (corresponding messages:
2968 * 'post-expand-template-argument-warning',
2969 * 'post-expand-template-argument-category')
2970 * 'post-expand-template-inclusion' (corresponding messages:
2971 * 'post-expand-template-inclusion-warning',
2972 * 'post-expand-template-inclusion-category')
2973 * 'node-count-exceeded' (corresponding messages:
2974 * 'node-count-exceeded-warning',
2975 * 'node-count-exceeded-category')
2976 * 'expansion-depth-exceeded' (corresponding messages:
2977 * 'expansion-depth-exceeded-warning',
2978 * 'expansion-depth-exceeded-category')
2979 * @param string|int|null $current Current value
2980 * @param string|int|null $max Maximum allowed, when an explicit limit has been
2981 * exceeded, provide the values (optional)
2983 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
2984 # does no harm if $current and $max are present but are unnecessary for the message
2985 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
2986 # only during preview, and that would split the parser cache unnecessarily.
2987 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
2989 $this->mOutput
->addWarning( $warning );
2990 $this->addTrackingCategory( "$limitationType-category" );
2994 * Return the text of a template, after recursively
2995 * replacing any variables or templates within the template.
2997 * @param array $piece The parts of the template
2998 * $piece['title']: the title, i.e. the part before the |
2999 * $piece['parts']: the parameter array
3000 * $piece['lineStart']: whether the brace was at the start of a line
3001 * @param PPFrame $frame The current frame, contains template arguments
3003 * @return string The text of the template
3005 public function braceSubstitution( $piece, $frame ) {
3008 // $text has been filled
3010 // wiki markup in $text should be escaped
3012 // $text is HTML, armour it against wikitext transformation
3014 // Force interwiki transclusion to be done in raw mode not rendered
3015 $forceRawInterwiki = false;
3016 // $text is a DOM node needing expansion in a child frame
3017 $isChildObj = false;
3018 // $text is a DOM node needing expansion in the current frame
3019 $isLocalObj = false;
3021 # Title object, where $text came from
3024 # $part1 is the bit before the first |, and must contain only title characters.
3025 # Various prefixes will be stripped from it later.
3026 $titleWithSpaces = $frame->expand( $piece['title'] );
3027 $part1 = trim( $titleWithSpaces );
3030 # Original title text preserved for various purposes
3031 $originalTitle = $part1;
3033 # $args is a list of argument nodes, starting from index 0, not including $part1
3034 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3035 # below won't work b/c this $args isn't an object
3036 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3038 $profileSection = null; // profile templates
3042 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3044 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3045 # Decide whether to expand template or keep wikitext as-is.
3046 if ( $this->ot
['wiki'] ) {
3047 if ( $substMatch === false ) {
3048 $literal = true; # literal when in PST with no prefix
3050 $literal = false; # expand when in PST with subst: or safesubst:
3053 if ( $substMatch == 'subst' ) {
3054 $literal = true; # literal when not in PST with plain subst:
3056 $literal = false; # expand when not in PST with safesubst: or no prefix
3060 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3067 if ( !$found && $args->getLength() == 0 ) {
3068 $id = $this->mVariables
->matchStartToEnd( $part1 );
3069 if ( $id !== false ) {
3070 $text = $this->getVariableValue( $id, $frame );
3071 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3072 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3078 # MSG, MSGNW and RAW
3081 $mwMsgnw = MagicWord
::get( 'msgnw' );
3082 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3085 # Remove obsolete MSG:
3086 $mwMsg = MagicWord
::get( 'msg' );
3087 $mwMsg->matchStartAndRemove( $part1 );
3091 $mwRaw = MagicWord
::get( 'raw' );
3092 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3093 $forceRawInterwiki = true;
3099 $colonPos = strpos( $part1, ':' );
3100 if ( $colonPos !== false ) {
3101 $func = substr( $part1, 0, $colonPos );
3102 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3103 $argsLength = $args->getLength();
3104 for ( $i = 0; $i < $argsLength; $i++
) {
3105 $funcArgs[] = $args->item( $i );
3108 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3109 } catch ( Exception
$ex ) {
3113 // Extract any forwarded flags
3114 if ( isset( $result['title'] ) ) {
3115 $title = $result['title'];
3117 if ( isset( $result['found'] ) ) {
3118 $found = $result['found'];
3120 if ( array_key_exists( 'text', $result ) ) {
3122 $text = $result['text'];
3124 if ( isset( $result['nowiki'] ) ) {
3125 $nowiki = $result['nowiki'];
3127 if ( isset( $result['isHTML'] ) ) {
3128 $isHTML = $result['isHTML'];
3130 if ( isset( $result['forceRawInterwiki'] ) ) {
3131 $forceRawInterwiki = $result['forceRawInterwiki'];
3133 if ( isset( $result['isChildObj'] ) ) {
3134 $isChildObj = $result['isChildObj'];
3136 if ( isset( $result['isLocalObj'] ) ) {
3137 $isLocalObj = $result['isLocalObj'];
3142 # Finish mangling title and then check for loops.
3143 # Set $title to a Title object and $titleText to the PDBK
3146 # Split the title into page and subpage
3148 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3149 if ( $part1 !== $relative ) {
3151 $ns = $this->mTitle
->getNamespace();
3153 $title = Title
::newFromText( $part1, $ns );
3155 $titleText = $title->getPrefixedText();
3156 # Check for language variants if the template is not found
3157 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3158 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3160 # Do recursion depth check
3161 $limit = $this->mOptions
->getMaxTemplateDepth();
3162 if ( $frame->depth
>= $limit ) {
3164 $text = '<span class="error">'
3165 . wfMessage( 'parser-template-recursion-depth-warning' )
3166 ->numParams( $limit )->inContentLanguage()->text()
3172 # Load from database
3173 if ( !$found && $title ) {
3174 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3175 if ( !$title->isExternal() ) {
3176 if ( $title->isSpecialPage()
3177 && $this->mOptions
->getAllowSpecialInclusion()
3178 && $this->ot
['html']
3180 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3181 // Pass the template arguments as URL parameters.
3182 // "uselang" will have no effect since the Language object
3183 // is forced to the one defined in ParserOptions.
3185 $argsLength = $args->getLength();
3186 for ( $i = 0; $i < $argsLength; $i++
) {
3187 $bits = $args->item( $i )->splitArg();
3188 if ( strval( $bits['index'] ) === '' ) {
3189 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3190 $value = trim( $frame->expand( $bits['value'] ) );
3191 $pageArgs[$name] = $value;
3195 // Create a new context to execute the special page
3196 $context = new RequestContext
;
3197 $context->setTitle( $title );
3198 $context->setRequest( new FauxRequest( $pageArgs ) );
3199 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3200 $context->setUser( $this->getUser() );
3202 // If this page is cached, then we better not be per user.
3203 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3205 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3206 $ret = SpecialPageFactory
::capturePath(
3207 $title, $context, $this->getLinkRenderer() );
3209 $text = $context->getOutput()->getHTML();
3210 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3213 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3214 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3215 $specialPage->maxIncludeCacheTime()
3219 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3220 $found = false; # access denied
3221 wfDebug( __METHOD__
. ": template inclusion denied for " .
3222 $title->getPrefixedDBkey() . "\n" );
3224 list( $text, $title ) = $this->getTemplateDom( $title );
3225 if ( $text !== false ) {
3231 # If the title is valid but undisplayable, make a link to it
3232 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3233 $text = "[[:$titleText]]";
3236 } elseif ( $title->isTrans() ) {
3237 # Interwiki transclusion
3238 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3239 $text = $this->interwikiTransclude( $title, 'render' );
3242 $text = $this->interwikiTransclude( $title, 'raw' );
3243 # Preprocess it like a template
3244 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3250 # Do infinite loop check
3251 # This has to be done after redirect resolution to avoid infinite loops via redirects
3252 if ( !$frame->loopCheck( $title ) ) {
3254 $text = '<span class="error">'
3255 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3257 $this->addTrackingCategory( 'template-loop-category' );
3258 $this->mOutput
->addWarning( wfMessage( 'template-loop-warning',
3259 wfEscapeWikiText( $titleText ) )->text() );
3260 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3264 # If we haven't found text to substitute by now, we're done
3265 # Recover the source wikitext and return it
3267 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3268 if ( $profileSection ) {
3269 $this->mProfiler
->scopedProfileOut( $profileSection );
3271 return [ 'object' => $text ];
3274 # Expand DOM-style return values in a child frame
3275 if ( $isChildObj ) {
3276 # Clean up argument array
3277 $newFrame = $frame->newChild( $args, $title );
3280 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3281 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3282 # Expansion is eligible for the empty-frame cache
3283 $text = $newFrame->cachedExpand( $titleText, $text );
3285 # Uncached expansion
3286 $text = $newFrame->expand( $text );
3289 if ( $isLocalObj && $nowiki ) {
3290 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3291 $isLocalObj = false;
3294 if ( $profileSection ) {
3295 $this->mProfiler
->scopedProfileOut( $profileSection );
3298 # Replace raw HTML by a placeholder
3300 $text = $this->insertStripItem( $text );
3301 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3302 # Escape nowiki-style return values
3303 $text = wfEscapeWikiText( $text );
3304 } elseif ( is_string( $text )
3305 && !$piece['lineStart']
3306 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3308 # T2529: if the template begins with a table or block-level
3309 # element, it should be treated as beginning a new line.
3310 # This behavior is somewhat controversial.
3311 $text = "\n" . $text;
3314 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3315 # Error, oversize inclusion
3316 if ( $titleText !== false ) {
3317 # Make a working, properly escaped link if possible (T25588)
3318 $text = "[[:$titleText]]";
3320 # This will probably not be a working link, but at least it may
3321 # provide some hint of where the problem is
3322 preg_replace( '/^:/', '', $originalTitle );
3323 $text = "[[:$originalTitle]]";
3325 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3326 . 'post-expand include size too large -->' );
3327 $this->limitationWarn( 'post-expand-template-inclusion' );
3330 if ( $isLocalObj ) {
3331 $ret = [ 'object' => $text ];
3333 $ret = [ 'text' => $text ];
3340 * Call a parser function and return an array with text and flags.
3342 * The returned array will always contain a boolean 'found', indicating
3343 * whether the parser function was found or not. It may also contain the
3345 * text: string|object, resulting wikitext or PP DOM object
3346 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3347 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3348 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3349 * nowiki: bool, wiki markup in $text should be escaped
3352 * @param PPFrame $frame The current frame, contains template arguments
3353 * @param string $function Function name
3354 * @param array $args Arguments to the function
3355 * @throws MWException
3358 public function callParserFunction( $frame, $function, array $args = [] ) {
3361 # Case sensitive functions
3362 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3363 $function = $this->mFunctionSynonyms
[1][$function];
3365 # Case insensitive functions
3366 $function = $wgContLang->lc( $function );
3367 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3368 $function = $this->mFunctionSynonyms
[0][$function];
3370 return [ 'found' => false ];
3374 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3376 // Avoid PHP 7.1 warning from passing $this by reference
3379 $allArgs = [ &$parser ];
3380 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3381 # Convert arguments to PPNodes and collect for appending to $allArgs
3383 foreach ( $args as $k => $v ) {
3384 if ( $v instanceof PPNode ||
$k === 0 ) {
3387 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3391 # Add a frame parameter, and pass the arguments as an array
3392 $allArgs[] = $frame;
3393 $allArgs[] = $funcArgs;
3395 # Convert arguments to plain text and append to $allArgs
3396 foreach ( $args as $k => $v ) {
3397 if ( $v instanceof PPNode
) {
3398 $allArgs[] = trim( $frame->expand( $v ) );
3399 } elseif ( is_int( $k ) && $k >= 0 ) {
3400 $allArgs[] = trim( $v );
3402 $allArgs[] = trim( "$k=$v" );
3407 $result = call_user_func_array( $callback, $allArgs );
3409 # The interface for function hooks allows them to return a wikitext
3410 # string or an array containing the string and any flags. This mungs
3411 # things around to match what this method should return.
3412 if ( !is_array( $result ) ) {
3418 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3419 $result['text'] = $result[0];
3421 unset( $result[0] );
3428 $preprocessFlags = 0;
3429 if ( isset( $result['noparse'] ) ) {
3430 $noparse = $result['noparse'];
3432 if ( isset( $result['preprocessFlags'] ) ) {
3433 $preprocessFlags = $result['preprocessFlags'];
3437 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3438 $result['isChildObj'] = true;
3445 * Get the semi-parsed DOM representation of a template with a given title,
3446 * and its redirect destination title. Cached.
3448 * @param Title $title
3452 public function getTemplateDom( $title ) {
3453 $cacheTitle = $title;
3454 $titleText = $title->getPrefixedDBkey();
3456 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3457 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3458 $title = Title
::makeTitle( $ns, $dbk );
3459 $titleText = $title->getPrefixedDBkey();
3461 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3462 return [ $this->mTplDomCache
[$titleText], $title ];
3465 # Cache miss, go to the database
3466 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3468 if ( $text === false ) {
3469 $this->mTplDomCache
[$titleText] = false;
3470 return [ false, $title ];
3473 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3474 $this->mTplDomCache
[$titleText] = $dom;
3476 if ( !$title->equals( $cacheTitle ) ) {
3477 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3478 [ $title->getNamespace(), $title->getDBkey() ];
3481 return [ $dom, $title ];
3485 * Fetch the current revision of a given title. Note that the revision
3486 * (and even the title) may not exist in the database, so everything
3487 * contributing to the output of the parser should use this method
3488 * where possible, rather than getting the revisions themselves. This
3489 * method also caches its results, so using it benefits performance.
3492 * @param Title $title
3495 public function fetchCurrentRevisionOfTitle( $title ) {
3496 $cacheKey = $title->getPrefixedDBkey();
3497 if ( !$this->currentRevisionCache
) {
3498 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3500 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3501 $this->currentRevisionCache
->set( $cacheKey,
3502 // Defaults to Parser::statelessFetchRevision()
3503 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3506 return $this->currentRevisionCache
->get( $cacheKey );
3510 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3511 * without passing them on to it.
3514 * @param Title $title
3515 * @param Parser|bool $parser
3516 * @return Revision|bool False if missing
3518 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3519 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
3525 * Fetch the unparsed text of a template and register a reference to it.
3526 * @param Title $title
3527 * @return array ( string or false, Title )
3529 public function fetchTemplateAndTitle( $title ) {
3530 // Defaults to Parser::statelessFetchTemplate()
3531 $templateCb = $this->mOptions
->getTemplateCallback();
3532 $stuff = call_user_func( $templateCb, $title, $this );
3533 // We use U+007F DELETE to distinguish strip markers from regular text.
3534 $text = $stuff['text'];
3535 if ( is_string( $stuff['text'] ) ) {
3536 $text = strtr( $text, "\x7f", "?" );
3538 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3539 if ( isset( $stuff['deps'] ) ) {
3540 foreach ( $stuff['deps'] as $dep ) {
3541 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3542 if ( $dep['title']->equals( $this->getTitle() ) ) {
3543 // If we transclude ourselves, the final result
3544 // will change based on the new version of the page
3545 $this->mOutput
->setFlag( 'vary-revision' );
3549 return [ $text, $finalTitle ];
3553 * Fetch the unparsed text of a template and register a reference to it.
3554 * @param Title $title
3555 * @return string|bool
3557 public function fetchTemplate( $title ) {
3558 return $this->fetchTemplateAndTitle( $title )[0];
3562 * Static function to get a template
3563 * Can be overridden via ParserOptions::setTemplateCallback().
3565 * @param Title $title
3566 * @param bool|Parser $parser
3570 public static function statelessFetchTemplate( $title, $parser = false ) {
3571 $text = $skip = false;
3572 $finalTitle = $title;
3575 # Loop to fetch the article, with up to 1 redirect
3576 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3577 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3578 # Give extensions a chance to select the revision instead
3579 $id = false; # Assume current
3580 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3581 [ $parser, $title, &$skip, &$id ] );
3587 'page_id' => $title->getArticleID(),
3594 $rev = Revision
::newFromId( $id );
3595 } elseif ( $parser ) {
3596 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3598 $rev = Revision
::newFromTitle( $title );
3600 $rev_id = $rev ?
$rev->getId() : 0;
3601 # If there is no current revision, there is no page
3602 if ( $id === false && !$rev ) {
3603 $linkCache = LinkCache
::singleton();
3604 $linkCache->addBadLinkObj( $title );
3609 'page_id' => $title->getArticleID(),
3610 'rev_id' => $rev_id ];
3611 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3612 # We fetched a rev from a different title; register it too...
3614 'title' => $rev->getTitle(),
3615 'page_id' => $rev->getPage(),
3616 'rev_id' => $rev_id ];
3620 $content = $rev->getContent();
3621 $text = $content ?
$content->getWikitextForTransclusion() : null;
3623 Hooks
::run( 'ParserFetchTemplate',
3624 [ $parser, $title, $rev, &$text, &$deps ] );
3626 if ( $text === false ||
$text === null ) {
3630 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3632 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3633 if ( !$message->exists() ) {
3637 $content = $message->content();
3638 $text = $message->plain();
3646 $finalTitle = $title;
3647 $title = $content->getRedirectTarget();
3651 'finalTitle' => $finalTitle,
3656 * Fetch a file and its title and register a reference to it.
3657 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3658 * @param Title $title
3659 * @param array $options Array of options to RepoGroup::findFile
3662 public function fetchFile( $title, $options = [] ) {
3663 return $this->fetchFileAndTitle( $title, $options )[0];
3667 * Fetch a file and its title and register a reference to it.
3668 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3669 * @param Title $title
3670 * @param array $options Array of options to RepoGroup::findFile
3671 * @return array ( File or false, Title of file )
3673 public function fetchFileAndTitle( $title, $options = [] ) {
3674 $file = $this->fetchFileNoRegister( $title, $options );
3676 $time = $file ?
$file->getTimestamp() : false;
3677 $sha1 = $file ?
$file->getSha1() : false;
3678 # Register the file as a dependency...
3679 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3680 if ( $file && !$title->equals( $file->getTitle() ) ) {
3681 # Update fetched file title
3682 $title = $file->getTitle();
3683 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3685 return [ $file, $title ];
3689 * Helper function for fetchFileAndTitle.
3691 * Also useful if you need to fetch a file but not use it yet,
3692 * for example to get the file's handler.
3694 * @param Title $title
3695 * @param array $options Array of options to RepoGroup::findFile
3698 protected function fetchFileNoRegister( $title, $options = [] ) {
3699 if ( isset( $options['broken'] ) ) {
3700 $file = false; // broken thumbnail forced by hook
3701 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3702 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3703 } else { // get by (name,timestamp)
3704 $file = wfFindFile( $title, $options );
3710 * Transclude an interwiki link.
3712 * @param Title $title
3713 * @param string $action
3717 public function interwikiTransclude( $title, $action ) {
3718 global $wgEnableScaryTranscluding;
3720 if ( !$wgEnableScaryTranscluding ) {
3721 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3724 $url = $title->getFullURL( [ 'action' => $action ] );
3726 if ( strlen( $url ) > 255 ) {
3727 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3729 return $this->fetchScaryTemplateMaybeFromCache( $url );
3733 * @param string $url
3734 * @return mixed|string
3736 public function fetchScaryTemplateMaybeFromCache( $url ) {
3737 global $wgTranscludeCacheExpiry;
3738 $dbr = wfGetDB( DB_REPLICA
);
3739 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3740 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3741 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3743 return $obj->tc_contents
;
3746 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3747 $status = $req->execute(); // Status object
3748 if ( $status->isOK() ) {
3749 $text = $req->getContent();
3750 } elseif ( $req->getStatus() != 200 ) {
3751 // Though we failed to fetch the content, this status is useless.
3752 return wfMessage( 'scarytranscludefailed-httpstatus' )
3753 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3755 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3758 $dbw = wfGetDB( DB_MASTER
);
3759 $dbw->replace( 'transcache', [ 'tc_url' ], [
3761 'tc_time' => $dbw->timestamp( time() ),
3762 'tc_contents' => $text
3768 * Triple brace replacement -- used for template arguments
3771 * @param array $piece
3772 * @param PPFrame $frame
3776 public function argSubstitution( $piece, $frame ) {
3778 $parts = $piece['parts'];
3779 $nameWithSpaces = $frame->expand( $piece['title'] );
3780 $argName = trim( $nameWithSpaces );
3782 $text = $frame->getArgument( $argName );
3783 if ( $text === false && $parts->getLength() > 0
3784 && ( $this->ot
['html']
3786 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3789 # No match in frame, use the supplied default
3790 $object = $parts->item( 0 )->getChildren();
3792 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3793 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3794 $this->limitationWarn( 'post-expand-template-argument' );
3797 if ( $text === false && $object === false ) {
3799 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3801 if ( $error !== false ) {
3804 if ( $object !== false ) {
3805 $ret = [ 'object' => $object ];
3807 $ret = [ 'text' => $text ];
3814 * Return the text to be used for a given extension tag.
3815 * This is the ghost of strip().
3817 * @param array $params Associative array of parameters:
3818 * name PPNode for the tag name
3819 * attr PPNode for unparsed text where tag attributes are thought to be
3820 * attributes Optional associative array of parsed attributes
3821 * inner Contents of extension element
3822 * noClose Original text did not have a close tag
3823 * @param PPFrame $frame
3825 * @throws MWException
3828 public function extensionSubstitution( $params, $frame ) {
3829 static $errorStr = '<span class="error">';
3830 static $errorLen = 20;
3832 $name = $frame->expand( $params['name'] );
3833 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3834 // Probably expansion depth or node count exceeded. Just punt the
3839 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3840 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3845 // We can't safely check if the expansion for $content resulted in an
3846 // error, because the content could happen to be the error string
3848 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3850 $marker = self
::MARKER_PREFIX
. "-$name-"
3851 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3853 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3854 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3855 if ( $isFunctionTag ) {
3856 $markerType = 'none';
3858 $markerType = 'general';
3860 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3861 $name = strtolower( $name );
3862 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3863 if ( isset( $params['attributes'] ) ) {
3864 $attributes = $attributes +
$params['attributes'];
3867 if ( isset( $this->mTagHooks
[$name] ) ) {
3868 $output = call_user_func_array( $this->mTagHooks
[$name],
3869 [ $content, $attributes, $this, $frame ] );
3870 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3871 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3873 // Avoid PHP 7.1 warning from passing $this by reference
3875 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3877 $output = '<span class="error">Invalid tag extension name: ' .
3878 htmlspecialchars( $name ) . '</span>';
3881 if ( is_array( $output ) ) {
3884 $output = $flags[0];
3885 if ( isset( $flags['markerType'] ) ) {
3886 $markerType = $flags['markerType'];
3890 if ( is_null( $attrText ) ) {
3893 if ( isset( $params['attributes'] ) ) {
3894 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3895 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3896 htmlspecialchars( $attrValue ) . '"';
3899 if ( $content === null ) {
3900 $output = "<$name$attrText/>";
3902 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3903 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3907 $output = "<$name$attrText>$content$close";
3911 if ( $markerType === 'none' ) {
3913 } elseif ( $markerType === 'nowiki' ) {
3914 $this->mStripState
->addNoWiki( $marker, $output );
3915 } elseif ( $markerType === 'general' ) {
3916 $this->mStripState
->addGeneral( $marker, $output );
3918 throw new MWException( __METHOD__
. ': invalid marker type' );
3924 * Increment an include size counter
3926 * @param string $type The type of expansion
3927 * @param int $size The size of the text
3928 * @return bool False if this inclusion would take it over the maximum, true otherwise
3930 public function incrementIncludeSize( $type, $size ) {
3931 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3934 $this->mIncludeSizes
[$type] +
= $size;
3940 * Increment the expensive function count
3942 * @return bool False if the limit has been exceeded
3944 public function incrementExpensiveFunctionCount() {
3945 $this->mExpensiveFunctionCount++
;
3946 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3950 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3951 * Fills $this->mDoubleUnderscores, returns the modified text
3953 * @param string $text
3957 public function doDoubleUnderscore( $text ) {
3958 # The position of __TOC__ needs to be recorded
3959 $mw = MagicWord
::get( 'toc' );
3960 if ( $mw->match( $text ) ) {
3961 $this->mShowToc
= true;
3962 $this->mForceTocPosition
= true;
3964 # Set a placeholder. At the end we'll fill it in with the TOC.
3965 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
3967 # Only keep the first one.
3968 $text = $mw->replace( '', $text );
3971 # Now match and remove the rest of them
3972 $mwa = MagicWord
::getDoubleUnderscoreArray();
3973 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3975 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3976 $this->mOutput
->mNoGallery
= true;
3978 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3979 $this->mShowToc
= false;
3981 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
3982 && $this->mTitle
->getNamespace() == NS_CATEGORY
3984 $this->addTrackingCategory( 'hidden-category-category' );
3986 # (T10068) Allow control over whether robots index a page.
3987 # __INDEX__ always overrides __NOINDEX__, see T16899
3988 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3989 $this->mOutput
->setIndexPolicy( 'noindex' );
3990 $this->addTrackingCategory( 'noindex-category' );
3992 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3993 $this->mOutput
->setIndexPolicy( 'index' );
3994 $this->addTrackingCategory( 'index-category' );
3997 # Cache all double underscores in the database
3998 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3999 $this->mOutput
->setProperty( $key, '' );
4006 * @see ParserOutput::addTrackingCategory()
4007 * @param string $msg Message key
4008 * @return bool Whether the addition was successful
4010 public function addTrackingCategory( $msg ) {
4011 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4015 * This function accomplishes several tasks:
4016 * 1) Auto-number headings if that option is enabled
4017 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4018 * 3) Add a Table of contents on the top for users who have enabled the option
4019 * 4) Auto-anchor headings
4021 * It loops through all headlines, collects the necessary data, then splits up the
4022 * string and re-inserts the newly formatted headlines.
4024 * @param string $text
4025 * @param string $origText Original, untouched wikitext
4026 * @param bool $isMain
4027 * @return mixed|string
4030 public function formatHeadings( $text, $origText, $isMain = true ) {
4031 global $wgMaxTocLevel;
4033 # Inhibit editsection links if requested in the page
4034 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4035 $maybeShowEditLink = $showEditLink = false;
4037 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4038 $showEditLink = $this->mOptions
->getEditSection();
4040 if ( $showEditLink ) {
4041 $this->mOutput
->setEditSectionTokens( true );
4044 # Get all headlines for numbering them and adding funky stuff like [edit]
4045 # links - this is for later, but we need the number of headlines right now
4047 $numMatches = preg_match_all(
4048 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4053 # if there are fewer than 4 headlines in the article, do not show TOC
4054 # unless it's been explicitly enabled.
4055 $enoughToc = $this->mShowToc
&&
4056 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4058 # Allow user to stipulate that a page should have a "new section"
4059 # link added via __NEWSECTIONLINK__
4060 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4061 $this->mOutput
->setNewSection( true );
4064 # Allow user to remove the "new section"
4065 # link via __NONEWSECTIONLINK__
4066 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4067 $this->mOutput
->hideNewSection( true );
4070 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4071 # override above conditions and always show TOC above first header
4072 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4073 $this->mShowToc
= true;
4081 # Ugh .. the TOC should have neat indentation levels which can be
4082 # passed to the skin functions. These are determined here
4086 $sublevelCount = [];
4092 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4093 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4094 $oldType = $this->mOutputType
;
4095 $this->setOutputType( self
::OT_WIKI
);
4096 $frame = $this->getPreprocessor()->newFrame();
4097 $root = $this->preprocessToDom( $origText );
4098 $node = $root->getFirstChild();
4103 $headlines = $numMatches !== false ?
$matches[3] : [];
4105 foreach ( $headlines as $headline ) {
4106 $isTemplate = false;
4108 $sectionIndex = false;
4110 $markerMatches = [];
4111 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4112 $serial = $markerMatches[1];
4113 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4114 $isTemplate = ( $titleText != $baseTitleText );
4115 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4119 $prevlevel = $level;
4121 $level = $matches[1][$headlineCount];
4123 if ( $level > $prevlevel ) {
4124 # Increase TOC level
4126 $sublevelCount[$toclevel] = 0;
4127 if ( $toclevel < $wgMaxTocLevel ) {
4128 $prevtoclevel = $toclevel;
4129 $toc .= Linker
::tocIndent();
4132 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4133 # Decrease TOC level, find level to jump to
4135 for ( $i = $toclevel; $i > 0; $i-- ) {
4136 if ( $levelCount[$i] == $level ) {
4137 # Found last matching level
4140 } elseif ( $levelCount[$i] < $level ) {
4141 # Found first matching level below current level
4149 if ( $toclevel < $wgMaxTocLevel ) {
4150 if ( $prevtoclevel < $wgMaxTocLevel ) {
4151 # Unindent only if the previous toc level was shown :p
4152 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4153 $prevtoclevel = $toclevel;
4155 $toc .= Linker
::tocLineEnd();
4159 # No change in level, end TOC line
4160 if ( $toclevel < $wgMaxTocLevel ) {
4161 $toc .= Linker
::tocLineEnd();
4165 $levelCount[$toclevel] = $level;
4167 # count number of headlines for each level
4168 $sublevelCount[$toclevel]++
;
4170 for ( $i = 1; $i <= $toclevel; $i++
) {
4171 if ( !empty( $sublevelCount[$i] ) ) {
4175 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4180 # The safe header is a version of the header text safe to use for links
4182 # Remove link placeholders by the link text.
4183 # <!--LINK number-->
4185 # link text with suffix
4186 # Do this before unstrip since link text can contain strip markers
4187 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4189 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4190 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4192 # Strip out HTML (first regex removes any tag not allowed)
4194 # * <sup> and <sub> (T10393)
4198 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4199 # * <s> and <strike> (T35715)
4200 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4201 # to allow setting directionality in toc items.
4202 $tocline = preg_replace(
4204 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4205 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4211 # Strip '<span></span>', which is the result from the above if
4212 # <span id="foo"></span> is used to produce an additional anchor
4214 $tocline = str_replace( '<span></span>', '', $tocline );
4216 $tocline = trim( $tocline );
4218 # For the anchor, strip out HTML-y stuff period
4219 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4220 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4222 # Save headline for section edit hint before it's escaped
4223 $headlineHint = $safeHeadline;
4225 # Decode HTML entities
4226 $safeHeadline = Sanitizer
::decodeCharReferences( $safeHeadline );
4228 $safeHeadline = self
::normalizeSectionName( $safeHeadline );
4230 $fallbackHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_FALLBACK
);
4231 $linkAnchor = Sanitizer
::escapeIdForLink( $safeHeadline );
4232 $safeHeadline = Sanitizer
::escapeIdForAttribute( $safeHeadline, Sanitizer
::ID_PRIMARY
);
4233 if ( $fallbackHeadline === $safeHeadline ) {
4234 # No reason to have both (in fact, we can't)
4235 $fallbackHeadline = false;
4238 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4239 # @todo FIXME: We may be changing them depending on the current locale.
4240 $arrayKey = strtolower( $safeHeadline );
4241 if ( $fallbackHeadline === false ) {
4242 $fallbackArrayKey = false;
4244 $fallbackArrayKey = strtolower( $fallbackHeadline );
4247 # Create the anchor for linking from the TOC to the section
4248 $anchor = $safeHeadline;
4249 $fallbackAnchor = $fallbackHeadline;
4250 if ( isset( $refers[$arrayKey] ) ) {
4251 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4252 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4254 $linkAnchor .= "_$i";
4255 $refers["${arrayKey}_$i"] = true;
4257 $refers[$arrayKey] = true;
4259 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4260 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4261 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++
$i );
4262 $fallbackAnchor .= "_$i";
4263 $refers["${fallbackArrayKey}_$i"] = true;
4265 $refers[$fallbackArrayKey] = true;
4268 # Don't number the heading if it is the only one (looks silly)
4269 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4270 # the two are different if the line contains a link
4271 $headline = Html
::element(
4273 [ 'class' => 'mw-headline-number' ],
4275 ) . ' ' . $headline;
4278 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4279 $toc .= Linker
::tocLine( $linkAnchor, $tocline,
4280 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4283 # Add the section to the section tree
4284 # Find the DOM node for this header
4285 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4286 while ( $node && !$noOffset ) {
4287 if ( $node->getName() === 'h' ) {
4288 $bits = $node->splitHeading();
4289 if ( $bits['i'] == $sectionIndex ) {
4293 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4294 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4295 $node = $node->getNextSibling();
4298 'toclevel' => $toclevel,
4301 'number' => $numbering,
4302 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4303 'fromtitle' => $titleText,
4304 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4305 'anchor' => $anchor,
4308 # give headline the correct <h#> tag
4309 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4310 // Output edit section links as markers with styles that can be customized by skins
4311 if ( $isTemplate ) {
4312 # Put a T flag in the section identifier, to indicate to extractSections()
4313 # that sections inside <includeonly> should be counted.
4314 $editsectionPage = $titleText;
4315 $editsectionSection = "T-$sectionIndex";
4316 $editsectionContent = null;
4318 $editsectionPage = $this->mTitle
->getPrefixedText();
4319 $editsectionSection = $sectionIndex;
4320 $editsectionContent = $headlineHint;
4322 // We use a bit of pesudo-xml for editsection markers. The
4323 // language converter is run later on. Using a UNIQ style marker
4324 // leads to the converter screwing up the tokens when it
4325 // converts stuff. And trying to insert strip tags fails too. At
4326 // this point all real inputted tags have already been escaped,
4327 // so we don't have to worry about a user trying to input one of
4328 // these markers directly. We use a page and section attribute
4329 // to stop the language converter from converting these
4330 // important bits of data, but put the headline hint inside a
4331 // content block because the language converter is supposed to
4332 // be able to convert that piece of data.
4333 // Gets replaced with html in ParserOutput::getText
4334 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4335 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4336 if ( $editsectionContent !== null ) {
4337 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4344 $head[$headlineCount] = Linker
::makeHeadline( $level,
4345 $matches['attrib'][$headlineCount], $anchor, $headline,
4346 $editlink, $fallbackAnchor );
4351 $this->setOutputType( $oldType );
4353 # Never ever show TOC if no headers
4354 if ( $numVisible < 1 ) {
4359 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4360 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4362 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4363 $this->mOutput
->setTOCHTML( $toc );
4364 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4368 $this->mOutput
->setSections( $tocraw );
4371 # split up and insert constructed headlines
4372 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4375 // build an array of document sections
4377 foreach ( $blocks as $block ) {
4378 // $head is zero-based, sections aren't.
4379 if ( empty( $head[$i - 1] ) ) {
4380 $sections[$i] = $block;
4382 $sections[$i] = $head[$i - 1] . $block;
4386 * Send a hook, one per section.
4387 * The idea here is to be able to make section-level DIVs, but to do so in a
4388 * lower-impact, more correct way than r50769
4391 * $section : the section number
4392 * &$sectionContent : ref to the content of the section
4393 * $showEditLinks : boolean describing whether this section has an edit link
4395 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $showEditLink ] );
4400 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4401 // append the TOC at the beginning
4402 // Top anchor now in skin
4403 $sections[0] = $sections[0] . $toc . "\n";
4406 $full .= implode( '', $sections );
4408 if ( $this->mForceTocPosition
) {
4409 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4416 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4417 * conversion, substituting signatures, {{subst:}} templates, etc.
4419 * @param string $text The text to transform
4420 * @param Title $title The Title object for the current article
4421 * @param User $user The User object describing the current user
4422 * @param ParserOptions $options Parsing options
4423 * @param bool $clearState Whether to clear the parser state first
4424 * @return string The altered wiki markup
4426 public function preSaveTransform( $text, Title
$title, User
$user,
4427 ParserOptions
$options, $clearState = true
4429 if ( $clearState ) {
4430 $magicScopeVariable = $this->lock();
4432 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4433 $this->setUser( $user );
4435 // Strip U+0000 NULL (T159174)
4436 $text = str_replace( "\000", '', $text );
4438 // We still normalize line endings for backwards-compatibility
4439 // with other code that just calls PST, but this should already
4440 // be handled in TextContent subclasses
4441 $text = TextContent
::normalizeLineEndings( $text );
4443 if ( $options->getPreSaveTransform() ) {
4444 $text = $this->pstPass2( $text, $user );
4446 $text = $this->mStripState
->unstripBoth( $text );
4448 $this->setUser( null ); # Reset
4454 * Pre-save transform helper function
4456 * @param string $text
4461 private function pstPass2( $text, $user ) {
4464 # Note: This is the timestamp saved as hardcoded wikitext to
4465 # the database, we use $wgContLang here in order to give
4466 # everyone the same signature and use the default one rather
4467 # than the one selected in each user's preferences.
4469 $ts = $this->mOptions
->getTimestamp();
4470 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4471 $ts = $timestamp->format( 'YmdHis' );
4472 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4474 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4476 # Variable replacement
4477 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4478 $text = $this->replaceVariables( $text );
4480 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4481 # which may corrupt this parser instance via its wfMessage()->text() call-
4484 if ( strpos( $text, '~~~' ) !== false ) {
4485 $sigText = $this->getUserSig( $user );
4486 $text = strtr( $text, [
4488 '~~~~' => "$sigText $d",
4491 # The main two signature forms used above are time-sensitive
4492 $this->mOutput
->setFlag( 'user-signature' );
4495 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4496 $tc = '[' . Title
::legalChars() . ']';
4497 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4499 // [[ns:page (context)|]]
4500 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4501 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4502 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4503 // [[ns:page (context), context|]] (using either single or double-width comma)
4504 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4505 // [[|page]] (reverse pipe trick: add context from page title)
4506 $p2 = "/\[\[\\|($tc+)]]/";
4508 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4509 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4510 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4511 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4513 $t = $this->mTitle
->getText();
4515 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4516 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4517 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4518 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4520 # if there's no context, don't bother duplicating the title
4521 $text = preg_replace( $p2, '[[\\1]]', $text );
4528 * Fetch the user's signature text, if any, and normalize to
4529 * validated, ready-to-insert wikitext.
4530 * If you have pre-fetched the nickname or the fancySig option, you can
4531 * specify them here to save a database query.
4532 * Do not reuse this parser instance after calling getUserSig(),
4533 * as it may have changed if it's the $wgParser.
4535 * @param User &$user
4536 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4537 * @param bool|null $fancySig whether the nicknname is the complete signature
4538 * or null to use default value
4541 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4542 global $wgMaxSigChars;
4544 $username = $user->getName();
4546 # If not given, retrieve from the user object.
4547 if ( $nickname === false ) {
4548 $nickname = $user->getOption( 'nickname' );
4551 if ( is_null( $fancySig ) ) {
4552 $fancySig = $user->getBoolOption( 'fancysig' );
4555 $nickname = $nickname == null ?
$username : $nickname;
4557 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4558 $nickname = $username;
4559 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4560 } elseif ( $fancySig !== false ) {
4561 # Sig. might contain markup; validate this
4562 if ( $this->validateSig( $nickname ) !== false ) {
4563 # Validated; clean up (if needed) and return it
4564 return $this->cleanSig( $nickname, true );
4566 # Failed to validate; fall back to the default
4567 $nickname = $username;
4568 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4572 # Make sure nickname doesnt get a sig in a sig
4573 $nickname = self
::cleanSigInSig( $nickname );
4575 # If we're still here, make it a link to the user page
4576 $userText = wfEscapeWikiText( $username );
4577 $nickText = wfEscapeWikiText( $nickname );
4578 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4580 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4581 ->title( $this->getTitle() )->text();
4585 * Check that the user's signature contains no bad XML
4587 * @param string $text
4588 * @return string|bool An expanded string, or false if invalid.
4590 public function validateSig( $text ) {
4591 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4595 * Clean up signature text
4597 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4598 * 2) Substitute all transclusions
4600 * @param string $text
4601 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4602 * @return string Signature text
4604 public function cleanSig( $text, $parsing = false ) {
4607 $magicScopeVariable = $this->lock();
4608 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4611 # Option to disable this feature
4612 if ( !$this->mOptions
->getCleanSignatures() ) {
4616 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4617 # => Move this logic to braceSubstitution()
4618 $substWord = MagicWord
::get( 'subst' );
4619 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4620 $substText = '{{' . $substWord->getSynonym( 0 );
4622 $text = preg_replace( $substRegex, $substText, $text );
4623 $text = self
::cleanSigInSig( $text );
4624 $dom = $this->preprocessToDom( $text );
4625 $frame = $this->getPreprocessor()->newFrame();
4626 $text = $frame->expand( $dom );
4629 $text = $this->mStripState
->unstripBoth( $text );
4636 * Strip 3, 4 or 5 tildes out of signatures.
4638 * @param string $text
4639 * @return string Signature text with /~{3,5}/ removed
4641 public static function cleanSigInSig( $text ) {
4642 $text = preg_replace( '/~{3,5}/', '', $text );
4647 * Set up some variables which are usually set up in parse()
4648 * so that an external function can call some class members with confidence
4650 * @param Title|null $title
4651 * @param ParserOptions $options
4652 * @param int $outputType
4653 * @param bool $clearState
4655 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4656 $outputType, $clearState = true
4658 $this->startParse( $title, $options, $outputType, $clearState );
4662 * @param Title|null $title
4663 * @param ParserOptions $options
4664 * @param int $outputType
4665 * @param bool $clearState
4667 private function startParse( Title
$title = null, ParserOptions
$options,
4668 $outputType, $clearState = true
4670 $this->setTitle( $title );
4671 $this->mOptions
= $options;
4672 $this->setOutputType( $outputType );
4673 if ( $clearState ) {
4674 $this->clearState();
4679 * Wrapper for preprocess()
4681 * @param string $text The text to preprocess
4682 * @param ParserOptions $options Options
4683 * @param Title|null $title Title object or null to use $wgTitle
4686 public function transformMsg( $text, $options, $title = null ) {
4687 static $executing = false;
4689 # Guard against infinite recursion
4700 $text = $this->preprocess( $text, $title, $options );
4707 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4708 * The callback should have the following form:
4709 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4711 * Transform and return $text. Use $parser for any required context, e.g. use
4712 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4714 * Hooks may return extended information by returning an array, of which the
4715 * first numbered element (index 0) must be the return string, and all other
4716 * entries are extracted into local variables within an internal function
4717 * in the Parser class.
4719 * This interface (introduced r61913) appears to be undocumented, but
4720 * 'markerType' is used by some core tag hooks to override which strip
4721 * array their results are placed in. **Use great caution if attempting
4722 * this interface, as it is not documented and injudicious use could smash
4723 * private variables.**
4725 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4726 * @param callable $callback The callback function (and object) to use for the tag
4727 * @throws MWException
4728 * @return callable|null The old value of the mTagHooks array associated with the hook
4730 public function setHook( $tag, callable
$callback ) {
4731 $tag = strtolower( $tag );
4732 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4733 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4735 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4736 $this->mTagHooks
[$tag] = $callback;
4737 if ( !in_array( $tag, $this->mStripList
) ) {
4738 $this->mStripList
[] = $tag;
4745 * As setHook(), but letting the contents be parsed.
4747 * Transparent tag hooks are like regular XML-style tag hooks, except they
4748 * operate late in the transformation sequence, on HTML instead of wikitext.
4750 * This is probably obsoleted by things dealing with parser frames?
4751 * The only extension currently using it is geoserver.
4754 * @todo better document or deprecate this
4756 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4757 * @param callable $callback The callback function (and object) to use for the tag
4758 * @throws MWException
4759 * @return callable|null The old value of the mTagHooks array associated with the hook
4761 public function setTransparentTagHook( $tag, callable
$callback ) {
4762 $tag = strtolower( $tag );
4763 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4764 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4766 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4767 $this->mTransparentTagHooks
[$tag] = $callback;
4773 * Remove all tag hooks
4775 public function clearTagHooks() {
4776 $this->mTagHooks
= [];
4777 $this->mFunctionTagHooks
= [];
4778 $this->mStripList
= $this->mDefaultStripList
;
4782 * Create a function, e.g. {{sum:1|2|3}}
4783 * The callback function should have the form:
4784 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4786 * Or with Parser::SFH_OBJECT_ARGS:
4787 * function myParserFunction( $parser, $frame, $args ) { ... }
4789 * The callback may either return the text result of the function, or an array with the text
4790 * in element 0, and a number of flags in the other elements. The names of the flags are
4791 * specified in the keys. Valid flags are:
4792 * found The text returned is valid, stop processing the template. This
4794 * nowiki Wiki markup in the return value should be escaped
4795 * isHTML The returned text is HTML, armour it against wikitext transformation
4797 * @param string $id The magic word ID
4798 * @param callable $callback The callback function (and object) to use
4799 * @param int $flags A combination of the following flags:
4800 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4802 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4803 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4804 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4805 * the arguments, and to control the way they are expanded.
4807 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4808 * arguments, for instance:
4809 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4811 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4812 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4813 * working if/when this is changed.
4815 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4818 * Please read the documentation in includes/parser/Preprocessor.php for more information
4819 * about the methods available in PPFrame and PPNode.
4821 * @throws MWException
4822 * @return string|callable The old callback function for this name, if any
4824 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4827 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4828 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4830 # Add to function cache
4831 $mw = MagicWord
::get( $id );
4833 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4836 $synonyms = $mw->getSynonyms();
4837 $sensitive = intval( $mw->isCaseSensitive() );
4839 foreach ( $synonyms as $syn ) {
4841 if ( !$sensitive ) {
4842 $syn = $wgContLang->lc( $syn );
4845 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4848 # Remove trailing colon
4849 if ( substr( $syn, -1, 1 ) === ':' ) {
4850 $syn = substr( $syn, 0, -1 );
4852 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4858 * Get all registered function hook identifiers
4862 public function getFunctionHooks() {
4863 return array_keys( $this->mFunctionHooks
);
4867 * Create a tag function, e.g. "<test>some stuff</test>".
4868 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4869 * Unlike parser functions, their content is not preprocessed.
4870 * @param string $tag
4871 * @param callable $callback
4873 * @throws MWException
4876 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4877 $tag = strtolower( $tag );
4878 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4879 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4881 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4882 $this->mFunctionTagHooks
[$tag] : null;
4883 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4885 if ( !in_array( $tag, $this->mStripList
) ) {
4886 $this->mStripList
[] = $tag;
4893 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4894 * Placeholders created in Linker::link()
4896 * @param string &$text
4897 * @param int $options
4899 public function replaceLinkHolders( &$text, $options = 0 ) {
4900 $this->mLinkHolders
->replace( $text );
4904 * Replace "<!--LINK-->" link placeholders with plain text of links
4905 * (not HTML-formatted).
4907 * @param string $text
4910 public function replaceLinkHoldersText( $text ) {
4911 return $this->mLinkHolders
->replaceText( $text );
4915 * Renders an image gallery from a text with one line per image.
4916 * text labels may be given by using |-style alternative text. E.g.
4917 * Image:one.jpg|The number "1"
4918 * Image:tree.jpg|A tree
4919 * given as text will return the HTML of a gallery with two images,
4920 * labeled 'The number "1"' and
4923 * @param string $text
4924 * @param array $params
4925 * @return string HTML
4927 public function renderImageGallery( $text, $params ) {
4929 if ( isset( $params['mode'] ) ) {
4930 $mode = $params['mode'];
4934 $ig = ImageGalleryBase
::factory( $mode );
4935 } catch ( Exception
$e ) {
4936 // If invalid type set, fallback to default.
4937 $ig = ImageGalleryBase
::factory( false );
4940 $ig->setContextTitle( $this->mTitle
);
4941 $ig->setShowBytes( false );
4942 $ig->setShowDimensions( false );
4943 $ig->setShowFilename( false );
4944 $ig->setParser( $this );
4945 $ig->setHideBadImages();
4946 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
4948 if ( isset( $params['showfilename'] ) ) {
4949 $ig->setShowFilename( true );
4951 $ig->setShowFilename( false );
4953 if ( isset( $params['caption'] ) ) {
4954 $caption = $params['caption'];
4955 $caption = htmlspecialchars( $caption );
4956 $caption = $this->replaceInternalLinks( $caption );
4957 $ig->setCaptionHtml( $caption );
4959 if ( isset( $params['perrow'] ) ) {
4960 $ig->setPerRow( $params['perrow'] );
4962 if ( isset( $params['widths'] ) ) {
4963 $ig->setWidths( $params['widths'] );
4965 if ( isset( $params['heights'] ) ) {
4966 $ig->setHeights( $params['heights'] );
4968 $ig->setAdditionalOptions( $params );
4970 // Avoid PHP 7.1 warning from passing $this by reference
4972 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
4974 $lines = StringUtils
::explode( "\n", $text );
4975 foreach ( $lines as $line ) {
4976 # match lines like these:
4977 # Image:someimage.jpg|This is some image
4979 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4981 if ( count( $matches ) == 0 ) {
4985 if ( strpos( $matches[0], '%' ) !== false ) {
4986 $matches[1] = rawurldecode( $matches[1] );
4988 $title = Title
::newFromText( $matches[1], NS_FILE
);
4989 if ( is_null( $title ) ) {
4990 # Bogus title. Ignore these so we don't bomb out later.
4994 # We need to get what handler the file uses, to figure out parameters.
4995 # Note, a hook can overide the file name, and chose an entirely different
4996 # file (which potentially could be of a different type and have different handler).
4999 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5000 [ $this, $title, &$options, &$descQuery ] );
5001 # Don't register it now, as TraditionalImageGallery does that later.
5002 $file = $this->fetchFileNoRegister( $title, $options );
5003 $handler = $file ?
$file->getHandler() : false;
5006 'img_alt' => 'gallery-internal-alt',
5007 'img_link' => 'gallery-internal-link',
5010 $paramMap = $paramMap +
$handler->getParamMap();
5011 // We don't want people to specify per-image widths.
5012 // Additionally the width parameter would need special casing anyhow.
5013 unset( $paramMap['img_width'] );
5016 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5021 $handlerOptions = [];
5022 if ( isset( $matches[3] ) ) {
5023 // look for an |alt= definition while trying not to break existing
5024 // captions with multiple pipes (|) in it, until a more sensible grammar
5025 // is defined for images in galleries
5027 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5028 // splitting on '|' is a bit odd, and different from makeImage.
5029 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5030 // Protect LanguageConverter markup
5031 $parameterMatches = StringUtils
::delimiterExplode(
5032 '-{', '}-', '|', $matches[3], true /* nested */
5035 foreach ( $parameterMatches as $parameterMatch ) {
5036 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5038 $paramName = $paramMap[$magicName];
5040 switch ( $paramName ) {
5041 case 'gallery-internal-alt':
5042 $alt = $this->stripAltText( $match, false );
5044 case 'gallery-internal-link':
5045 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5046 $chars = self
::EXT_LINK_URL_CLASS
;
5047 $addr = self
::EXT_LINK_ADDR
;
5048 $prots = $this->mUrlProtocols
;
5049 // check to see if link matches an absolute url, if not then it must be a wiki link.
5050 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5051 // Result of LanguageConverter::markNoConversion
5052 // invoked on an external link.
5053 $linkValue = substr( $linkValue, 4, -2 );
5055 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5057 $this->mOutput
->addExternalLink( $link );
5059 $localLinkTitle = Title
::newFromText( $linkValue );
5060 if ( $localLinkTitle !== null ) {
5061 $this->mOutput
->addLink( $localLinkTitle );
5062 $link = $localLinkTitle->getLinkURL();
5067 // Must be a handler specific parameter.
5068 if ( $handler->validateParam( $paramName, $match ) ) {
5069 $handlerOptions[$paramName] = $match;
5071 // Guess not, consider it as caption.
5072 wfDebug( "$parameterMatch failed parameter validation\n" );
5073 $label = '|' . $parameterMatch;
5079 $label = '|' . $parameterMatch;
5083 $label = substr( $label, 1 );
5086 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5088 $html = $ig->toHTML();
5089 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5094 * @param MediaHandler $handler
5097 public function getImageParams( $handler ) {
5099 $handlerClass = get_class( $handler );
5103 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5104 # Initialise static lists
5105 static $internalParamNames = [
5106 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5107 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5108 'bottom', 'text-bottom' ],
5109 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5110 'upright', 'border', 'link', 'alt', 'class' ],
5112 static $internalParamMap;
5113 if ( !$internalParamMap ) {
5114 $internalParamMap = [];
5115 foreach ( $internalParamNames as $type => $names ) {
5116 foreach ( $names as $name ) {
5117 // For grep: img_left, img_right, img_center, img_none,
5118 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5119 // img_bottom, img_text_bottom,
5120 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5121 // img_border, img_link, img_alt, img_class
5122 $magicName = str_replace( '-', '_', "img_$name" );
5123 $internalParamMap[$magicName] = [ $type, $name ];
5128 # Add handler params
5129 $paramMap = $internalParamMap;
5131 $handlerParamMap = $handler->getParamMap();
5132 foreach ( $handlerParamMap as $magic => $paramName ) {
5133 $paramMap[$magic] = [ 'handler', $paramName ];
5136 $this->mImageParams
[$handlerClass] = $paramMap;
5137 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5139 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5143 * Parse image options text and use it to make an image
5145 * @param Title $title
5146 * @param string $options
5147 * @param LinkHolderArray|bool $holders
5148 * @return string HTML
5150 public function makeImage( $title, $options, $holders = false ) {
5151 # Check if the options text is of the form "options|alt text"
5153 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5154 # * left no resizing, just left align. label is used for alt= only
5155 # * right same, but right aligned
5156 # * none same, but not aligned
5157 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5158 # * center center the image
5159 # * frame Keep original image size, no magnify-button.
5160 # * framed Same as "frame"
5161 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5162 # * upright reduce width for upright images, rounded to full __0 px
5163 # * border draw a 1px border around the image
5164 # * alt Text for HTML alt attribute (defaults to empty)
5165 # * class Set a class for img node
5166 # * link Set the target of the image link. Can be external, interwiki, or local
5167 # vertical-align values (no % or length right now):
5177 # Protect LanguageConverter markup when splitting into parts
5178 $parts = StringUtils
::delimiterExplode(
5179 '-{', '}-', '|', $options, true /* allow nesting */
5182 # Give extensions a chance to select the file revision for us
5185 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5186 [ $this, $title, &$options, &$descQuery ] );
5187 # Fetch and register the file (file title may be different via hooks)
5188 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5191 $handler = $file ?
$file->getHandler() : false;
5193 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5196 $this->addTrackingCategory( 'broken-file-category' );
5199 # Process the input parameters
5201 $params = [ 'frame' => [], 'handler' => [],
5202 'horizAlign' => [], 'vertAlign' => [] ];
5203 $seenformat = false;
5204 foreach ( $parts as $part ) {
5205 $part = trim( $part );
5206 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5208 if ( isset( $paramMap[$magicName] ) ) {
5209 list( $type, $paramName ) = $paramMap[$magicName];
5211 # Special case; width and height come in one variable together
5212 if ( $type === 'handler' && $paramName === 'width' ) {
5213 $parsedWidthParam = $this->parseWidthParam( $value );
5214 if ( isset( $parsedWidthParam['width'] ) ) {
5215 $width = $parsedWidthParam['width'];
5216 if ( $handler->validateParam( 'width', $width ) ) {
5217 $params[$type]['width'] = $width;
5221 if ( isset( $parsedWidthParam['height'] ) ) {
5222 $height = $parsedWidthParam['height'];
5223 if ( $handler->validateParam( 'height', $height ) ) {
5224 $params[$type]['height'] = $height;
5228 # else no validation -- T15436
5230 if ( $type === 'handler' ) {
5231 # Validate handler parameter
5232 $validated = $handler->validateParam( $paramName, $value );
5234 # Validate internal parameters
5235 switch ( $paramName ) {
5239 # @todo FIXME: Possibly check validity here for
5240 # manualthumb? downstream behavior seems odd with
5241 # missing manual thumbs.
5243 $value = $this->stripAltText( $value, $holders );
5246 $chars = self
::EXT_LINK_URL_CLASS
;
5247 $addr = self
::EXT_LINK_ADDR
;
5248 $prots = $this->mUrlProtocols
;
5249 if ( $value === '' ) {
5250 $paramName = 'no-link';
5253 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5254 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5255 $paramName = 'link-url';
5256 $this->mOutput
->addExternalLink( $value );
5257 if ( $this->mOptions
->getExternalLinkTarget() ) {
5258 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5263 $linkTitle = Title
::newFromText( $value );
5265 $paramName = 'link-title';
5266 $value = $linkTitle;
5267 $this->mOutput
->addLink( $linkTitle );
5275 // use first appearing option, discard others.
5276 $validated = !$seenformat;
5280 # Most other things appear to be empty or numeric...
5281 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5286 $params[$type][$paramName] = $value;
5290 if ( !$validated ) {
5295 # Process alignment parameters
5296 if ( $params['horizAlign'] ) {
5297 $params['frame']['align'] = key( $params['horizAlign'] );
5299 if ( $params['vertAlign'] ) {
5300 $params['frame']['valign'] = key( $params['vertAlign'] );
5303 $params['frame']['caption'] = $caption;
5305 # Will the image be presented in a frame, with the caption below?
5306 $imageIsFramed = isset( $params['frame']['frame'] )
5307 ||
isset( $params['frame']['framed'] )
5308 ||
isset( $params['frame']['thumbnail'] )
5309 ||
isset( $params['frame']['manualthumb'] );
5311 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5312 # came to also set the caption, ordinary text after the image -- which
5313 # makes no sense, because that just repeats the text multiple times in
5314 # screen readers. It *also* came to set the title attribute.
5315 # Now that we have an alt attribute, we should not set the alt text to
5316 # equal the caption: that's worse than useless, it just repeats the
5317 # text. This is the framed/thumbnail case. If there's no caption, we
5318 # use the unnamed parameter for alt text as well, just for the time be-
5319 # ing, if the unnamed param is set and the alt param is not.
5320 # For the future, we need to figure out if we want to tweak this more,
5321 # e.g., introducing a title= parameter for the title; ignoring the un-
5322 # named parameter entirely for images without a caption; adding an ex-
5323 # plicit caption= parameter and preserving the old magic unnamed para-
5325 if ( $imageIsFramed ) { # Framed image
5326 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5327 # No caption or alt text, add the filename as the alt text so
5328 # that screen readers at least get some description of the image
5329 $params['frame']['alt'] = $title->getText();
5331 # Do not set $params['frame']['title'] because tooltips don't make sense
5333 } else { # Inline image
5334 if ( !isset( $params['frame']['alt'] ) ) {
5335 # No alt text, use the "caption" for the alt text
5336 if ( $caption !== '' ) {
5337 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5339 # No caption, fall back to using the filename for the
5341 $params['frame']['alt'] = $title->getText();
5344 # Use the "caption" for the tooltip text
5345 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5348 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5350 # Linker does the rest
5351 $time = isset( $options['time'] ) ?
$options['time'] : false;
5352 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5353 $time, $descQuery, $this->mOptions
->getThumbSize() );
5355 # Give the handler a chance to modify the parser object
5357 $handler->parserTransformHook( $this, $file );
5364 * @param string $caption
5365 * @param LinkHolderArray|bool $holders
5366 * @return mixed|string
5368 protected function stripAltText( $caption, $holders ) {
5369 # Strip bad stuff out of the title (tooltip). We can't just use
5370 # replaceLinkHoldersText() here, because if this function is called
5371 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5373 $tooltip = $holders->replaceText( $caption );
5375 $tooltip = $this->replaceLinkHoldersText( $caption );
5378 # make sure there are no placeholders in thumbnail attributes
5379 # that are later expanded to html- so expand them now and
5381 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5382 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5388 * Set a flag in the output object indicating that the content is dynamic and
5389 * shouldn't be cached.
5390 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5392 public function disableCache() {
5393 wfDebug( "Parser output marked as uncacheable.\n" );
5394 if ( !$this->mOutput
) {
5395 throw new MWException( __METHOD__
.
5396 " can only be called when actually parsing something" );
5398 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5402 * Callback from the Sanitizer for expanding items found in HTML attribute
5403 * values, so they can be safely tested and escaped.
5405 * @param string &$text
5406 * @param bool|PPFrame $frame
5409 public function attributeStripCallback( &$text, $frame = false ) {
5410 $text = $this->replaceVariables( $text, $frame );
5411 $text = $this->mStripState
->unstripBoth( $text );
5420 public function getTags() {
5422 array_keys( $this->mTransparentTagHooks
),
5423 array_keys( $this->mTagHooks
),
5424 array_keys( $this->mFunctionTagHooks
)
5429 * Replace transparent tags in $text with the values given by the callbacks.
5431 * Transparent tag hooks are like regular XML-style tag hooks, except they
5432 * operate late in the transformation sequence, on HTML instead of wikitext.
5434 * @param string $text
5438 public function replaceTransparentTags( $text ) {
5440 $elements = array_keys( $this->mTransparentTagHooks
);
5441 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5444 foreach ( $matches as $marker => $data ) {
5445 list( $element, $content, $params, $tag ) = $data;
5446 $tagName = strtolower( $element );
5447 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5448 $output = call_user_func_array(
5449 $this->mTransparentTagHooks
[$tagName],
5450 [ $content, $params, $this ]
5455 $replacements[$marker] = $output;
5457 return strtr( $text, $replacements );
5461 * Break wikitext input into sections, and either pull or replace
5462 * some particular section's text.
5464 * External callers should use the getSection and replaceSection methods.
5466 * @param string $text Page wikitext
5467 * @param string|int $sectionId A section identifier string of the form:
5468 * "<flag1> - <flag2> - ... - <section number>"
5470 * Currently the only recognised flag is "T", which means the target section number
5471 * was derived during a template inclusion parse, in other words this is a template
5472 * section edit link. If no flags are given, it was an ordinary section edit link.
5473 * This flag is required to avoid a section numbering mismatch when a section is
5474 * enclosed by "<includeonly>" (T8563).
5476 * The section number 0 pulls the text before the first heading; other numbers will
5477 * pull the given section along with its lower-level subsections. If the section is
5478 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5480 * Section 0 is always considered to exist, even if it only contains the empty
5481 * string. If $text is the empty string and section 0 is replaced, $newText is
5484 * @param string $mode One of "get" or "replace"
5485 * @param string $newText Replacement text for section data.
5486 * @return string For "get", the extracted section text.
5487 * for "replace", the whole page with the section replaced.
5489 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5490 global $wgTitle; # not generally used but removes an ugly failure mode
5492 $magicScopeVariable = $this->lock();
5493 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5495 $frame = $this->getPreprocessor()->newFrame();
5497 # Process section extraction flags
5499 $sectionParts = explode( '-', $sectionId );
5500 $sectionIndex = array_pop( $sectionParts );
5501 foreach ( $sectionParts as $part ) {
5502 if ( $part === 'T' ) {
5503 $flags |
= self
::PTD_FOR_INCLUSION
;
5507 # Check for empty input
5508 if ( strval( $text ) === '' ) {
5509 # Only sections 0 and T-0 exist in an empty document
5510 if ( $sectionIndex == 0 ) {
5511 if ( $mode === 'get' ) {
5517 if ( $mode === 'get' ) {
5525 # Preprocess the text
5526 $root = $this->preprocessToDom( $text, $flags );
5528 # <h> nodes indicate section breaks
5529 # They can only occur at the top level, so we can find them by iterating the root's children
5530 $node = $root->getFirstChild();
5532 # Find the target section
5533 if ( $sectionIndex == 0 ) {
5534 # Section zero doesn't nest, level=big
5535 $targetLevel = 1000;
5538 if ( $node->getName() === 'h' ) {
5539 $bits = $node->splitHeading();
5540 if ( $bits['i'] == $sectionIndex ) {
5541 $targetLevel = $bits['level'];
5545 if ( $mode === 'replace' ) {
5546 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5548 $node = $node->getNextSibling();
5554 if ( $mode === 'get' ) {
5561 # Find the end of the section, including nested sections
5563 if ( $node->getName() === 'h' ) {
5564 $bits = $node->splitHeading();
5565 $curLevel = $bits['level'];
5566 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5570 if ( $mode === 'get' ) {
5571 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5573 $node = $node->getNextSibling();
5576 # Write out the remainder (in replace mode only)
5577 if ( $mode === 'replace' ) {
5578 # Output the replacement text
5579 # Add two newlines on -- trailing whitespace in $newText is conventionally
5580 # stripped by the editor, so we need both newlines to restore the paragraph gap
5581 # Only add trailing whitespace if there is newText
5582 if ( $newText != "" ) {
5583 $outText .= $newText . "\n\n";
5587 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5588 $node = $node->getNextSibling();
5592 if ( is_string( $outText ) ) {
5593 # Re-insert stripped tags
5594 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5601 * This function returns the text of a section, specified by a number ($section).
5602 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5603 * the first section before any such heading (section 0).
5605 * If a section contains subsections, these are also returned.
5607 * @param string $text Text to look in
5608 * @param string|int $sectionId Section identifier as a number or string
5609 * (e.g. 0, 1 or 'T-1').
5610 * @param string $defaultText Default to return if section is not found
5612 * @return string Text of the requested section
5614 public function getSection( $text, $sectionId, $defaultText = '' ) {
5615 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5619 * This function returns $oldtext after the content of the section
5620 * specified by $section has been replaced with $text. If the target
5621 * section does not exist, $oldtext is returned unchanged.
5623 * @param string $oldText Former text of the article
5624 * @param string|int $sectionId Section identifier as a number or string
5625 * (e.g. 0, 1 or 'T-1').
5626 * @param string $newText Replacing text
5628 * @return string Modified text
5630 public function replaceSection( $oldText, $sectionId, $newText ) {
5631 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5635 * Get the ID of the revision we are parsing
5639 public function getRevisionId() {
5640 return $this->mRevisionId
;
5644 * Get the revision object for $this->mRevisionId
5646 * @return Revision|null Either a Revision object or null
5647 * @since 1.23 (public since 1.23)
5649 public function getRevisionObject() {
5650 if ( !is_null( $this->mRevisionObject
) ) {
5651 return $this->mRevisionObject
;
5653 if ( is_null( $this->mRevisionId
) ) {
5657 $rev = call_user_func(
5658 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5661 # If the parse is for a new revision, then the callback should have
5662 # already been set to force the object and should match mRevisionId.
5663 # If not, try to fetch by mRevisionId for sanity.
5664 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5665 $rev = Revision
::newFromId( $this->mRevisionId
);
5668 $this->mRevisionObject
= $rev;
5670 return $this->mRevisionObject
;
5674 * Get the timestamp associated with the current revision, adjusted for
5675 * the default server-local timestamp
5678 public function getRevisionTimestamp() {
5679 if ( is_null( $this->mRevisionTimestamp
) ) {
5682 $revObject = $this->getRevisionObject();
5683 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5685 # The cryptic '' timezone parameter tells to use the site-default
5686 # timezone offset instead of the user settings.
5687 # Since this value will be saved into the parser cache, served
5688 # to other users, and potentially even used inside links and such,
5689 # it needs to be consistent for all visitors.
5690 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5693 return $this->mRevisionTimestamp
;
5697 * Get the name of the user that edited the last revision
5699 * @return string User name
5701 public function getRevisionUser() {
5702 if ( is_null( $this->mRevisionUser
) ) {
5703 $revObject = $this->getRevisionObject();
5705 # if this template is subst: the revision id will be blank,
5706 # so just use the current user's name
5708 $this->mRevisionUser
= $revObject->getUserText();
5709 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5710 $this->mRevisionUser
= $this->getUser()->getName();
5713 return $this->mRevisionUser
;
5717 * Get the size of the revision
5719 * @return int|null Revision size
5721 public function getRevisionSize() {
5722 if ( is_null( $this->mRevisionSize
) ) {
5723 $revObject = $this->getRevisionObject();
5725 # if this variable is subst: the revision id will be blank,
5726 # so just use the parser input size, because the own substituation
5727 # will change the size.
5729 $this->mRevisionSize
= $revObject->getSize();
5731 $this->mRevisionSize
= $this->mInputSize
;
5734 return $this->mRevisionSize
;
5738 * Mutator for $mDefaultSort
5740 * @param string $sort New value
5742 public function setDefaultSort( $sort ) {
5743 $this->mDefaultSort
= $sort;
5744 $this->mOutput
->setProperty( 'defaultsort', $sort );
5748 * Accessor for $mDefaultSort
5749 * Will use the empty string if none is set.
5751 * This value is treated as a prefix, so the
5752 * empty string is equivalent to sorting by
5757 public function getDefaultSort() {
5758 if ( $this->mDefaultSort
!== false ) {
5759 return $this->mDefaultSort
;
5766 * Accessor for $mDefaultSort
5767 * Unlike getDefaultSort(), will return false if none is set
5769 * @return string|bool
5771 public function getCustomDefaultSort() {
5772 return $this->mDefaultSort
;
5775 private static function getSectionNameFromStrippedText( $text ) {
5776 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5777 $text = Sanitizer
::decodeCharReferences( $text );
5778 $text = self
::normalizeSectionName( $text );
5782 private static function makeAnchor( $sectionName ) {
5783 return '#' . Sanitizer
::escapeIdForLink( $sectionName );
5786 private static function makeLegacyAnchor( $sectionName ) {
5787 global $wgFragmentMode;
5788 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5789 // ForAttribute() and ForLink() are the same for legacy encoding
5790 $id = Sanitizer
::escapeIdForAttribute( $text, Sanitizer
::ID_FALLBACK
);
5792 $id = Sanitizer
::escapeIdForLink( $text );
5799 * Try to guess the section anchor name based on a wikitext fragment
5800 * presumably extracted from a heading, for example "Header" from
5803 * @param string $text
5804 * @return string Anchor (starting with '#')
5806 public function guessSectionNameFromWikiText( $text ) {
5807 # Strip out wikitext links(they break the anchor)
5808 $text = $this->stripSectionName( $text );
5809 $sectionName = self
::getSectionNameFromStrippedText( $text );
5810 return self
::makeAnchor( $sectionName );
5814 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5815 * instead, if possible. For use in redirects, since various versions
5816 * of Microsoft browsers interpret Location: headers as something other
5817 * than UTF-8, resulting in breakage.
5819 * @param string $text The section name
5820 * @return string Anchor (starting with '#')
5822 public function guessLegacySectionNameFromWikiText( $text ) {
5823 # Strip out wikitext links(they break the anchor)
5824 $text = $this->stripSectionName( $text );
5825 $sectionName = self
::getSectionNameFromStrippedText( $text );
5826 return self
::makeLegacyAnchor( $sectionName );
5830 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
5831 * @param string $text Section name (plain text)
5832 * @return string Anchor (starting with '#')
5834 public static function guessSectionNameFromStrippedText( $text ) {
5835 $sectionName = self
::getSectionNameFromStrippedText( $text );
5836 return self
::makeAnchor( $sectionName );
5840 * Apply the same normalization as code making links to this section would
5842 * @param string $text
5845 private static function normalizeSectionName( $text ) {
5846 # T90902: ensure the same normalization is applied for IDs as to links
5847 $titleParser = MediaWikiServices
::getInstance()->getTitleParser();
5850 $parts = $titleParser->splitTitleString( "#$text" );
5851 } catch ( MalformedTitleException
$ex ) {
5854 return $parts['fragment'];
5858 * Strips a text string of wikitext for use in a section anchor
5860 * Accepts a text string and then removes all wikitext from the
5861 * string and leaves only the resultant text (i.e. the result of
5862 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5863 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5864 * to create valid section anchors by mimicing the output of the
5865 * parser when headings are parsed.
5867 * @param string $text Text string to be stripped of wikitext
5868 * for use in a Section anchor
5869 * @return string Filtered text string
5871 public function stripSectionName( $text ) {
5872 # Strip internal link markup
5873 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5874 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5876 # Strip external link markup
5877 # @todo FIXME: Not tolerant to blank link text
5878 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5879 # on how many empty links there are on the page - need to figure that out.
5880 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5882 # Parse wikitext quotes (italics & bold)
5883 $text = $this->doQuotes( $text );
5886 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5891 * strip/replaceVariables/unstrip for preprocessor regression testing
5893 * @param string $text
5894 * @param Title $title
5895 * @param ParserOptions $options
5896 * @param int $outputType
5900 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5901 $outputType = self
::OT_HTML
5903 $magicScopeVariable = $this->lock();
5904 $this->startParse( $title, $options, $outputType, true );
5906 $text = $this->replaceVariables( $text );
5907 $text = $this->mStripState
->unstripBoth( $text );
5908 $text = Sanitizer
::removeHTMLtags( $text );
5913 * @param string $text
5914 * @param Title $title
5915 * @param ParserOptions $options
5918 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5919 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5923 * @param string $text
5924 * @param Title $title
5925 * @param ParserOptions $options
5928 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5929 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5933 * Call a callback function on all regions of the given text that are not
5934 * inside strip markers, and replace those regions with the return value
5935 * of the callback. For example, with input:
5939 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5940 * two strings will be replaced with the value returned by the callback in
5944 * @param callable $callback
5948 public function markerSkipCallback( $s, $callback ) {
5951 while ( $i < strlen( $s ) ) {
5952 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
5953 if ( $markerStart === false ) {
5954 $out .= call_user_func( $callback, substr( $s, $i ) );
5957 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5958 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5959 if ( $markerEnd === false ) {
5960 $out .= substr( $s, $markerStart );
5963 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5964 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5973 * Remove any strip markers found in the given text.
5975 * @param string $text Input string
5978 public function killMarkers( $text ) {
5979 return $this->mStripState
->killMarkers( $text );
5983 * Save the parser state required to convert the given half-parsed text to
5984 * HTML. "Half-parsed" in this context means the output of
5985 * recursiveTagParse() or internalParse(). This output has strip markers
5986 * from replaceVariables (extensionSubstitution() etc.), and link
5987 * placeholders from replaceLinkHolders().
5989 * Returns an array which can be serialized and stored persistently. This
5990 * array can later be loaded into another parser instance with
5991 * unserializeHalfParsedText(). The text can then be safely incorporated into
5992 * the return value of a parser hook.
5994 * @param string $text
5998 public function serializeHalfParsedText( $text ) {
6001 'version' => self
::HALF_PARSED_VERSION
,
6002 'stripState' => $this->mStripState
->getSubState( $text ),
6003 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6009 * Load the parser state given in the $data array, which is assumed to
6010 * have been generated by serializeHalfParsedText(). The text contents is
6011 * extracted from the array, and its markers are transformed into markers
6012 * appropriate for the current Parser instance. This transformed text is
6013 * returned, and can be safely included in the return value of a parser
6016 * If the $data array has been stored persistently, the caller should first
6017 * check whether it is still valid, by calling isValidHalfParsedText().
6019 * @param array $data Serialized data
6020 * @throws MWException
6023 public function unserializeHalfParsedText( $data ) {
6024 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6025 throw new MWException( __METHOD__
. ': invalid version' );
6028 # First, extract the strip state.
6029 $texts = [ $data['text'] ];
6030 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6032 # Now renumber links
6033 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6035 # Should be good to go.
6040 * Returns true if the given array, presumed to be generated by
6041 * serializeHalfParsedText(), is compatible with the current version of the
6044 * @param array $data
6048 public function isValidHalfParsedText( $data ) {
6049 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6053 * Parsed a width param of imagelink like 300px or 200x300px
6055 * @param string $value
6060 public function parseWidthParam( $value ) {
6061 $parsedWidthParam = [];
6062 if ( $value === '' ) {
6063 return $parsedWidthParam;
6066 # (T15500) In both cases (width/height and width only),
6067 # permit trailing "px" for backward compatibility.
6068 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6069 $width = intval( $m[1] );
6070 $height = intval( $m[2] );
6071 $parsedWidthParam['width'] = $width;
6072 $parsedWidthParam['height'] = $height;
6073 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6074 $width = intval( $value );
6075 $parsedWidthParam['width'] = $width;
6077 return $parsedWidthParam;
6081 * Lock the current instance of the parser.
6083 * This is meant to stop someone from calling the parser
6084 * recursively and messing up all the strip state.
6086 * @throws MWException If parser is in a parse
6087 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6089 protected function lock() {
6090 if ( $this->mInParse
) {
6091 throw new MWException( "Parser state cleared while parsing. "
6092 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6095 // Save the backtrace when locking, so that if some code tries locking again,
6096 // we can print the lock owner's backtrace for easier debugging
6098 $this->mInParse
= $e->getTraceAsString();
6100 $recursiveCheck = new ScopedCallback( function () {
6101 $this->mInParse
= false;
6104 return $recursiveCheck;
6108 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6110 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6111 * or if there is more than one <p/> tag in the input HTML.
6113 * @param string $html
6117 public static function stripOuterParagraph( $html ) {
6119 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6120 if ( strpos( $m[1], '</p>' ) === false ) {
6129 * Return this parser if it is not doing anything, otherwise
6130 * get a fresh parser. You can use this method by doing
6131 * $myParser = $wgParser->getFreshParser(), or more simply
6132 * $wgParser->getFreshParser()->parse( ... );
6133 * if you're unsure if $wgParser is safe to use.
6136 * @return Parser A parser object that is not parsing anything
6138 public function getFreshParser() {
6139 global $wgParserConf;
6140 if ( $this->mInParse
) {
6141 return new $wgParserConf['class']( $wgParserConf );
6148 * Set's up the PHP implementation of OOUI for use in this request
6149 * and instructs OutputPage to enable OOUI for itself.
6153 public function enableOOUI() {
6154 OutputPage
::setupOOUI();
6155 $this->mOutput
->setEnableOOUI( true );