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 // @codingStandardsIgnoreStart 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';
102 // @codingStandardsIgnoreEnd
104 # Regular expression for a non-newline space
105 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
107 # Flags for preprocessToDom
108 const PTD_FOR_INCLUSION
= 1;
110 # Allowed values for $this->mOutputType
111 # Parameter to startExternalParse().
112 const OT_HTML
= 1; # like parse()
113 const OT_WIKI
= 2; # like preSaveTransform()
114 const OT_PREPROCESS
= 3; # like preprocess()
116 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
119 * @var string Prefix and suffix for temporary replacement strings
120 * for the multipass parser.
122 * \x7f should never appear in input as it's disallowed in XML.
123 * Using it at the front also gives us a little extra robustness
124 * since it shouldn't match when butted up against identifier-like
127 * Must not consist of all title characters, or else it will change
128 * the behavior of <nowiki> in a link.
130 * Must have a character that needs escaping in attributes, otherwise
131 * someone could put a strip marker in an attribute, to get around
132 * escaping quote marks, and break out of the attribute. Thus we add
135 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
136 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
138 # Markers used for wrapping the table of contents
139 const TOC_START
= '<mw:toc>';
140 const TOC_END
= '</mw:toc>';
143 public $mTagHooks = [];
144 public $mTransparentTagHooks = [];
145 public $mFunctionHooks = [];
146 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
147 public $mFunctionTagHooks = [];
148 public $mStripList = [];
149 public $mDefaultStripList = [];
150 public $mVarCache = [];
151 public $mImageParams = [];
152 public $mImageParamsMagicArray = [];
153 public $mMarkerIndex = 0;
154 public $mFirstCall = true;
156 # Initialised by initialiseVariables()
159 * @var MagicWordArray
164 * @var MagicWordArray
167 # Initialised in constructor
168 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
170 # Initialized in getPreprocessor()
171 /** @var Preprocessor */
172 public $mPreprocessor;
174 # Cleared with clearState():
186 public $mIncludeCount;
188 * @var LinkHolderArray
190 public $mLinkHolders;
193 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
194 public $mDefaultSort;
195 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
196 public $mExpensiveFunctionCount; # number of expensive parser function calls
197 public $mShowToc, $mForceTocPosition;
202 public $mUser; # User object; only used when doing pre-save transform
205 # These are variables reset at least once per parse regardless of $clearState
215 public $mTitle; # Title context, used for self-link rendering and similar things
216 public $mOutputType; # Output type, one of the OT_xxx constants
217 public $ot; # Shortcut alias, see setOutputType()
218 public $mRevisionObject; # The revision object of the specified revision ID
219 public $mRevisionId; # ID to display in {{REVISIONID}} tags
220 public $mRevisionTimestamp; # The timestamp of the specified revision ID
221 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
222 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
223 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
224 public $mInputSize = false; # For {{PAGESIZE}} on current page.
227 * @var string Deprecated accessor for the strip marker prefix.
228 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
230 public $mUniqPrefix = Parser
::MARKER_PREFIX
;
233 * @var array Array with the language name of each language link (i.e. the
234 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
235 * duplicate language links to the ParserOutput.
237 public $mLangLinkLanguages;
240 * @var MapCacheLRU|null
243 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
245 public $currentRevisionCache;
248 * @var bool|string Recursive call protection.
249 * This variable should be treated as if it were private.
251 public $mInParse = false;
253 /** @var SectionProfiler */
254 protected $mProfiler;
259 protected $mLinkRenderer;
264 public function __construct( $conf = [] ) {
265 $this->mConf
= $conf;
266 $this->mUrlProtocols
= wfUrlProtocols();
267 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
268 self
::EXT_LINK_ADDR
.
269 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
270 if ( isset( $conf['preprocessorClass'] ) ) {
271 $this->mPreprocessorClass
= $conf['preprocessorClass'];
272 } elseif ( defined( 'HPHP_VERSION' ) ) {
273 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
274 $this->mPreprocessorClass
= 'Preprocessor_Hash';
275 } elseif ( extension_loaded( 'domxml' ) ) {
276 # PECL extension that conflicts with the core DOM extension (T15770)
277 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
278 $this->mPreprocessorClass
= 'Preprocessor_Hash';
279 } elseif ( extension_loaded( 'dom' ) ) {
280 $this->mPreprocessorClass
= 'Preprocessor_DOM';
282 $this->mPreprocessorClass
= 'Preprocessor_Hash';
284 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
288 * Reduce memory usage to reduce the impact of circular references
290 public function __destruct() {
291 if ( isset( $this->mLinkHolders
) ) {
292 unset( $this->mLinkHolders
);
294 foreach ( $this as $name => $value ) {
295 unset( $this->$name );
300 * Allow extensions to clean up when the parser is cloned
302 public function __clone() {
303 $this->mInParse
= false;
305 // T58226: When you create a reference "to" an object field, that
306 // makes the object field itself be a reference too (until the other
307 // reference goes out of scope). When cloning, any field that's a
308 // reference is copied as a reference in the new object. Both of these
309 // are defined PHP5 behaviors, as inconvenient as it is for us when old
310 // hooks from PHP4 days are passing fields by reference.
311 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
312 // Make a non-reference copy of the field, then rebind the field to
313 // reference the new copy.
319 Hooks
::run( 'ParserCloned', [ $this ] );
323 * Do various kinds of initialisation on the first call of the parser
325 public function firstCallInit() {
326 if ( !$this->mFirstCall
) {
329 $this->mFirstCall
= false;
331 CoreParserFunctions
::register( $this );
332 CoreTagHooks
::register( $this );
333 $this->initialiseVariables();
335 // Avoid PHP 7.1 warning from passing $this by reference
337 Hooks
::run( 'ParserFirstCallInit', [ &$parser ] );
345 public function clearState() {
346 if ( $this->mFirstCall
) {
347 $this->firstCallInit();
349 $this->mOutput
= new ParserOutput
;
350 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
351 $this->mAutonumber
= 0;
352 $this->mIncludeCount
= [];
353 $this->mLinkHolders
= new LinkHolderArray( $this );
355 $this->mRevisionObject
= $this->mRevisionTimestamp
=
356 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
357 $this->mVarCache
= [];
359 $this->mLangLinkLanguages
= [];
360 $this->currentRevisionCache
= null;
362 $this->mStripState
= new StripState
;
364 # Clear these on every parse, T6549
365 $this->mTplRedirCache
= $this->mTplDomCache
= [];
367 $this->mShowToc
= true;
368 $this->mForceTocPosition
= false;
369 $this->mIncludeSizes
= [
373 $this->mPPNodeCount
= 0;
374 $this->mGeneratedPPNodeCount
= 0;
375 $this->mHighestExpansionDepth
= 0;
376 $this->mDefaultSort
= false;
377 $this->mHeadings
= [];
378 $this->mDoubleUnderscores
= [];
379 $this->mExpensiveFunctionCount
= 0;
382 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
383 $this->mPreprocessor
= null;
386 $this->mProfiler
= new SectionProfiler();
388 // Avoid PHP 7.1 warning from passing $this by reference
390 Hooks
::run( 'ParserClearState', [ &$parser ] );
394 * Convert wikitext to HTML
395 * Do not call this function recursively.
397 * @param string $text Text we want to parse
398 * @param Title $title
399 * @param ParserOptions $options
400 * @param bool $linestart
401 * @param bool $clearState
402 * @param int $revid Number to pass in {{REVISIONID}}
403 * @return ParserOutput A ParserOutput
405 public function parse(
406 $text, Title
$title, ParserOptions
$options,
407 $linestart = true, $clearState = true, $revid = null
410 * First pass--just handle <nowiki> sections, pass the rest off
411 * to internalParse() which does all the real work.
414 global $wgShowHostnames;
417 // We use U+007F DELETE to construct strip markers, so we have to make
418 // sure that this character does not occur in the input text.
419 $text = strtr( $text, "\x7f", "?" );
420 $magicScopeVariable = $this->lock();
422 // Strip U+0000 NULL (T159174)
423 $text = str_replace( "\000", '', $text );
425 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
427 $this->currentRevisionCache
= null;
428 $this->mInputSize
= strlen( $text );
429 if ( $this->mOptions
->getEnableLimitReport() ) {
430 $this->mOutput
->resetParseStartTime();
433 $oldRevisionId = $this->mRevisionId
;
434 $oldRevisionObject = $this->mRevisionObject
;
435 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
436 $oldRevisionUser = $this->mRevisionUser
;
437 $oldRevisionSize = $this->mRevisionSize
;
438 if ( $revid !== null ) {
439 $this->mRevisionId
= $revid;
440 $this->mRevisionObject
= null;
441 $this->mRevisionTimestamp
= null;
442 $this->mRevisionUser
= null;
443 $this->mRevisionSize
= null;
446 // Avoid PHP 7.1 warning from passing $this by reference
448 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
450 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
451 $text = $this->internalParse( $text );
452 Hooks
::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState
] );
454 $text = $this->internalParseHalfParsed( $text, true, $linestart );
457 * A converted title will be provided in the output object if title and
458 * content conversion are enabled, the article text does not contain
459 * a conversion-suppressing double-underscore tag, and no
460 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
461 * automatic link conversion.
463 if ( !( $options->getDisableTitleConversion()
464 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
465 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
466 ||
$this->mOutput
->getDisplayTitle() !== false )
468 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
469 if ( $convruletitle ) {
470 $this->mOutput
->setTitleText( $convruletitle );
472 $titleText = $this->getConverterLanguage()->convertTitle( $title );
473 $this->mOutput
->setTitleText( $titleText );
477 # Done parsing! Compute runtime adaptive expiry if set
478 $this->mOutput
->finalizeAdaptiveCacheExpiry();
480 # Warn if too many heavyweight parser functions were used
481 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
482 $this->limitationWarn( 'expensive-parserfunction',
483 $this->mExpensiveFunctionCount
,
484 $this->mOptions
->getExpensiveParserFunctionLimit()
488 # Information on include size limits, for the benefit of users who try to skirt them
489 if ( $this->mOptions
->getEnableLimitReport() ) {
490 $max = $this->mOptions
->getMaxIncludeSize();
492 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
493 if ( $cpuTime !== null ) {
494 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
495 sprintf( "%.3f", $cpuTime )
499 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
500 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
501 sprintf( "%.3f", $wallTime )
504 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
505 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
507 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
508 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
510 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
511 [ $this->mIncludeSizes
['post-expand'], $max ]
513 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
514 [ $this->mIncludeSizes
['arg'], $max ]
516 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
517 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
519 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
520 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
522 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
524 $limitReport = "NewPP limit report\n";
525 if ( $wgShowHostnames ) {
526 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
528 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
529 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
530 $limitReport .= 'Dynamic content: ' .
531 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
534 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
535 if ( Hooks
::run( 'ParserLimitReportFormat',
536 [ $key, &$value, &$limitReport, false, false ]
538 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
539 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
540 ->inLanguage( 'en' )->useDatabase( false );
541 if ( !$valueMsg->exists() ) {
542 $valueMsg = new RawMessage( '$1' );
544 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
545 $valueMsg->params( $value );
546 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
550 // Since we're not really outputting HTML, decode the entities and
551 // then re-encode the things that need hiding inside HTML comments.
552 $limitReport = htmlspecialchars_decode( $limitReport );
553 // Run deprecated hook
554 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
556 // Sanitize for comment. Note '‐' in the replacement is U+2010,
557 // which looks much like the problematic '-'.
558 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
559 $text .= "\n<!-- \n$limitReport-->\n";
561 // Add on template profiling data in human/machine readable way
562 $dataByFunc = $this->mProfiler
->getFunctionStats();
563 uasort( $dataByFunc, function ( $a, $b ) {
564 return $a['real'] < $b['real']; // descending order
567 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
568 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
569 $item['%real'], $item['real'], $item['calls'],
570 htmlspecialchars( $item['name'] ) );
572 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
573 $text .= implode( "\n", $profileReport ) . "\n-->\n";
575 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
577 // Add other cache related metadata
578 if ( $wgShowHostnames ) {
579 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
581 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
582 $this->mOutput
->getCacheTime() );
583 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
584 $this->mOutput
->getCacheExpiry() );
585 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
586 $this->mOutput
->hasDynamicContent() );
588 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
589 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
590 $this->mTitle
->getPrefixedDBkey() );
594 # Wrap non-interface parser output in a <div> so it can be targeted
596 $class = $this->mOptions
->getWrapOutputClass();
597 if ( $class !== false && !$this->mOptions
->getInterfaceMessage() ) {
598 $text = Html
::rawElement( 'div', [ 'class' => $class ], $text );
601 $this->mOutput
->setText( $text );
603 $this->mRevisionId
= $oldRevisionId;
604 $this->mRevisionObject
= $oldRevisionObject;
605 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
606 $this->mRevisionUser
= $oldRevisionUser;
607 $this->mRevisionSize
= $oldRevisionSize;
608 $this->mInputSize
= false;
609 $this->currentRevisionCache
= null;
611 return $this->mOutput
;
615 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
616 * can be called from an extension tag hook.
618 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
619 * instead, which means that lists and links have not been fully parsed yet,
620 * and strip markers are still present.
622 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
624 * Use this function if you're a parser tag hook and you want to parse
625 * wikitext before or after applying additional transformations, and you
626 * intend to *return the result as hook output*, which will cause it to go
627 * through the rest of parsing process automatically.
629 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
630 * $text are not expanded
632 * @param string $text Text extension wants to have parsed
633 * @param bool|PPFrame $frame The frame to use for expanding any template variables
634 * @return string UNSAFE half-parsed HTML
636 public function recursiveTagParse( $text, $frame = false ) {
637 // Avoid PHP 7.1 warning from passing $this by reference
639 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
640 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
641 $text = $this->internalParse( $text, false, $frame );
646 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
647 * point can be called from an extension tag hook.
649 * The output of this function is fully-parsed HTML that is safe for output.
650 * If you're a parser tag hook, you might want to use recursiveTagParse()
653 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
654 * $text are not expanded
658 * @param string $text Text extension wants to have parsed
659 * @param bool|PPFrame $frame The frame to use for expanding any template variables
660 * @return string Fully parsed HTML
662 public function recursiveTagParseFully( $text, $frame = false ) {
663 $text = $this->recursiveTagParse( $text, $frame );
664 $text = $this->internalParseHalfParsed( $text, false );
669 * Expand templates and variables in the text, producing valid, static wikitext.
670 * Also removes comments.
671 * Do not call this function recursively.
672 * @param string $text
673 * @param Title $title
674 * @param ParserOptions $options
675 * @param int|null $revid
676 * @param bool|PPFrame $frame
677 * @return mixed|string
679 public function preprocess( $text, Title
$title = null,
680 ParserOptions
$options, $revid = null, $frame = false
682 $magicScopeVariable = $this->lock();
683 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
684 if ( $revid !== null ) {
685 $this->mRevisionId
= $revid;
687 // Avoid PHP 7.1 warning from passing $this by reference
689 Hooks
::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState
] );
690 Hooks
::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState
] );
691 $text = $this->replaceVariables( $text, $frame );
692 $text = $this->mStripState
->unstripBoth( $text );
697 * Recursive parser entry point that can be called from an extension tag
700 * @param string $text Text to be expanded
701 * @param bool|PPFrame $frame The frame to use for expanding any template variables
705 public function recursivePreprocess( $text, $frame = false ) {
706 $text = $this->replaceVariables( $text, $frame );
707 $text = $this->mStripState
->unstripBoth( $text );
712 * Process the wikitext for the "?preload=" feature. (T7210)
714 * "<noinclude>", "<includeonly>" etc. are parsed as for template
715 * transclusion, comments, templates, arguments, tags hooks and parser
716 * functions are untouched.
718 * @param string $text
719 * @param Title $title
720 * @param ParserOptions $options
721 * @param array $params
724 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
725 $msg = new RawMessage( $text );
726 $text = $msg->params( $params )->plain();
728 # Parser (re)initialisation
729 $magicScopeVariable = $this->lock();
730 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
732 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
733 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
734 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
735 $text = $this->mStripState
->unstripBoth( $text );
740 * Get a random string
743 * @deprecated since 1.26; use wfRandomString() instead.
745 public static function getRandomString() {
746 wfDeprecated( __METHOD__
, '1.26' );
747 return wfRandomString( 16 );
751 * Set the current user.
752 * Should only be used when doing pre-save transform.
754 * @param User|null $user User object or null (to reset)
756 public function setUser( $user ) {
757 $this->mUser
= $user;
761 * Accessor for mUniqPrefix.
764 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
766 public function uniqPrefix() {
767 wfDeprecated( __METHOD__
, '1.26' );
768 return self
::MARKER_PREFIX
;
772 * Set the context title
776 public function setTitle( $t ) {
778 $t = Title
::newFromText( 'NO TITLE' );
781 if ( $t->hasFragment() ) {
782 # Strip the fragment to avoid various odd effects
783 $this->mTitle
= $t->createFragmentTarget( '' );
790 * Accessor for the Title object
794 public function getTitle() {
795 return $this->mTitle
;
799 * Accessor/mutator for the Title object
801 * @param Title $x Title object or null to just get the current one
804 public function Title( $x = null ) {
805 return wfSetVar( $this->mTitle
, $x );
809 * Set the output type
811 * @param int $ot New value
813 public function setOutputType( $ot ) {
814 $this->mOutputType
= $ot;
817 'html' => $ot == self
::OT_HTML
,
818 'wiki' => $ot == self
::OT_WIKI
,
819 'pre' => $ot == self
::OT_PREPROCESS
,
820 'plain' => $ot == self
::OT_PLAIN
,
825 * Accessor/mutator for the output type
827 * @param int|null $x New value or null to just get the current one
830 public function OutputType( $x = null ) {
831 return wfSetVar( $this->mOutputType
, $x );
835 * Get the ParserOutput object
837 * @return ParserOutput
839 public function getOutput() {
840 return $this->mOutput
;
844 * Get the ParserOptions object
846 * @return ParserOptions
848 public function getOptions() {
849 return $this->mOptions
;
853 * Accessor/mutator for the ParserOptions object
855 * @param ParserOptions $x New value or null to just get the current one
856 * @return ParserOptions Current ParserOptions object
858 public function Options( $x = null ) {
859 return wfSetVar( $this->mOptions
, $x );
865 public function nextLinkID() {
866 return $this->mLinkID++
;
872 public function setLinkID( $id ) {
873 $this->mLinkID
= $id;
877 * Get a language object for use in parser functions such as {{FORMATNUM:}}
880 public function getFunctionLang() {
881 return $this->getTargetLanguage();
885 * Get the target language for the content being parsed. This is usually the
886 * language that the content is in.
890 * @throws MWException
893 public function getTargetLanguage() {
894 $target = $this->mOptions
->getTargetLanguage();
896 if ( $target !== null ) {
898 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
899 return $this->mOptions
->getUserLangObj();
900 } elseif ( is_null( $this->mTitle
) ) {
901 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
904 return $this->mTitle
->getPageLanguage();
908 * Get the language object for language conversion
909 * @return Language|null
911 public function getConverterLanguage() {
912 return $this->getTargetLanguage();
916 * Get a User object either from $this->mUser, if set, or from the
917 * ParserOptions object otherwise
921 public function getUser() {
922 if ( !is_null( $this->mUser
) ) {
925 return $this->mOptions
->getUser();
929 * Get a preprocessor object
931 * @return Preprocessor
933 public function getPreprocessor() {
934 if ( !isset( $this->mPreprocessor
) ) {
935 $class = $this->mPreprocessorClass
;
936 $this->mPreprocessor
= new $class( $this );
938 return $this->mPreprocessor
;
942 * Get a LinkRenderer instance to make links with
945 * @return LinkRenderer
947 public function getLinkRenderer() {
948 if ( !$this->mLinkRenderer
) {
949 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
950 ->getLinkRendererFactory()->create();
951 $this->mLinkRenderer
->setStubThreshold(
952 $this->getOptions()->getStubThreshold()
956 return $this->mLinkRenderer
;
960 * Replaces all occurrences of HTML-style comments and the given tags
961 * in the text with a random marker and returns the next text. The output
962 * parameter $matches will be an associative array filled with data in
969 * [ 'param' => 'x' ],
970 * '<element param="x">tag content</element>' ]
973 * @param array $elements List of element names. Comments are always extracted.
974 * @param string $text Source text string.
975 * @param array $matches Out parameter, Array: extracted tags
976 * @param string|null $uniq_prefix
977 * @return string Stripped text
978 * @since 1.26 The uniq_prefix argument is deprecated.
980 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
981 if ( $uniq_prefix !== null ) {
982 wfDeprecated( __METHOD__
. ' called with $prefix argument', '1.26' );
988 $taglist = implode( '|', $elements );
989 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
991 while ( $text != '' ) {
992 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
994 if ( count( $p ) < 5 ) {
997 if ( count( $p ) > 5 ) {
1006 $attributes = $p[2];
1011 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1012 $stripped .= $marker;
1014 if ( $close === '/>' ) {
1015 # Empty element tag, <tag />
1020 if ( $element === '!--' ) {
1023 $end = "/(<\\/$element\\s*>)/i";
1025 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1027 if ( count( $q ) < 3 ) {
1028 # No end tag -- let it run out to the end of the text.
1037 $matches[$marker] = [ $element,
1039 Sanitizer
::decodeTagAttributes( $attributes ),
1040 "<$element$attributes$close$content$tail" ];
1046 * Get a list of strippable XML-like elements
1050 public function getStripList() {
1051 return $this->mStripList
;
1055 * Add an item to the strip state
1056 * Returns the unique tag which must be inserted into the stripped text
1057 * The tag will be replaced with the original text in unstrip()
1059 * @param string $text
1063 public function insertStripItem( $text ) {
1064 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1065 $this->mMarkerIndex++
;
1066 $this->mStripState
->addGeneral( $marker, $text );
1071 * parse the wiki syntax used to render tables
1074 * @param string $text
1077 public function doTableStuff( $text ) {
1078 $lines = StringUtils
::explode( "\n", $text );
1080 $td_history = []; # Is currently a td tag open?
1081 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1082 $tr_history = []; # Is currently a tr tag open?
1083 $tr_attributes = []; # history of tr attributes
1084 $has_opened_tr = []; # Did this table open a <tr> element?
1085 $indent_level = 0; # indent level of the table
1087 foreach ( $lines as $outLine ) {
1088 $line = trim( $outLine );
1090 if ( $line === '' ) { # empty line, go to next line
1091 $out .= $outLine . "\n";
1095 $first_character = $line[0];
1096 $first_two = substr( $line, 0, 2 );
1099 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1100 # First check if we are starting a new table
1101 $indent_level = strlen( $matches[1] );
1103 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1104 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1106 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1107 array_push( $td_history, false );
1108 array_push( $last_tag_history, '' );
1109 array_push( $tr_history, false );
1110 array_push( $tr_attributes, '' );
1111 array_push( $has_opened_tr, false );
1112 } elseif ( count( $td_history ) == 0 ) {
1113 # Don't do any of the following
1114 $out .= $outLine . "\n";
1116 } elseif ( $first_two === '|}' ) {
1117 # We are ending a table
1118 $line = '</table>' . substr( $line, 2 );
1119 $last_tag = array_pop( $last_tag_history );
1121 if ( !array_pop( $has_opened_tr ) ) {
1122 $line = "<tr><td></td></tr>{$line}";
1125 if ( array_pop( $tr_history ) ) {
1126 $line = "</tr>{$line}";
1129 if ( array_pop( $td_history ) ) {
1130 $line = "</{$last_tag}>{$line}";
1132 array_pop( $tr_attributes );
1133 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1134 } elseif ( $first_two === '|-' ) {
1135 # Now we have a table row
1136 $line = preg_replace( '#^\|-+#', '', $line );
1138 # Whats after the tag is now only attributes
1139 $attributes = $this->mStripState
->unstripBoth( $line );
1140 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1141 array_pop( $tr_attributes );
1142 array_push( $tr_attributes, $attributes );
1145 $last_tag = array_pop( $last_tag_history );
1146 array_pop( $has_opened_tr );
1147 array_push( $has_opened_tr, true );
1149 if ( array_pop( $tr_history ) ) {
1153 if ( array_pop( $td_history ) ) {
1154 $line = "</{$last_tag}>{$line}";
1158 array_push( $tr_history, false );
1159 array_push( $td_history, false );
1160 array_push( $last_tag_history, '' );
1161 } elseif ( $first_character === '|'
1162 ||
$first_character === '!'
1163 ||
$first_two === '|+'
1165 # This might be cell elements, td, th or captions
1166 if ( $first_two === '|+' ) {
1167 $first_character = '+';
1168 $line = substr( $line, 2 );
1170 $line = substr( $line, 1 );
1173 // Implies both are valid for table headings.
1174 if ( $first_character === '!' ) {
1175 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1178 # Split up multiple cells on the same line.
1179 # FIXME : This can result in improper nesting of tags processed
1180 # by earlier parser steps.
1181 $cells = explode( '||', $line );
1185 # Loop through each table cell
1186 foreach ( $cells as $cell ) {
1188 if ( $first_character !== '+' ) {
1189 $tr_after = array_pop( $tr_attributes );
1190 if ( !array_pop( $tr_history ) ) {
1191 $previous = "<tr{$tr_after}>\n";
1193 array_push( $tr_history, true );
1194 array_push( $tr_attributes, '' );
1195 array_pop( $has_opened_tr );
1196 array_push( $has_opened_tr, true );
1199 $last_tag = array_pop( $last_tag_history );
1201 if ( array_pop( $td_history ) ) {
1202 $previous = "</{$last_tag}>\n{$previous}";
1205 if ( $first_character === '|' ) {
1207 } elseif ( $first_character === '!' ) {
1209 } elseif ( $first_character === '+' ) {
1210 $last_tag = 'caption';
1215 array_push( $last_tag_history, $last_tag );
1217 # A cell could contain both parameters and data
1218 $cell_data = explode( '|', $cell, 2 );
1220 # T2553: Note that a '|' inside an invalid link should not
1221 # be mistaken as delimiting cell parameters
1222 # Bug T153140: Neither should language converter markup.
1223 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1224 $cell = "{$previous}<{$last_tag}>{$cell}";
1225 } elseif ( count( $cell_data ) == 1 ) {
1226 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1228 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1229 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1230 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1234 array_push( $td_history, true );
1237 $out .= $outLine . "\n";
1240 # Closing open td, tr && table
1241 while ( count( $td_history ) > 0 ) {
1242 if ( array_pop( $td_history ) ) {
1245 if ( array_pop( $tr_history ) ) {
1248 if ( !array_pop( $has_opened_tr ) ) {
1249 $out .= "<tr><td></td></tr>\n";
1252 $out .= "</table>\n";
1255 # Remove trailing line-ending (b/c)
1256 if ( substr( $out, -1 ) === "\n" ) {
1257 $out = substr( $out, 0, -1 );
1260 # special case: don't return empty table
1261 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1269 * Helper function for parse() that transforms wiki markup into half-parsed
1270 * HTML. Only called for $mOutputType == self::OT_HTML.
1274 * @param string $text The text to parse
1275 * @param bool $isMain Whether this is being called from the main parse() function
1276 * @param PPFrame|bool $frame A pre-processor frame
1280 public function internalParse( $text, $isMain = true, $frame = false ) {
1283 // Avoid PHP 7.1 warning from passing $this by reference
1286 # Hook to suspend the parser in this state
1287 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState
] ) ) {
1291 # if $frame is provided, then use $frame for replacing any variables
1293 # use frame depth to infer how include/noinclude tags should be handled
1294 # depth=0 means this is the top-level document; otherwise it's an included document
1295 if ( !$frame->depth
) {
1298 $flag = Parser
::PTD_FOR_INCLUSION
;
1300 $dom = $this->preprocessToDom( $text, $flag );
1301 $text = $frame->expand( $dom );
1303 # if $frame is not provided, then use old-style replaceVariables
1304 $text = $this->replaceVariables( $text );
1307 Hooks
::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState
] );
1308 $text = Sanitizer
::removeHTMLtags(
1310 [ $this, 'attributeStripCallback' ],
1312 array_keys( $this->mTransparentTagHooks
),
1314 [ $this, 'addTrackingCategory' ]
1316 Hooks
::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState
] );
1318 # Tables need to come after variable replacement for things to work
1319 # properly; putting them before other transformations should keep
1320 # exciting things like link expansions from showing up in surprising
1322 $text = $this->doTableStuff( $text );
1324 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1326 $text = $this->doDoubleUnderscore( $text );
1328 $text = $this->doHeadings( $text );
1329 $text = $this->replaceInternalLinks( $text );
1330 $text = $this->doAllQuotes( $text );
1331 $text = $this->replaceExternalLinks( $text );
1333 # replaceInternalLinks may sometimes leave behind
1334 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1335 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1337 $text = $this->doMagicLinks( $text );
1338 $text = $this->formatHeadings( $text, $origText, $isMain );
1344 * Helper function for parse() that transforms half-parsed HTML into fully
1347 * @param string $text
1348 * @param bool $isMain
1349 * @param bool $linestart
1352 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1353 $text = $this->mStripState
->unstripGeneral( $text );
1355 // Avoid PHP 7.1 warning from passing $this by reference
1359 Hooks
::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1362 # Clean up special characters, only run once, next-to-last before doBlockLevels
1364 # French spaces, last one Guillemet-left
1365 # only if there is something before the space
1366 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1367 # french spaces, Guillemet-right
1368 '/(\\302\\253) /' => '\\1 ',
1369 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1371 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1373 $text = $this->doBlockLevels( $text, $linestart );
1375 $this->replaceLinkHolders( $text );
1378 * The input doesn't get language converted if
1380 * b) Content isn't converted
1381 * c) It's a conversion table
1382 * d) it is an interface message (which is in the user language)
1384 if ( !( $this->mOptions
->getDisableContentConversion()
1385 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1387 if ( !$this->mOptions
->getInterfaceMessage() ) {
1388 # The position of the convert() call should not be changed. it
1389 # assumes that the links are all replaced and the only thing left
1390 # is the <nowiki> mark.
1391 $text = $this->getConverterLanguage()->convert( $text );
1395 $text = $this->mStripState
->unstripNoWiki( $text );
1398 Hooks
::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1401 $text = $this->replaceTransparentTags( $text );
1402 $text = $this->mStripState
->unstripGeneral( $text );
1404 $text = Sanitizer
::normalizeCharReferences( $text );
1406 if ( MWTidy
::isEnabled() ) {
1407 if ( $this->mOptions
->getTidy() ) {
1408 $text = MWTidy
::tidy( $text );
1411 # attempt to sanitize at least some nesting problems
1412 # (T4702 and quite a few others)
1414 # ''Something [http://www.cool.com cool''] -->
1415 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1416 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1417 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1418 # fix up an anchor inside another anchor, only
1419 # at least for a single single nested link (T5695)
1420 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1421 '\\1\\2</a>\\3</a>\\1\\4</a>',
1422 # fix div inside inline elements- doBlockLevels won't wrap a line which
1423 # contains a div, so fix it up here; replace
1424 # div with escaped text
1425 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1426 '\\1\\3<div\\5>\\6</div>\\8\\9',
1427 # remove empty italic or bold tag pairs, some
1428 # introduced by rules above
1429 '/<([bi])><\/\\1>/' => '',
1432 $text = preg_replace(
1433 array_keys( $tidyregs ),
1434 array_values( $tidyregs ),
1439 Hooks
::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1446 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1447 * magic external links.
1452 * @param string $text
1456 public function doMagicLinks( $text ) {
1457 $prots = wfUrlProtocolsWithoutProtRel();
1458 $urlChar = self
::EXT_LINK_URL_CLASS
;
1459 $addr = self
::EXT_LINK_ADDR
;
1460 $space = self
::SPACE_NOT_NL
; # non-newline space
1461 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1462 $spaces = "$space++"; # possessive match of 1 or more spaces
1463 $text = preg_replace_callback(
1465 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1466 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1467 (\b # m[3]: Free external links
1469 ($addr$urlChar*) # m[4]: Post-protocol path
1471 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1473 \bISBN $spaces ( # m[6]: ISBN, capture number
1474 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1475 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1476 [0-9Xx] # check digit
1478 )!xu", [ $this, 'magicLinkCallback' ], $text );
1483 * @throws MWException
1485 * @return HTML|string
1487 public function magicLinkCallback( $m ) {
1488 if ( isset( $m[1] ) && $m[1] !== '' ) {
1491 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1494 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1495 # Free external link
1496 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1497 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1499 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1500 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1505 $cssClass = 'mw-magiclink-rfc';
1506 $trackingCat = 'magiclink-tracking-rfc';
1508 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1509 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1513 $urlmsg = 'pubmedurl';
1514 $cssClass = 'mw-magiclink-pmid';
1515 $trackingCat = 'magiclink-tracking-pmid';
1518 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1519 substr( $m[0], 0, 20 ) . '"' );
1521 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1522 $this->addTrackingCategory( $trackingCat );
1523 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1524 } elseif ( isset( $m[6] ) && $m[6] !== ''
1525 && $this->mOptions
->getMagicISBNLinks()
1529 $space = self
::SPACE_NOT_NL
; # non-newline space
1530 $isbn = preg_replace( "/$space/", ' ', $isbn );
1531 $num = strtr( $isbn, [
1536 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1537 return $this->getLinkRenderer()->makeKnownLink(
1538 SpecialPage
::getTitleFor( 'Booksources', $num ),
1541 'class' => 'internal mw-magiclink-isbn',
1542 'title' => false // suppress title attribute
1551 * Make a free external link, given a user-supplied URL
1553 * @param string $url
1554 * @param int $numPostProto
1555 * The number of characters after the protocol.
1556 * @return string HTML
1559 public function makeFreeExternalLink( $url, $numPostProto ) {
1562 # The characters '<' and '>' (which were escaped by
1563 # removeHTMLtags()) should not be included in
1564 # URLs, per RFC 2396.
1565 # Make terminate a URL as well (bug T84937)
1568 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1573 $trail = substr( $url, $m2[0][1] ) . $trail;
1574 $url = substr( $url, 0, $m2[0][1] );
1577 # Move trailing punctuation to $trail
1579 # If there is no left bracket, then consider right brackets fair game too
1580 if ( strpos( $url, '(' ) === false ) {
1584 $urlRev = strrev( $url );
1585 $numSepChars = strspn( $urlRev, $sep );
1586 # Don't break a trailing HTML entity by moving the ; into $trail
1587 # This is in hot code, so use substr_compare to avoid having to
1588 # create a new string object for the comparison
1589 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1590 # more optimization: instead of running preg_match with a $
1591 # anchor, which can be slow, do the match on the reversed
1592 # string starting at the desired offset.
1593 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1594 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1598 if ( $numSepChars ) {
1599 $trail = substr( $url, -$numSepChars ) . $trail;
1600 $url = substr( $url, 0, -$numSepChars );
1603 # Verify that we still have a real URL after trail removal, and
1604 # not just lone protocol
1605 if ( strlen( $trail ) >= $numPostProto ) {
1606 return $url . $trail;
1609 $url = Sanitizer
::cleanUrl( $url );
1611 # Is this an external image?
1612 $text = $this->maybeMakeExternalImage( $url );
1613 if ( $text === false ) {
1614 # Not an image, make a link
1615 $text = Linker
::makeExternalLink( $url,
1616 $this->getConverterLanguage()->markNoConversion( $url, true ),
1618 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1619 # Register it in the output object...
1620 $this->mOutput
->addExternalLink( $url );
1622 return $text . $trail;
1626 * Parse headers and return html
1630 * @param string $text
1634 public function doHeadings( $text ) {
1635 for ( $i = 6; $i >= 1; --$i ) {
1636 $h = str_repeat( '=', $i );
1637 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1643 * Replace single quotes with HTML markup
1646 * @param string $text
1648 * @return string The altered text
1650 public function doAllQuotes( $text ) {
1652 $lines = StringUtils
::explode( "\n", $text );
1653 foreach ( $lines as $line ) {
1654 $outtext .= $this->doQuotes( $line ) . "\n";
1656 $outtext = substr( $outtext, 0, -1 );
1661 * Helper function for doAllQuotes()
1663 * @param string $text
1667 public function doQuotes( $text ) {
1668 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1669 $countarr = count( $arr );
1670 if ( $countarr == 1 ) {
1674 // First, do some preliminary work. This may shift some apostrophes from
1675 // being mark-up to being text. It also counts the number of occurrences
1676 // of bold and italics mark-ups.
1679 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1680 $thislen = strlen( $arr[$i] );
1681 // If there are ever four apostrophes, assume the first is supposed to
1682 // be text, and the remaining three constitute mark-up for bold text.
1683 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1684 if ( $thislen == 4 ) {
1685 $arr[$i - 1] .= "'";
1688 } elseif ( $thislen > 5 ) {
1689 // If there are more than 5 apostrophes in a row, assume they're all
1690 // text except for the last 5.
1691 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1692 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1696 // Count the number of occurrences of bold and italics mark-ups.
1697 if ( $thislen == 2 ) {
1699 } elseif ( $thislen == 3 ) {
1701 } elseif ( $thislen == 5 ) {
1707 // If there is an odd number of both bold and italics, it is likely
1708 // that one of the bold ones was meant to be an apostrophe followed
1709 // by italics. Which one we cannot know for certain, but it is more
1710 // likely to be one that has a single-letter word before it.
1711 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1712 $firstsingleletterword = -1;
1713 $firstmultiletterword = -1;
1715 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1716 if ( strlen( $arr[$i] ) == 3 ) {
1717 $x1 = substr( $arr[$i - 1], -1 );
1718 $x2 = substr( $arr[$i - 1], -2, 1 );
1719 if ( $x1 === ' ' ) {
1720 if ( $firstspace == -1 ) {
1723 } elseif ( $x2 === ' ' ) {
1724 $firstsingleletterword = $i;
1725 // if $firstsingleletterword is set, we don't
1726 // look at the other options, so we can bail early.
1729 if ( $firstmultiletterword == -1 ) {
1730 $firstmultiletterword = $i;
1736 // If there is a single-letter word, use it!
1737 if ( $firstsingleletterword > -1 ) {
1738 $arr[$firstsingleletterword] = "''";
1739 $arr[$firstsingleletterword - 1] .= "'";
1740 } elseif ( $firstmultiletterword > -1 ) {
1741 // If not, but there's a multi-letter word, use that one.
1742 $arr[$firstmultiletterword] = "''";
1743 $arr[$firstmultiletterword - 1] .= "'";
1744 } elseif ( $firstspace > -1 ) {
1745 // ... otherwise use the first one that has neither.
1746 // (notice that it is possible for all three to be -1 if, for example,
1747 // there is only one pentuple-apostrophe in the line)
1748 $arr[$firstspace] = "''";
1749 $arr[$firstspace - 1] .= "'";
1753 // Now let's actually convert our apostrophic mush to HTML!
1758 foreach ( $arr as $r ) {
1759 if ( ( $i %
2 ) == 0 ) {
1760 if ( $state === 'both' ) {
1766 $thislen = strlen( $r );
1767 if ( $thislen == 2 ) {
1768 if ( $state === 'i' ) {
1771 } elseif ( $state === 'bi' ) {
1774 } elseif ( $state === 'ib' ) {
1775 $output .= '</b></i><b>';
1777 } elseif ( $state === 'both' ) {
1778 $output .= '<b><i>' . $buffer . '</i>';
1780 } else { // $state can be 'b' or ''
1784 } elseif ( $thislen == 3 ) {
1785 if ( $state === 'b' ) {
1788 } elseif ( $state === 'bi' ) {
1789 $output .= '</i></b><i>';
1791 } elseif ( $state === 'ib' ) {
1794 } elseif ( $state === 'both' ) {
1795 $output .= '<i><b>' . $buffer . '</b>';
1797 } else { // $state can be 'i' or ''
1801 } elseif ( $thislen == 5 ) {
1802 if ( $state === 'b' ) {
1803 $output .= '</b><i>';
1805 } elseif ( $state === 'i' ) {
1806 $output .= '</i><b>';
1808 } elseif ( $state === 'bi' ) {
1809 $output .= '</i></b>';
1811 } elseif ( $state === 'ib' ) {
1812 $output .= '</b></i>';
1814 } elseif ( $state === 'both' ) {
1815 $output .= '<i><b>' . $buffer . '</b></i>';
1817 } else { // ($state == '')
1825 // Now close all remaining tags. Notice that the order is important.
1826 if ( $state === 'b' ||
$state === 'ib' ) {
1829 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1832 if ( $state === 'bi' ) {
1835 // There might be lonely ''''', so make sure we have a buffer
1836 if ( $state === 'both' && $buffer ) {
1837 $output .= '<b><i>' . $buffer . '</i></b>';
1843 * Replace external links (REL)
1845 * Note: this is all very hackish and the order of execution matters a lot.
1846 * Make sure to run tests/parser/parserTests.php if you change this code.
1850 * @param string $text
1852 * @throws MWException
1855 public function replaceExternalLinks( $text ) {
1856 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1857 if ( $bits === false ) {
1858 throw new MWException( "PCRE needs to be compiled with "
1859 . "--enable-unicode-properties in order for MediaWiki to function" );
1861 $s = array_shift( $bits );
1864 while ( $i < count( $bits ) ) {
1867 $text = $bits[$i++
];
1868 $trail = $bits[$i++
];
1870 # The characters '<' and '>' (which were escaped by
1871 # removeHTMLtags()) should not be included in
1872 # URLs, per RFC 2396.
1874 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1875 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1876 $url = substr( $url, 0, $m2[0][1] );
1879 # If the link text is an image URL, replace it with an <img> tag
1880 # This happened by accident in the original parser, but some people used it extensively
1881 $img = $this->maybeMakeExternalImage( $text );
1882 if ( $img !== false ) {
1888 # Set linktype for CSS - if URL==text, link is essentially free
1889 $linktype = ( $text === $url ) ?
'free' : 'text';
1891 # No link text, e.g. [http://domain.tld/some.link]
1892 if ( $text == '' ) {
1894 $langObj = $this->getTargetLanguage();
1895 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1896 $linktype = 'autonumber';
1898 # Have link text, e.g. [http://domain.tld/some.link text]s
1900 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1903 $text = $this->getConverterLanguage()->markNoConversion( $text );
1905 $url = Sanitizer
::cleanUrl( $url );
1907 # Use the encoded URL
1908 # This means that users can paste URLs directly into the text
1909 # Funny characters like ö aren't valid in URLs anyway
1910 # This was changed in August 2004
1911 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1912 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1914 # Register link in the output object.
1915 $this->mOutput
->addExternalLink( $url );
1922 * Get the rel attribute for a particular external link.
1925 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1926 * nofollow if appropriate
1927 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1928 * @return string|null Rel attribute for $url
1930 public static function getExternalLinkRel( $url = false, $title = null ) {
1931 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1932 $ns = $title ?
$title->getNamespace() : false;
1933 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1934 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1942 * Get an associative array of additional HTML attributes appropriate for a
1943 * particular external link. This currently may include rel => nofollow
1944 * (depending on configuration, namespace, and the URL's domain) and/or a
1945 * target attribute (depending on configuration).
1947 * @param string $url URL to extract the domain from for rel =>
1948 * nofollow if appropriate
1949 * @return array Associative array of HTML attributes
1951 public function getExternalLinkAttribs( $url ) {
1953 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1955 $target = $this->mOptions
->getExternalLinkTarget();
1957 $attribs['target'] = $target;
1958 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1959 // T133507. New windows can navigate parent cross-origin.
1960 // Including noreferrer due to lacking browser
1961 // support of noopener. Eventually noreferrer should be removed.
1962 if ( $rel !== '' ) {
1965 $rel .= 'noreferrer noopener';
1968 $attribs['rel'] = $rel;
1973 * Replace unusual escape codes in a URL with their equivalent characters
1975 * This generally follows the syntax defined in RFC 3986, with special
1976 * consideration for HTTP query strings.
1978 * @param string $url
1981 public static function normalizeLinkUrl( $url ) {
1982 # First, make sure unsafe characters are encoded
1983 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1985 return rawurlencode( $m[0] );
1991 $end = strlen( $url );
1993 # Fragment part - 'fragment'
1994 $start = strpos( $url, '#' );
1995 if ( $start !== false && $start < $end ) {
1996 $ret = self
::normalizeUrlComponent(
1997 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2001 # Query part - 'query' minus &=+;
2002 $start = strpos( $url, '?' );
2003 if ( $start !== false && $start < $end ) {
2004 $ret = self
::normalizeUrlComponent(
2005 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2009 # Scheme and path part - 'pchar'
2010 # (we assume no userinfo or encoded colons in the host)
2011 $ret = self
::normalizeUrlComponent(
2012 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2017 private static function normalizeUrlComponent( $component, $unsafe ) {
2018 $callback = function ( $matches ) use ( $unsafe ) {
2019 $char = urldecode( $matches[0] );
2020 $ord = ord( $char );
2021 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2025 # Leave it escaped, but use uppercase for a-f
2026 return strtoupper( $matches[0] );
2029 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2033 * make an image if it's allowed, either through the global
2034 * option, through the exception, or through the on-wiki whitelist
2036 * @param string $url
2040 private function maybeMakeExternalImage( $url ) {
2041 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2042 $imagesexception = !empty( $imagesfrom );
2044 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2045 if ( $imagesexception && is_array( $imagesfrom ) ) {
2046 $imagematch = false;
2047 foreach ( $imagesfrom as $match ) {
2048 if ( strpos( $url, $match ) === 0 ) {
2053 } elseif ( $imagesexception ) {
2054 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2056 $imagematch = false;
2059 if ( $this->mOptions
->getAllowExternalImages()
2060 ||
( $imagesexception && $imagematch )
2062 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2064 $text = Linker
::makeExternalImage( $url );
2067 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2068 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2070 $whitelist = explode(
2072 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2075 foreach ( $whitelist as $entry ) {
2076 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2077 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2080 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2081 # Image matches a whitelist entry
2082 $text = Linker
::makeExternalImage( $url );
2091 * Process [[ ]] wikilinks
2095 * @return string Processed text
2099 public function replaceInternalLinks( $s ) {
2100 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2105 * Process [[ ]] wikilinks (RIL)
2107 * @throws MWException
2108 * @return LinkHolderArray
2112 public function replaceInternalLinks2( &$s ) {
2113 global $wgExtraInterlanguageLinkPrefixes;
2115 static $tc = false, $e1, $e1_img;
2116 # the % is needed to support urlencoded titles as well
2118 $tc = Title
::legalChars() . '#%';
2119 # Match a link having the form [[namespace:link|alternate]]trail
2120 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2121 # Match cases where there is no "]]", which might still be images
2122 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2125 $holders = new LinkHolderArray( $this );
2127 # split the entire text string on occurrences of [[
2128 $a = StringUtils
::explode( '[[', ' ' . $s );
2129 # get the first element (all text up to first [[), and remove the space we added
2132 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2133 $s = substr( $s, 1 );
2135 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2137 if ( $useLinkPrefixExtension ) {
2138 # Match the end of a line for a word that's not followed by whitespace,
2139 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2141 $charset = $wgContLang->linkPrefixCharset();
2142 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2145 if ( is_null( $this->mTitle
) ) {
2146 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2148 $nottalk = !$this->mTitle
->isTalkPage();
2150 if ( $useLinkPrefixExtension ) {
2152 if ( preg_match( $e2, $s, $m ) ) {
2153 $first_prefix = $m[2];
2155 $first_prefix = false;
2161 $useSubpages = $this->areSubpagesAllowed();
2163 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2164 # Loop for each link
2165 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2166 // @codingStandardsIgnoreEnd
2168 # Check for excessive memory usage
2169 if ( $holders->isBig() ) {
2171 # Do the existence check, replace the link holders and clear the array
2172 $holders->replace( $s );
2176 if ( $useLinkPrefixExtension ) {
2177 if ( preg_match( $e2, $s, $m ) ) {
2184 if ( $first_prefix ) {
2185 $prefix = $first_prefix;
2186 $first_prefix = false;
2190 $might_be_img = false;
2192 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2194 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2195 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2196 # the real problem is with the $e1 regex
2198 # Still some problems for cases where the ] is meant to be outside punctuation,
2199 # and no image is in sight. See T4095.
2201 && substr( $m[3], 0, 1 ) === ']'
2202 && strpos( $text, '[' ) !== false
2204 $text .= ']'; # so that replaceExternalLinks($text) works later
2205 $m[3] = substr( $m[3], 1 );
2207 # fix up urlencoded title texts
2208 if ( strpos( $m[1], '%' ) !== false ) {
2209 # Should anchors '#' also be rejected?
2210 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2213 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2214 # Invalid, but might be an image with a link in its caption
2215 $might_be_img = true;
2217 if ( strpos( $m[1], '%' ) !== false ) {
2218 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2221 } else { # Invalid form; output directly
2222 $s .= $prefix . '[[' . $line;
2226 $origLink = ltrim( $m[1], ' ' );
2228 # Don't allow internal links to pages containing
2229 # PROTO: where PROTO is a valid URL protocol; these
2230 # should be external links.
2231 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2232 $s .= $prefix . '[[' . $line;
2236 # Make subpage if necessary
2237 if ( $useSubpages ) {
2238 $link = $this->maybeDoSubpageLink( $origLink, $text );
2243 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2245 # Strip off leading ':'
2246 $link = substr( $link, 1 );
2249 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2250 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2251 if ( $nt === null ) {
2252 $s .= $prefix . '[[' . $line;
2256 $ns = $nt->getNamespace();
2257 $iw = $nt->getInterwiki();
2259 if ( $might_be_img ) { # if this is actually an invalid link
2260 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2263 # look at the next 'line' to see if we can close it there
2265 $next_line = $a->current();
2266 if ( $next_line === false ||
$next_line === null ) {
2269 $m = explode( ']]', $next_line, 3 );
2270 if ( count( $m ) == 3 ) {
2271 # the first ]] closes the inner link, the second the image
2273 $text .= "[[{$m[0]}]]{$m[1]}";
2276 } elseif ( count( $m ) == 2 ) {
2277 # if there's exactly one ]] that's fine, we'll keep looking
2278 $text .= "[[{$m[0]}]]{$m[1]}";
2280 # if $next_line is invalid too, we need look no further
2281 $text .= '[[' . $next_line;
2286 # we couldn't find the end of this imageLink, so output it raw
2287 # but don't ignore what might be perfectly normal links in the text we've examined
2288 $holders->merge( $this->replaceInternalLinks2( $text ) );
2289 $s .= "{$prefix}[[$link|$text";
2290 # note: no $trail, because without an end, there *is* no trail
2293 } else { # it's not an image, so output it raw
2294 $s .= "{$prefix}[[$link|$text";
2295 # note: no $trail, because without an end, there *is* no trail
2300 $wasblank = ( $text == '' );
2304 # T6598 madness. Handle the quotes only if they come from the alternate part
2305 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2306 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2307 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2308 $text = $this->doQuotes( $text );
2311 # Link not escaped by : , create the various objects
2312 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2315 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2316 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2317 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2320 # T26502: filter duplicates
2321 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2322 $this->mLangLinkLanguages
[$iw] = true;
2323 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2326 $s = rtrim( $s . $prefix );
2327 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2331 if ( $ns == NS_FILE
) {
2332 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2334 # if no parameters were passed, $text
2335 # becomes something like "File:Foo.png",
2336 # which we don't want to pass on to the
2340 # recursively parse links inside the image caption
2341 # actually, this will parse them in any other parameters, too,
2342 # but it might be hard to fix that, and it doesn't matter ATM
2343 $text = $this->replaceExternalLinks( $text );
2344 $holders->merge( $this->replaceInternalLinks2( $text ) );
2346 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2347 $s .= $prefix . $this->armorLinks(
2348 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2351 } elseif ( $ns == NS_CATEGORY
) {
2352 $s = rtrim( $s . "\n" ); # T2087
2355 $sortkey = $this->getDefaultSort();
2359 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2360 $sortkey = str_replace( "\n", '', $sortkey );
2361 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2362 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2365 * Strip the whitespace Category links produce, see T2087
2367 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2373 # Self-link checking. For some languages, variants of the title are checked in
2374 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2375 # for linking to a different variant.
2376 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2377 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2381 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2382 # @todo FIXME: Should do batch file existence checks, see comment below
2383 if ( $ns == NS_MEDIA
) {
2384 # Give extensions a chance to select the file revision for us
2387 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2388 [ $this, $nt, &$options, &$descQuery ] );
2389 # Fetch and register the file (file title may be different via hooks)
2390 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2391 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2392 $s .= $prefix . $this->armorLinks(
2393 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2397 # Some titles, such as valid special pages or files in foreign repos, should
2398 # be shown as bluelinks even though they're not included in the page table
2399 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2400 # batch file existence checks for NS_FILE and NS_MEDIA
2401 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2402 $this->mOutput
->addLink( $nt );
2403 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2405 # Links will be added to the output link list after checking
2406 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2413 * Render a forced-blue link inline; protect against double expansion of
2414 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2415 * Since this little disaster has to split off the trail text to avoid
2416 * breaking URLs in the following text without breaking trails on the
2417 * wiki links, it's been made into a horrible function.
2420 * @param string $text
2421 * @param string $trail
2422 * @param string $prefix
2423 * @return string HTML-wikitext mix oh yuck
2425 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2426 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2428 if ( $text == '' ) {
2429 $text = htmlspecialchars( $nt->getPrefixedText() );
2432 $link = $this->getLinkRenderer()->makeKnownLink(
2433 $nt, new HtmlArmor( "$prefix$text$inside" )
2436 return $this->armorLinks( $link ) . $trail;
2440 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2441 * going to go through further parsing steps before inline URL expansion.
2443 * Not needed quite as much as it used to be since free links are a bit
2444 * more sensible these days. But bracketed links are still an issue.
2446 * @param string $text More-or-less HTML
2447 * @return string Less-or-more HTML with NOPARSE bits
2449 public function armorLinks( $text ) {
2450 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2451 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2455 * Return true if subpage links should be expanded on this page.
2458 public function areSubpagesAllowed() {
2459 # Some namespaces don't allow subpages
2460 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2464 * Handle link to subpage if necessary
2466 * @param string $target The source of the link
2467 * @param string &$text The link text, modified as necessary
2468 * @return string The full name of the link
2471 public function maybeDoSubpageLink( $target, &$text ) {
2472 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2476 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2478 * @param string $text
2479 * @param bool $linestart Whether or not this is at the start of a line.
2481 * @return string The lists rendered as HTML
2483 public function doBlockLevels( $text, $linestart ) {
2484 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2488 * Return value of a magic variable (like PAGENAME)
2492 * @param string $index Magic variable identifier as mapped in MagicWord::$mVariableIDs
2493 * @param bool|PPFrame $frame
2495 * @throws MWException
2498 public function getVariableValue( $index, $frame = false ) {
2499 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2500 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2502 if ( is_null( $this->mTitle
) ) {
2503 // If no title set, bad things are going to happen
2504 // later. Title should always be set since this
2505 // should only be called in the middle of a parse
2506 // operation (but the unit-tests do funky stuff)
2507 throw new MWException( __METHOD__
. ' Should only be '
2508 . ' called while parsing (no title set)' );
2511 // Avoid PHP 7.1 warning from passing $this by reference
2515 * Some of these require message or data lookups and can be
2516 * expensive to check many times.
2518 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache
] ) ) {
2519 if ( isset( $this->mVarCache
[$index] ) ) {
2520 return $this->mVarCache
[$index];
2524 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2525 Hooks
::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2527 $pageLang = $this->getFunctionLang();
2533 case 'currentmonth':
2534 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2536 case 'currentmonth1':
2537 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2539 case 'currentmonthname':
2540 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2542 case 'currentmonthnamegen':
2543 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2545 case 'currentmonthabbrev':
2546 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2549 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2552 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2555 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2558 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2560 case 'localmonthname':
2561 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2563 case 'localmonthnamegen':
2564 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2566 case 'localmonthabbrev':
2567 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2570 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2573 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2576 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2579 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2581 case 'fullpagename':
2582 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2584 case 'fullpagenamee':
2585 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2588 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2590 case 'subpagenamee':
2591 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2593 case 'rootpagename':
2594 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2596 case 'rootpagenamee':
2597 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2600 $this->mTitle
->getRootText()
2603 case 'basepagename':
2604 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2606 case 'basepagenamee':
2607 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2610 $this->mTitle
->getBaseText()
2613 case 'talkpagename':
2614 if ( $this->mTitle
->canTalk() ) {
2615 $talkPage = $this->mTitle
->getTalkPage();
2616 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2621 case 'talkpagenamee':
2622 if ( $this->mTitle
->canTalk() ) {
2623 $talkPage = $this->mTitle
->getTalkPage();
2624 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2629 case 'subjectpagename':
2630 $subjPage = $this->mTitle
->getSubjectPage();
2631 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2633 case 'subjectpagenamee':
2634 $subjPage = $this->mTitle
->getSubjectPage();
2635 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2637 case 'pageid': // requested in T25427
2638 $pageid = $this->getTitle()->getArticleID();
2639 if ( $pageid == 0 ) {
2640 # 0 means the page doesn't exist in the database,
2641 # which means the user is previewing a new page.
2642 # The vary-revision flag must be set, because the magic word
2643 # will have a different value once the page is saved.
2644 $this->mOutput
->setFlag( 'vary-revision' );
2645 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2647 $value = $pageid ?
$pageid : null;
2650 # Let the edit saving system know we should parse the page
2651 # *after* a revision ID has been assigned.
2652 $this->mOutput
->setFlag( 'vary-revision-id' );
2653 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2654 $value = $this->mRevisionId
;
2655 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2656 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2657 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2661 # Let the edit saving system know we should parse the page
2662 # *after* a revision ID has been assigned. This is for null edits.
2663 $this->mOutput
->setFlag( 'vary-revision' );
2664 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2665 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2667 case 'revisionday2':
2668 # Let the edit saving system know we should parse the page
2669 # *after* a revision ID has been assigned. This is for null edits.
2670 $this->mOutput
->setFlag( 'vary-revision' );
2671 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2672 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2674 case 'revisionmonth':
2675 # Let the edit saving system know we should parse the page
2676 # *after* a revision ID has been assigned. This is for null edits.
2677 $this->mOutput
->setFlag( 'vary-revision' );
2678 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2679 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2681 case 'revisionmonth1':
2682 # Let the edit saving system know we should parse the page
2683 # *after* a revision ID has been assigned. This is for null edits.
2684 $this->mOutput
->setFlag( 'vary-revision' );
2685 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2686 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2688 case 'revisionyear':
2689 # Let the edit saving system know we should parse the page
2690 # *after* a revision ID has been assigned. This is for null edits.
2691 $this->mOutput
->setFlag( 'vary-revision' );
2692 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2693 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2695 case 'revisiontimestamp':
2696 # Let the edit saving system know we should parse the page
2697 # *after* a revision ID has been assigned. This is for null edits.
2698 $this->mOutput
->setFlag( 'vary-revision' );
2699 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2700 $value = $this->getRevisionTimestamp();
2702 case 'revisionuser':
2703 # Let the edit saving system know we should parse the page
2704 # *after* a revision ID has been assigned for null edits.
2705 $this->mOutput
->setFlag( 'vary-user' );
2706 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2707 $value = $this->getRevisionUser();
2709 case 'revisionsize':
2710 $value = $this->getRevisionSize();
2713 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2716 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2718 case 'namespacenumber':
2719 $value = $this->mTitle
->getNamespace();
2722 $value = $this->mTitle
->canTalk()
2723 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2727 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2729 case 'subjectspace':
2730 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2732 case 'subjectspacee':
2733 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2735 case 'currentdayname':
2736 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2739 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2742 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2745 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2748 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2749 # int to remove the padding
2750 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2753 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2755 case 'localdayname':
2756 $value = $pageLang->getWeekdayName(
2757 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2761 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2764 $value = $pageLang->time(
2765 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2771 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2774 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2775 # int to remove the padding
2776 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2779 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2781 case 'numberofarticles':
2782 $value = $pageLang->formatNum( SiteStats
::articles() );
2784 case 'numberoffiles':
2785 $value = $pageLang->formatNum( SiteStats
::images() );
2787 case 'numberofusers':
2788 $value = $pageLang->formatNum( SiteStats
::users() );
2790 case 'numberofactiveusers':
2791 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2793 case 'numberofpages':
2794 $value = $pageLang->formatNum( SiteStats
::pages() );
2796 case 'numberofadmins':
2797 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2799 case 'numberofedits':
2800 $value = $pageLang->formatNum( SiteStats
::edits() );
2802 case 'currenttimestamp':
2803 $value = wfTimestamp( TS_MW
, $ts );
2805 case 'localtimestamp':
2806 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2808 case 'currentversion':
2809 $value = SpecialVersion
::getVersion();
2812 return $wgArticlePath;
2818 return $wgServerName;
2820 return $wgScriptPath;
2822 return $wgStylePath;
2823 case 'directionmark':
2824 return $pageLang->getDirMark();
2825 case 'contentlanguage':
2826 global $wgLanguageCode;
2827 return $wgLanguageCode;
2828 case 'pagelanguage':
2829 $value = $pageLang->getCode();
2831 case 'cascadingsources':
2832 $value = CoreParserFunctions
::cascadingsources( $this );
2837 'ParserGetVariableValueSwitch',
2838 [ &$parser, &$this->mVarCache
, &$index, &$ret, &$frame ]
2845 $this->mVarCache
[$index] = $value;
2852 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2856 public function initialiseVariables() {
2857 $variableIDs = MagicWord
::getVariableIDs();
2858 $substIDs = MagicWord
::getSubstIDs();
2860 $this->mVariables
= new MagicWordArray( $variableIDs );
2861 $this->mSubstWords
= new MagicWordArray( $substIDs );
2865 * Preprocess some wikitext and return the document tree.
2866 * This is the ghost of replace_variables().
2868 * @param string $text The text to parse
2869 * @param int $flags Bitwise combination of:
2870 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2871 * included. Default is to assume a direct page view.
2873 * The generated DOM tree must depend only on the input text and the flags.
2874 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2876 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2877 * change in the DOM tree for a given text, must be passed through the section identifier
2878 * in the section edit link and thus back to extractSections().
2880 * The output of this function is currently only cached in process memory, but a persistent
2881 * cache may be implemented at a later date which takes further advantage of these strict
2882 * dependency requirements.
2886 public function preprocessToDom( $text, $flags = 0 ) {
2887 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2892 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2898 public static function splitWhitespace( $s ) {
2899 $ltrimmed = ltrim( $s );
2900 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2901 $trimmed = rtrim( $ltrimmed );
2902 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2904 $w2 = substr( $ltrimmed, -$diff );
2908 return [ $w1, $trimmed, $w2 ];
2912 * Replace magic variables, templates, and template arguments
2913 * with the appropriate text. Templates are substituted recursively,
2914 * taking care to avoid infinite loops.
2916 * Note that the substitution depends on value of $mOutputType:
2917 * self::OT_WIKI: only {{subst:}} templates
2918 * self::OT_PREPROCESS: templates but not extension tags
2919 * self::OT_HTML: all templates and extension tags
2921 * @param string $text The text to transform
2922 * @param bool|PPFrame $frame Object describing the arguments passed to the
2923 * template. Arguments may also be provided as an associative array, as
2924 * was the usual case before MW1.12. Providing arguments this way may be
2925 * useful for extensions wishing to perform variable replacement
2927 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2928 * double-brace expansion.
2931 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2932 # Is there any text? Also, Prevent too big inclusions!
2933 $textSize = strlen( $text );
2934 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2938 if ( $frame === false ) {
2939 $frame = $this->getPreprocessor()->newFrame();
2940 } elseif ( !( $frame instanceof PPFrame
) ) {
2941 wfDebug( __METHOD__
. " called using plain parameters instead of "
2942 . "a PPFrame instance. Creating custom frame.\n" );
2943 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2946 $dom = $this->preprocessToDom( $text );
2947 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2948 $text = $frame->expand( $dom, $flags );
2954 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2956 * @param array $args
2960 public static function createAssocArgs( $args ) {
2963 foreach ( $args as $arg ) {
2964 $eqpos = strpos( $arg, '=' );
2965 if ( $eqpos === false ) {
2966 $assocArgs[$index++
] = $arg;
2968 $name = trim( substr( $arg, 0, $eqpos ) );
2969 $value = trim( substr( $arg, $eqpos +
1 ) );
2970 if ( $value === false ) {
2973 if ( $name !== false ) {
2974 $assocArgs[$name] = $value;
2983 * Warn the user when a parser limitation is reached
2984 * Will warn at most once the user per limitation type
2986 * The results are shown during preview and run through the Parser (See EditPage.php)
2988 * @param string $limitationType Should be one of:
2989 * 'expensive-parserfunction' (corresponding messages:
2990 * 'expensive-parserfunction-warning',
2991 * 'expensive-parserfunction-category')
2992 * 'post-expand-template-argument' (corresponding messages:
2993 * 'post-expand-template-argument-warning',
2994 * 'post-expand-template-argument-category')
2995 * 'post-expand-template-inclusion' (corresponding messages:
2996 * 'post-expand-template-inclusion-warning',
2997 * 'post-expand-template-inclusion-category')
2998 * 'node-count-exceeded' (corresponding messages:
2999 * 'node-count-exceeded-warning',
3000 * 'node-count-exceeded-category')
3001 * 'expansion-depth-exceeded' (corresponding messages:
3002 * 'expansion-depth-exceeded-warning',
3003 * 'expansion-depth-exceeded-category')
3004 * @param string|int|null $current Current value
3005 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3006 * exceeded, provide the values (optional)
3008 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3009 # does no harm if $current and $max are present but are unnecessary for the message
3010 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3011 # only during preview, and that would split the parser cache unnecessarily.
3012 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3014 $this->mOutput
->addWarning( $warning );
3015 $this->addTrackingCategory( "$limitationType-category" );
3019 * Return the text of a template, after recursively
3020 * replacing any variables or templates within the template.
3022 * @param array $piece The parts of the template
3023 * $piece['title']: the title, i.e. the part before the |
3024 * $piece['parts']: the parameter array
3025 * $piece['lineStart']: whether the brace was at the start of a line
3026 * @param PPFrame $frame The current frame, contains template arguments
3028 * @return string The text of the template
3030 public function braceSubstitution( $piece, $frame ) {
3033 // $text has been filled
3035 // wiki markup in $text should be escaped
3037 // $text is HTML, armour it against wikitext transformation
3039 // Force interwiki transclusion to be done in raw mode not rendered
3040 $forceRawInterwiki = false;
3041 // $text is a DOM node needing expansion in a child frame
3042 $isChildObj = false;
3043 // $text is a DOM node needing expansion in the current frame
3044 $isLocalObj = false;
3046 # Title object, where $text came from
3049 # $part1 is the bit before the first |, and must contain only title characters.
3050 # Various prefixes will be stripped from it later.
3051 $titleWithSpaces = $frame->expand( $piece['title'] );
3052 $part1 = trim( $titleWithSpaces );
3055 # Original title text preserved for various purposes
3056 $originalTitle = $part1;
3058 # $args is a list of argument nodes, starting from index 0, not including $part1
3059 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3060 # below won't work b/c this $args isn't an object
3061 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3063 $profileSection = null; // profile templates
3067 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3069 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3070 # Decide whether to expand template or keep wikitext as-is.
3071 if ( $this->ot
['wiki'] ) {
3072 if ( $substMatch === false ) {
3073 $literal = true; # literal when in PST with no prefix
3075 $literal = false; # expand when in PST with subst: or safesubst:
3078 if ( $substMatch == 'subst' ) {
3079 $literal = true; # literal when not in PST with plain subst:
3081 $literal = false; # expand when not in PST with safesubst: or no prefix
3085 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3092 if ( !$found && $args->getLength() == 0 ) {
3093 $id = $this->mVariables
->matchStartToEnd( $part1 );
3094 if ( $id !== false ) {
3095 $text = $this->getVariableValue( $id, $frame );
3096 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3097 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3103 # MSG, MSGNW and RAW
3106 $mwMsgnw = MagicWord
::get( 'msgnw' );
3107 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3110 # Remove obsolete MSG:
3111 $mwMsg = MagicWord
::get( 'msg' );
3112 $mwMsg->matchStartAndRemove( $part1 );
3116 $mwRaw = MagicWord
::get( 'raw' );
3117 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3118 $forceRawInterwiki = true;
3124 $colonPos = strpos( $part1, ':' );
3125 if ( $colonPos !== false ) {
3126 $func = substr( $part1, 0, $colonPos );
3127 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3128 $argsLength = $args->getLength();
3129 for ( $i = 0; $i < $argsLength; $i++
) {
3130 $funcArgs[] = $args->item( $i );
3133 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3134 } catch ( Exception
$ex ) {
3138 # The interface for parser functions allows for extracting
3139 # flags into the local scope. Extract any forwarded flags
3145 # Finish mangling title and then check for loops.
3146 # Set $title to a Title object and $titleText to the PDBK
3149 # Split the title into page and subpage
3151 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3152 if ( $part1 !== $relative ) {
3154 $ns = $this->mTitle
->getNamespace();
3156 $title = Title
::newFromText( $part1, $ns );
3158 $titleText = $title->getPrefixedText();
3159 # Check for language variants if the template is not found
3160 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3161 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3163 # Do recursion depth check
3164 $limit = $this->mOptions
->getMaxTemplateDepth();
3165 if ( $frame->depth
>= $limit ) {
3167 $text = '<span class="error">'
3168 . wfMessage( 'parser-template-recursion-depth-warning' )
3169 ->numParams( $limit )->inContentLanguage()->text()
3175 # Load from database
3176 if ( !$found && $title ) {
3177 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3178 if ( !$title->isExternal() ) {
3179 if ( $title->isSpecialPage()
3180 && $this->mOptions
->getAllowSpecialInclusion()
3181 && $this->ot
['html']
3183 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3184 // Pass the template arguments as URL parameters.
3185 // "uselang" will have no effect since the Language object
3186 // is forced to the one defined in ParserOptions.
3188 $argsLength = $args->getLength();
3189 for ( $i = 0; $i < $argsLength; $i++
) {
3190 $bits = $args->item( $i )->splitArg();
3191 if ( strval( $bits['index'] ) === '' ) {
3192 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3193 $value = trim( $frame->expand( $bits['value'] ) );
3194 $pageArgs[$name] = $value;
3198 // Create a new context to execute the special page
3199 $context = new RequestContext
;
3200 $context->setTitle( $title );
3201 $context->setRequest( new FauxRequest( $pageArgs ) );
3202 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3203 $context->setUser( $this->getUser() );
3205 // If this page is cached, then we better not be per user.
3206 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3208 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3209 $ret = SpecialPageFactory
::capturePath(
3210 $title, $context, $this->getLinkRenderer() );
3212 $text = $context->getOutput()->getHTML();
3213 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3216 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3217 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3218 $specialPage->maxIncludeCacheTime()
3222 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3223 $found = false; # access denied
3224 wfDebug( __METHOD__
. ": template inclusion denied for " .
3225 $title->getPrefixedDBkey() . "\n" );
3227 list( $text, $title ) = $this->getTemplateDom( $title );
3228 if ( $text !== false ) {
3234 # If the title is valid but undisplayable, make a link to it
3235 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3236 $text = "[[:$titleText]]";
3239 } elseif ( $title->isTrans() ) {
3240 # Interwiki transclusion
3241 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3242 $text = $this->interwikiTransclude( $title, 'render' );
3245 $text = $this->interwikiTransclude( $title, 'raw' );
3246 # Preprocess it like a template
3247 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3253 # Do infinite loop check
3254 # This has to be done after redirect resolution to avoid infinite loops via redirects
3255 if ( !$frame->loopCheck( $title ) ) {
3257 $text = '<span class="error">'
3258 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3260 $this->addTrackingCategory( 'template-loop-category' );
3261 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3265 # If we haven't found text to substitute by now, we're done
3266 # Recover the source wikitext and return it
3268 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3269 if ( $profileSection ) {
3270 $this->mProfiler
->scopedProfileOut( $profileSection );
3272 return [ 'object' => $text ];
3275 # Expand DOM-style return values in a child frame
3276 if ( $isChildObj ) {
3277 # Clean up argument array
3278 $newFrame = $frame->newChild( $args, $title );
3281 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3282 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3283 # Expansion is eligible for the empty-frame cache
3284 $text = $newFrame->cachedExpand( $titleText, $text );
3286 # Uncached expansion
3287 $text = $newFrame->expand( $text );
3290 if ( $isLocalObj && $nowiki ) {
3291 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3292 $isLocalObj = false;
3295 if ( $profileSection ) {
3296 $this->mProfiler
->scopedProfileOut( $profileSection );
3299 # Replace raw HTML by a placeholder
3301 $text = $this->insertStripItem( $text );
3302 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3303 # Escape nowiki-style return values
3304 $text = wfEscapeWikiText( $text );
3305 } elseif ( is_string( $text )
3306 && !$piece['lineStart']
3307 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3309 # T2529: if the template begins with a table or block-level
3310 # element, it should be treated as beginning a new line.
3311 # This behavior is somewhat controversial.
3312 $text = "\n" . $text;
3315 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3316 # Error, oversize inclusion
3317 if ( $titleText !== false ) {
3318 # Make a working, properly escaped link if possible (T25588)
3319 $text = "[[:$titleText]]";
3321 # This will probably not be a working link, but at least it may
3322 # provide some hint of where the problem is
3323 preg_replace( '/^:/', '', $originalTitle );
3324 $text = "[[:$originalTitle]]";
3326 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3327 . 'post-expand include size too large -->' );
3328 $this->limitationWarn( 'post-expand-template-inclusion' );
3331 if ( $isLocalObj ) {
3332 $ret = [ 'object' => $text ];
3334 $ret = [ 'text' => $text ];
3341 * Call a parser function and return an array with text and flags.
3343 * The returned array will always contain a boolean 'found', indicating
3344 * whether the parser function was found or not. It may also contain the
3346 * text: string|object, resulting wikitext or PP DOM object
3347 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3348 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3349 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3350 * nowiki: bool, wiki markup in $text should be escaped
3353 * @param PPFrame $frame The current frame, contains template arguments
3354 * @param string $function Function name
3355 * @param array $args Arguments to the function
3356 * @throws MWException
3359 public function callParserFunction( $frame, $function, array $args = [] ) {
3362 # Case sensitive functions
3363 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3364 $function = $this->mFunctionSynonyms
[1][$function];
3366 # Case insensitive functions
3367 $function = $wgContLang->lc( $function );
3368 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3369 $function = $this->mFunctionSynonyms
[0][$function];
3371 return [ 'found' => false ];
3375 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3377 // Avoid PHP 7.1 warning from passing $this by reference
3380 $allArgs = [ &$parser ];
3381 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3382 # Convert arguments to PPNodes and collect for appending to $allArgs
3384 foreach ( $args as $k => $v ) {
3385 if ( $v instanceof PPNode ||
$k === 0 ) {
3388 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3392 # Add a frame parameter, and pass the arguments as an array
3393 $allArgs[] = $frame;
3394 $allArgs[] = $funcArgs;
3396 # Convert arguments to plain text and append to $allArgs
3397 foreach ( $args as $k => $v ) {
3398 if ( $v instanceof PPNode
) {
3399 $allArgs[] = trim( $frame->expand( $v ) );
3400 } elseif ( is_int( $k ) && $k >= 0 ) {
3401 $allArgs[] = trim( $v );
3403 $allArgs[] = trim( "$k=$v" );
3408 $result = call_user_func_array( $callback, $allArgs );
3410 # The interface for function hooks allows them to return a wikitext
3411 # string or an array containing the string and any flags. This mungs
3412 # things around to match what this method should return.
3413 if ( !is_array( $result ) ) {
3419 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3420 $result['text'] = $result[0];
3422 unset( $result[0] );
3429 $preprocessFlags = 0;
3430 if ( isset( $result['noparse'] ) ) {
3431 $noparse = $result['noparse'];
3433 if ( isset( $result['preprocessFlags'] ) ) {
3434 $preprocessFlags = $result['preprocessFlags'];
3438 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3439 $result['isChildObj'] = true;
3446 * Get the semi-parsed DOM representation of a template with a given title,
3447 * and its redirect destination title. Cached.
3449 * @param Title $title
3453 public function getTemplateDom( $title ) {
3454 $cacheTitle = $title;
3455 $titleText = $title->getPrefixedDBkey();
3457 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3458 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3459 $title = Title
::makeTitle( $ns, $dbk );
3460 $titleText = $title->getPrefixedDBkey();
3462 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3463 return [ $this->mTplDomCache
[$titleText], $title ];
3466 # Cache miss, go to the database
3467 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3469 if ( $text === false ) {
3470 $this->mTplDomCache
[$titleText] = false;
3471 return [ false, $title ];
3474 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3475 $this->mTplDomCache
[$titleText] = $dom;
3477 if ( !$title->equals( $cacheTitle ) ) {
3478 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3479 [ $title->getNamespace(), $title->getDBkey() ];
3482 return [ $dom, $title ];
3486 * Fetch the current revision of a given title. Note that the revision
3487 * (and even the title) may not exist in the database, so everything
3488 * contributing to the output of the parser should use this method
3489 * where possible, rather than getting the revisions themselves. This
3490 * method also caches its results, so using it benefits performance.
3493 * @param Title $title
3496 public function fetchCurrentRevisionOfTitle( $title ) {
3497 $cacheKey = $title->getPrefixedDBkey();
3498 if ( !$this->currentRevisionCache
) {
3499 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3501 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3502 $this->currentRevisionCache
->set( $cacheKey,
3503 // Defaults to Parser::statelessFetchRevision()
3504 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3507 return $this->currentRevisionCache
->get( $cacheKey );
3511 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3512 * without passing them on to it.
3515 * @param Title $title
3516 * @param Parser|bool $parser
3517 * @return Revision|bool False if missing
3519 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3520 $pageId = $title->getArticleID();
3521 $revId = $title->getLatestRevID();
3523 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $pageId, $revId );
3525 $rev->setTitle( $title );
3532 * Fetch the unparsed text of a template and register a reference to it.
3533 * @param Title $title
3534 * @return array ( string or false, Title )
3536 public function fetchTemplateAndTitle( $title ) {
3537 // Defaults to Parser::statelessFetchTemplate()
3538 $templateCb = $this->mOptions
->getTemplateCallback();
3539 $stuff = call_user_func( $templateCb, $title, $this );
3540 // We use U+007F DELETE to distinguish strip markers from regular text.
3541 $text = $stuff['text'];
3542 if ( is_string( $stuff['text'] ) ) {
3543 $text = strtr( $text, "\x7f", "?" );
3545 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3546 if ( isset( $stuff['deps'] ) ) {
3547 foreach ( $stuff['deps'] as $dep ) {
3548 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3549 if ( $dep['title']->equals( $this->getTitle() ) ) {
3550 // If we transclude ourselves, the final result
3551 // will change based on the new version of the page
3552 $this->mOutput
->setFlag( 'vary-revision' );
3556 return [ $text, $finalTitle ];
3560 * Fetch the unparsed text of a template and register a reference to it.
3561 * @param Title $title
3562 * @return string|bool
3564 public function fetchTemplate( $title ) {
3565 return $this->fetchTemplateAndTitle( $title )[0];
3569 * Static function to get a template
3570 * Can be overridden via ParserOptions::setTemplateCallback().
3572 * @param Title $title
3573 * @param bool|Parser $parser
3577 public static function statelessFetchTemplate( $title, $parser = false ) {
3578 $text = $skip = false;
3579 $finalTitle = $title;
3582 # Loop to fetch the article, with up to 1 redirect
3583 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3584 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3585 // @codingStandardsIgnoreEnd
3586 # Give extensions a chance to select the revision instead
3587 $id = false; # Assume current
3588 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3589 [ $parser, $title, &$skip, &$id ] );
3595 'page_id' => $title->getArticleID(),
3602 $rev = Revision
::newFromId( $id );
3603 } elseif ( $parser ) {
3604 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3606 $rev = Revision
::newFromTitle( $title );
3608 $rev_id = $rev ?
$rev->getId() : 0;
3609 # If there is no current revision, there is no page
3610 if ( $id === false && !$rev ) {
3611 $linkCache = LinkCache
::singleton();
3612 $linkCache->addBadLinkObj( $title );
3617 'page_id' => $title->getArticleID(),
3618 'rev_id' => $rev_id ];
3619 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3620 # We fetched a rev from a different title; register it too...
3622 'title' => $rev->getTitle(),
3623 'page_id' => $rev->getPage(),
3624 'rev_id' => $rev_id ];
3628 $content = $rev->getContent();
3629 $text = $content ?
$content->getWikitextForTransclusion() : null;
3631 Hooks
::run( 'ParserFetchTemplate',
3632 [ $parser, $title, $rev, &$text, &$deps ] );
3634 if ( $text === false ||
$text === null ) {
3638 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3640 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3641 if ( !$message->exists() ) {
3645 $content = $message->content();
3646 $text = $message->plain();
3654 $finalTitle = $title;
3655 $title = $content->getRedirectTarget();
3659 'finalTitle' => $finalTitle,
3664 * Fetch a file and its title and register a reference to it.
3665 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3666 * @param Title $title
3667 * @param array $options Array of options to RepoGroup::findFile
3670 public function fetchFile( $title, $options = [] ) {
3671 return $this->fetchFileAndTitle( $title, $options )[0];
3675 * Fetch a file and its title and register a reference to it.
3676 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3677 * @param Title $title
3678 * @param array $options Array of options to RepoGroup::findFile
3679 * @return array ( File or false, Title of file )
3681 public function fetchFileAndTitle( $title, $options = [] ) {
3682 $file = $this->fetchFileNoRegister( $title, $options );
3684 $time = $file ?
$file->getTimestamp() : false;
3685 $sha1 = $file ?
$file->getSha1() : false;
3686 # Register the file as a dependency...
3687 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3688 if ( $file && !$title->equals( $file->getTitle() ) ) {
3689 # Update fetched file title
3690 $title = $file->getTitle();
3691 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3693 return [ $file, $title ];
3697 * Helper function for fetchFileAndTitle.
3699 * Also useful if you need to fetch a file but not use it yet,
3700 * for example to get the file's handler.
3702 * @param Title $title
3703 * @param array $options Array of options to RepoGroup::findFile
3706 protected function fetchFileNoRegister( $title, $options = [] ) {
3707 if ( isset( $options['broken'] ) ) {
3708 $file = false; // broken thumbnail forced by hook
3709 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3710 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3711 } else { // get by (name,timestamp)
3712 $file = wfFindFile( $title, $options );
3718 * Transclude an interwiki link.
3720 * @param Title $title
3721 * @param string $action
3725 public function interwikiTransclude( $title, $action ) {
3726 global $wgEnableScaryTranscluding;
3728 if ( !$wgEnableScaryTranscluding ) {
3729 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3732 $url = $title->getFullURL( [ 'action' => $action ] );
3734 if ( strlen( $url ) > 255 ) {
3735 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3737 return $this->fetchScaryTemplateMaybeFromCache( $url );
3741 * @param string $url
3742 * @return mixed|string
3744 public function fetchScaryTemplateMaybeFromCache( $url ) {
3745 global $wgTranscludeCacheExpiry;
3746 $dbr = wfGetDB( DB_REPLICA
);
3747 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3748 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3749 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3751 return $obj->tc_contents
;
3754 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3755 $status = $req->execute(); // Status object
3756 if ( $status->isOK() ) {
3757 $text = $req->getContent();
3758 } elseif ( $req->getStatus() != 200 ) {
3759 // Though we failed to fetch the content, this status is useless.
3760 return wfMessage( 'scarytranscludefailed-httpstatus' )
3761 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3763 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3766 $dbw = wfGetDB( DB_MASTER
);
3767 $dbw->replace( 'transcache', [ 'tc_url' ], [
3769 'tc_time' => $dbw->timestamp( time() ),
3770 'tc_contents' => $text
3776 * Triple brace replacement -- used for template arguments
3779 * @param array $piece
3780 * @param PPFrame $frame
3784 public function argSubstitution( $piece, $frame ) {
3786 $parts = $piece['parts'];
3787 $nameWithSpaces = $frame->expand( $piece['title'] );
3788 $argName = trim( $nameWithSpaces );
3790 $text = $frame->getArgument( $argName );
3791 if ( $text === false && $parts->getLength() > 0
3792 && ( $this->ot
['html']
3794 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3797 # No match in frame, use the supplied default
3798 $object = $parts->item( 0 )->getChildren();
3800 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3801 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3802 $this->limitationWarn( 'post-expand-template-argument' );
3805 if ( $text === false && $object === false ) {
3807 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3809 if ( $error !== false ) {
3812 if ( $object !== false ) {
3813 $ret = [ 'object' => $object ];
3815 $ret = [ 'text' => $text ];
3822 * Return the text to be used for a given extension tag.
3823 * This is the ghost of strip().
3825 * @param array $params Associative array of parameters:
3826 * name PPNode for the tag name
3827 * attr PPNode for unparsed text where tag attributes are thought to be
3828 * attributes Optional associative array of parsed attributes
3829 * inner Contents of extension element
3830 * noClose Original text did not have a close tag
3831 * @param PPFrame $frame
3833 * @throws MWException
3836 public function extensionSubstitution( $params, $frame ) {
3837 static $errorStr = '<span class="error">';
3838 static $errorLen = 20;
3840 $name = $frame->expand( $params['name'] );
3841 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3842 // Probably expansion depth or node count exceeded. Just punt the
3847 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3848 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3853 // We can't safely check if the expansion for $content resulted in an
3854 // error, because the content could happen to be the error string
3856 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3858 $marker = self
::MARKER_PREFIX
. "-$name-"
3859 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3861 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3862 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3863 if ( $isFunctionTag ) {
3864 $markerType = 'none';
3866 $markerType = 'general';
3868 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3869 $name = strtolower( $name );
3870 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3871 if ( isset( $params['attributes'] ) ) {
3872 $attributes = $attributes +
$params['attributes'];
3875 if ( isset( $this->mTagHooks
[$name] ) ) {
3876 $output = call_user_func_array( $this->mTagHooks
[$name],
3877 [ $content, $attributes, $this, $frame ] );
3878 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3879 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3881 // Avoid PHP 7.1 warning from passing $this by reference
3883 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3885 $output = '<span class="error">Invalid tag extension name: ' .
3886 htmlspecialchars( $name ) . '</span>';
3889 if ( is_array( $output ) ) {
3890 # Extract flags to local scope (to override $markerType)
3892 $output = $flags[0];
3897 if ( is_null( $attrText ) ) {
3900 if ( isset( $params['attributes'] ) ) {
3901 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3902 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3903 htmlspecialchars( $attrValue ) . '"';
3906 if ( $content === null ) {
3907 $output = "<$name$attrText/>";
3909 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3910 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3914 $output = "<$name$attrText>$content$close";
3918 if ( $markerType === 'none' ) {
3920 } elseif ( $markerType === 'nowiki' ) {
3921 $this->mStripState
->addNoWiki( $marker, $output );
3922 } elseif ( $markerType === 'general' ) {
3923 $this->mStripState
->addGeneral( $marker, $output );
3925 throw new MWException( __METHOD__
. ': invalid marker type' );
3931 * Increment an include size counter
3933 * @param string $type The type of expansion
3934 * @param int $size The size of the text
3935 * @return bool False if this inclusion would take it over the maximum, true otherwise
3937 public function incrementIncludeSize( $type, $size ) {
3938 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3941 $this->mIncludeSizes
[$type] +
= $size;
3947 * Increment the expensive function count
3949 * @return bool False if the limit has been exceeded
3951 public function incrementExpensiveFunctionCount() {
3952 $this->mExpensiveFunctionCount++
;
3953 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3957 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3958 * Fills $this->mDoubleUnderscores, returns the modified text
3960 * @param string $text
3964 public function doDoubleUnderscore( $text ) {
3965 # The position of __TOC__ needs to be recorded
3966 $mw = MagicWord
::get( 'toc' );
3967 if ( $mw->match( $text ) ) {
3968 $this->mShowToc
= true;
3969 $this->mForceTocPosition
= true;
3971 # Set a placeholder. At the end we'll fill it in with the TOC.
3972 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3974 # Only keep the first one.
3975 $text = $mw->replace( '', $text );
3978 # Now match and remove the rest of them
3979 $mwa = MagicWord
::getDoubleUnderscoreArray();
3980 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3982 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3983 $this->mOutput
->mNoGallery
= true;
3985 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3986 $this->mShowToc
= false;
3988 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
3989 && $this->mTitle
->getNamespace() == NS_CATEGORY
3991 $this->addTrackingCategory( 'hidden-category-category' );
3993 # (T10068) Allow control over whether robots index a page.
3994 # __INDEX__ always overrides __NOINDEX__, see T16899
3995 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3996 $this->mOutput
->setIndexPolicy( 'noindex' );
3997 $this->addTrackingCategory( 'noindex-category' );
3999 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4000 $this->mOutput
->setIndexPolicy( 'index' );
4001 $this->addTrackingCategory( 'index-category' );
4004 # Cache all double underscores in the database
4005 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4006 $this->mOutput
->setProperty( $key, '' );
4013 * @see ParserOutput::addTrackingCategory()
4014 * @param string $msg Message key
4015 * @return bool Whether the addition was successful
4017 public function addTrackingCategory( $msg ) {
4018 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4022 * This function accomplishes several tasks:
4023 * 1) Auto-number headings if that option is enabled
4024 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4025 * 3) Add a Table of contents on the top for users who have enabled the option
4026 * 4) Auto-anchor headings
4028 * It loops through all headlines, collects the necessary data, then splits up the
4029 * string and re-inserts the newly formatted headlines.
4031 * @param string $text
4032 * @param string $origText Original, untouched wikitext
4033 * @param bool $isMain
4034 * @return mixed|string
4037 public function formatHeadings( $text, $origText, $isMain = true ) {
4038 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4040 # Inhibit editsection links if requested in the page
4041 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4042 $maybeShowEditLink = $showEditLink = false;
4044 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4045 $showEditLink = $this->mOptions
->getEditSection();
4047 if ( $showEditLink ) {
4048 $this->mOutput
->setEditSectionTokens( true );
4051 # Get all headlines for numbering them and adding funky stuff like [edit]
4052 # links - this is for later, but we need the number of headlines right now
4054 $numMatches = preg_match_all(
4055 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4060 # if there are fewer than 4 headlines in the article, do not show TOC
4061 # unless it's been explicitly enabled.
4062 $enoughToc = $this->mShowToc
&&
4063 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4065 # Allow user to stipulate that a page should have a "new section"
4066 # link added via __NEWSECTIONLINK__
4067 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4068 $this->mOutput
->setNewSection( true );
4071 # Allow user to remove the "new section"
4072 # link via __NONEWSECTIONLINK__
4073 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4074 $this->mOutput
->hideNewSection( true );
4077 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4078 # override above conditions and always show TOC above first header
4079 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4080 $this->mShowToc
= true;
4088 # Ugh .. the TOC should have neat indentation levels which can be
4089 # passed to the skin functions. These are determined here
4093 $sublevelCount = [];
4099 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4100 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4101 $oldType = $this->mOutputType
;
4102 $this->setOutputType( self
::OT_WIKI
);
4103 $frame = $this->getPreprocessor()->newFrame();
4104 $root = $this->preprocessToDom( $origText );
4105 $node = $root->getFirstChild();
4110 $headlines = $numMatches !== false ?
$matches[3] : [];
4112 foreach ( $headlines as $headline ) {
4113 $isTemplate = false;
4115 $sectionIndex = false;
4117 $markerMatches = [];
4118 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4119 $serial = $markerMatches[1];
4120 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4121 $isTemplate = ( $titleText != $baseTitleText );
4122 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4126 $prevlevel = $level;
4128 $level = $matches[1][$headlineCount];
4130 if ( $level > $prevlevel ) {
4131 # Increase TOC level
4133 $sublevelCount[$toclevel] = 0;
4134 if ( $toclevel < $wgMaxTocLevel ) {
4135 $prevtoclevel = $toclevel;
4136 $toc .= Linker
::tocIndent();
4139 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4140 # Decrease TOC level, find level to jump to
4142 for ( $i = $toclevel; $i > 0; $i-- ) {
4143 if ( $levelCount[$i] == $level ) {
4144 # Found last matching level
4147 } elseif ( $levelCount[$i] < $level ) {
4148 # Found first matching level below current level
4156 if ( $toclevel < $wgMaxTocLevel ) {
4157 if ( $prevtoclevel < $wgMaxTocLevel ) {
4158 # Unindent only if the previous toc level was shown :p
4159 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4160 $prevtoclevel = $toclevel;
4162 $toc .= Linker
::tocLineEnd();
4166 # No change in level, end TOC line
4167 if ( $toclevel < $wgMaxTocLevel ) {
4168 $toc .= Linker
::tocLineEnd();
4172 $levelCount[$toclevel] = $level;
4174 # count number of headlines for each level
4175 $sublevelCount[$toclevel]++
;
4177 for ( $i = 1; $i <= $toclevel; $i++
) {
4178 if ( !empty( $sublevelCount[$i] ) ) {
4182 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4187 # The safe header is a version of the header text safe to use for links
4189 # Remove link placeholders by the link text.
4190 # <!--LINK number-->
4192 # link text with suffix
4193 # Do this before unstrip since link text can contain strip markers
4194 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4196 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4197 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4199 # Strip out HTML (first regex removes any tag not allowed)
4201 # * <sup> and <sub> (T10393)
4205 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4206 # * <s> and <strike> (T35715)
4207 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4208 # to allow setting directionality in toc items.
4209 $tocline = preg_replace(
4211 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4212 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4218 # Strip '<span></span>', which is the result from the above if
4219 # <span id="foo"></span> is used to produce an additional anchor
4221 $tocline = str_replace( '<span></span>', '', $tocline );
4223 $tocline = trim( $tocline );
4225 # For the anchor, strip out HTML-y stuff period
4226 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4227 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4229 # Save headline for section edit hint before it's escaped
4230 $headlineHint = $safeHeadline;
4232 if ( $wgExperimentalHtmlIds ) {
4233 # For reverse compatibility, provide an id that's
4234 # HTML4-compatible, like we used to.
4235 # It may be worth noting, academically, that it's possible for
4236 # the legacy anchor to conflict with a non-legacy headline
4237 # anchor on the page. In this case likely the "correct" thing
4238 # would be to either drop the legacy anchors or make sure
4239 # they're numbered first. However, this would require people
4240 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4241 # manually, so let's not bother worrying about it.
4242 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4243 [ 'noninitial', 'legacy' ] );
4244 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4246 if ( $legacyHeadline == $safeHeadline ) {
4247 # No reason to have both (in fact, we can't)
4248 $legacyHeadline = false;
4251 $legacyHeadline = false;
4252 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4256 # HTML names must be case-insensitively unique (T12721).
4257 # This does not apply to Unicode characters per
4258 # https://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4259 # @todo FIXME: We may be changing them depending on the current locale.
4260 $arrayKey = strtolower( $safeHeadline );
4261 if ( $legacyHeadline === false ) {
4262 $legacyArrayKey = false;
4264 $legacyArrayKey = strtolower( $legacyHeadline );
4267 # Create the anchor for linking from the TOC to the section
4268 $anchor = $safeHeadline;
4269 $legacyAnchor = $legacyHeadline;
4270 if ( isset( $refers[$arrayKey] ) ) {
4271 // @codingStandardsIgnoreStart
4272 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4273 // @codingStandardsIgnoreEnd
4275 $refers["${arrayKey}_$i"] = true;
4277 $refers[$arrayKey] = true;
4279 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4280 // @codingStandardsIgnoreStart
4281 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4282 // @codingStandardsIgnoreEnd
4283 $legacyAnchor .= "_$i";
4284 $refers["${legacyArrayKey}_$i"] = true;
4286 $refers[$legacyArrayKey] = true;
4289 # Don't number the heading if it is the only one (looks silly)
4290 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4291 # the two are different if the line contains a link
4292 $headline = Html
::element(
4294 [ 'class' => 'mw-headline-number' ],
4296 ) . ' ' . $headline;
4299 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4300 $toc .= Linker
::tocLine( $anchor, $tocline,
4301 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4304 # Add the section to the section tree
4305 # Find the DOM node for this header
4306 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4307 while ( $node && !$noOffset ) {
4308 if ( $node->getName() === 'h' ) {
4309 $bits = $node->splitHeading();
4310 if ( $bits['i'] == $sectionIndex ) {
4314 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4315 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4316 $node = $node->getNextSibling();
4319 'toclevel' => $toclevel,
4322 'number' => $numbering,
4323 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4324 'fromtitle' => $titleText,
4325 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4326 'anchor' => $anchor,
4329 # give headline the correct <h#> tag
4330 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4331 // Output edit section links as markers with styles that can be customized by skins
4332 if ( $isTemplate ) {
4333 # Put a T flag in the section identifier, to indicate to extractSections()
4334 # that sections inside <includeonly> should be counted.
4335 $editsectionPage = $titleText;
4336 $editsectionSection = "T-$sectionIndex";
4337 $editsectionContent = null;
4339 $editsectionPage = $this->mTitle
->getPrefixedText();
4340 $editsectionSection = $sectionIndex;
4341 $editsectionContent = $headlineHint;
4343 // We use a bit of pesudo-xml for editsection markers. The
4344 // language converter is run later on. Using a UNIQ style marker
4345 // leads to the converter screwing up the tokens when it
4346 // converts stuff. And trying to insert strip tags fails too. At
4347 // this point all real inputted tags have already been escaped,
4348 // so we don't have to worry about a user trying to input one of
4349 // these markers directly. We use a page and section attribute
4350 // to stop the language converter from converting these
4351 // important bits of data, but put the headline hint inside a
4352 // content block because the language converter is supposed to
4353 // be able to convert that piece of data.
4354 // Gets replaced with html in ParserOutput::getText
4355 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4356 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4357 if ( $editsectionContent !== null ) {
4358 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4365 $head[$headlineCount] = Linker
::makeHeadline( $level,
4366 $matches['attrib'][$headlineCount], $anchor, $headline,
4367 $editlink, $legacyAnchor );
4372 $this->setOutputType( $oldType );
4374 # Never ever show TOC if no headers
4375 if ( $numVisible < 1 ) {
4380 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4381 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4383 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4384 $this->mOutput
->setTOCHTML( $toc );
4385 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4389 $this->mOutput
->setSections( $tocraw );
4392 # split up and insert constructed headlines
4393 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4396 // build an array of document sections
4398 foreach ( $blocks as $block ) {
4399 // $head is zero-based, sections aren't.
4400 if ( empty( $head[$i - 1] ) ) {
4401 $sections[$i] = $block;
4403 $sections[$i] = $head[$i - 1] . $block;
4407 * Send a hook, one per section.
4408 * The idea here is to be able to make section-level DIVs, but to do so in a
4409 * lower-impact, more correct way than r50769
4412 * $section : the section number
4413 * &$sectionContent : ref to the content of the section
4414 * $showEditLinks : boolean describing whether this section has an edit link
4416 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $showEditLink ] );
4421 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4422 // append the TOC at the beginning
4423 // Top anchor now in skin
4424 $sections[0] = $sections[0] . $toc . "\n";
4427 $full .= implode( '', $sections );
4429 if ( $this->mForceTocPosition
) {
4430 return str_replace( '<!--MWTOC-->', $toc, $full );
4437 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4438 * conversion, substituting signatures, {{subst:}} templates, etc.
4440 * @param string $text The text to transform
4441 * @param Title $title The Title object for the current article
4442 * @param User $user The User object describing the current user
4443 * @param ParserOptions $options Parsing options
4444 * @param bool $clearState Whether to clear the parser state first
4445 * @return string The altered wiki markup
4447 public function preSaveTransform( $text, Title
$title, User
$user,
4448 ParserOptions
$options, $clearState = true
4450 if ( $clearState ) {
4451 $magicScopeVariable = $this->lock();
4453 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4454 $this->setUser( $user );
4456 // Strip U+0000 NULL (T159174)
4457 $text = str_replace( "\000", '', $text );
4459 // We still normalize line endings for backwards-compatibility
4460 // with other code that just calls PST, but this should already
4461 // be handled in TextContent subclasses
4462 $text = TextContent
::normalizeLineEndings( $text );
4464 if ( $options->getPreSaveTransform() ) {
4465 $text = $this->pstPass2( $text, $user );
4467 $text = $this->mStripState
->unstripBoth( $text );
4469 $this->setUser( null ); # Reset
4475 * Pre-save transform helper function
4477 * @param string $text
4482 private function pstPass2( $text, $user ) {
4485 # Note: This is the timestamp saved as hardcoded wikitext to
4486 # the database, we use $wgContLang here in order to give
4487 # everyone the same signature and use the default one rather
4488 # than the one selected in each user's preferences.
4490 $ts = $this->mOptions
->getTimestamp();
4491 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4492 $ts = $timestamp->format( 'YmdHis' );
4493 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4495 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4497 # Variable replacement
4498 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4499 $text = $this->replaceVariables( $text );
4501 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4502 # which may corrupt this parser instance via its wfMessage()->text() call-
4505 $sigText = $this->getUserSig( $user );
4506 $text = strtr( $text, [
4508 '~~~~' => "$sigText $d",
4512 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4513 $tc = '[' . Title
::legalChars() . ']';
4514 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4516 // [[ns:page (context)|]]
4517 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4518 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4519 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4520 // [[ns:page (context), context|]] (using either single or double-width comma)
4521 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4522 // [[|page]] (reverse pipe trick: add context from page title)
4523 $p2 = "/\[\[\\|($tc+)]]/";
4525 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4526 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4527 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4528 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4530 $t = $this->mTitle
->getText();
4532 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4533 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4534 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4535 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4537 # if there's no context, don't bother duplicating the title
4538 $text = preg_replace( $p2, '[[\\1]]', $text );
4545 * Fetch the user's signature text, if any, and normalize to
4546 * validated, ready-to-insert wikitext.
4547 * If you have pre-fetched the nickname or the fancySig option, you can
4548 * specify them here to save a database query.
4549 * Do not reuse this parser instance after calling getUserSig(),
4550 * as it may have changed if it's the $wgParser.
4553 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4554 * @param bool|null $fancySig whether the nicknname is the complete signature
4555 * or null to use default value
4558 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4559 global $wgMaxSigChars;
4561 $username = $user->getName();
4563 # If not given, retrieve from the user object.
4564 if ( $nickname === false ) {
4565 $nickname = $user->getOption( 'nickname' );
4568 if ( is_null( $fancySig ) ) {
4569 $fancySig = $user->getBoolOption( 'fancysig' );
4572 $nickname = $nickname == null ?
$username : $nickname;
4574 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4575 $nickname = $username;
4576 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4577 } elseif ( $fancySig !== false ) {
4578 # Sig. might contain markup; validate this
4579 if ( $this->validateSig( $nickname ) !== false ) {
4580 # Validated; clean up (if needed) and return it
4581 return $this->cleanSig( $nickname, true );
4583 # Failed to validate; fall back to the default
4584 $nickname = $username;
4585 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4589 # Make sure nickname doesnt get a sig in a sig
4590 $nickname = self
::cleanSigInSig( $nickname );
4592 # If we're still here, make it a link to the user page
4593 $userText = wfEscapeWikiText( $username );
4594 $nickText = wfEscapeWikiText( $nickname );
4595 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4597 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4598 ->title( $this->getTitle() )->text();
4602 * Check that the user's signature contains no bad XML
4604 * @param string $text
4605 * @return string|bool An expanded string, or false if invalid.
4607 public function validateSig( $text ) {
4608 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4612 * Clean up signature text
4614 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4615 * 2) Substitute all transclusions
4617 * @param string $text
4618 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4619 * @return string Signature text
4621 public function cleanSig( $text, $parsing = false ) {
4624 $magicScopeVariable = $this->lock();
4625 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4628 # Option to disable this feature
4629 if ( !$this->mOptions
->getCleanSignatures() ) {
4633 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4634 # => Move this logic to braceSubstitution()
4635 $substWord = MagicWord
::get( 'subst' );
4636 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4637 $substText = '{{' . $substWord->getSynonym( 0 );
4639 $text = preg_replace( $substRegex, $substText, $text );
4640 $text = self
::cleanSigInSig( $text );
4641 $dom = $this->preprocessToDom( $text );
4642 $frame = $this->getPreprocessor()->newFrame();
4643 $text = $frame->expand( $dom );
4646 $text = $this->mStripState
->unstripBoth( $text );
4653 * Strip 3, 4 or 5 tildes out of signatures.
4655 * @param string $text
4656 * @return string Signature text with /~{3,5}/ removed
4658 public static function cleanSigInSig( $text ) {
4659 $text = preg_replace( '/~{3,5}/', '', $text );
4664 * Set up some variables which are usually set up in parse()
4665 * so that an external function can call some class members with confidence
4667 * @param Title|null $title
4668 * @param ParserOptions $options
4669 * @param int $outputType
4670 * @param bool $clearState
4672 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4673 $outputType, $clearState = true
4675 $this->startParse( $title, $options, $outputType, $clearState );
4679 * @param Title|null $title
4680 * @param ParserOptions $options
4681 * @param int $outputType
4682 * @param bool $clearState
4684 private function startParse( Title
$title = null, ParserOptions
$options,
4685 $outputType, $clearState = true
4687 $this->setTitle( $title );
4688 $this->mOptions
= $options;
4689 $this->setOutputType( $outputType );
4690 if ( $clearState ) {
4691 $this->clearState();
4696 * Wrapper for preprocess()
4698 * @param string $text The text to preprocess
4699 * @param ParserOptions $options Options
4700 * @param Title|null $title Title object or null to use $wgTitle
4703 public function transformMsg( $text, $options, $title = null ) {
4704 static $executing = false;
4706 # Guard against infinite recursion
4717 $text = $this->preprocess( $text, $title, $options );
4724 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4725 * The callback should have the following form:
4726 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4728 * Transform and return $text. Use $parser for any required context, e.g. use
4729 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4731 * Hooks may return extended information by returning an array, of which the
4732 * first numbered element (index 0) must be the return string, and all other
4733 * entries are extracted into local variables within an internal function
4734 * in the Parser class.
4736 * This interface (introduced r61913) appears to be undocumented, but
4737 * 'markerType' is used by some core tag hooks to override which strip
4738 * array their results are placed in. **Use great caution if attempting
4739 * this interface, as it is not documented and injudicious use could smash
4740 * private variables.**
4742 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4743 * @param callable $callback The callback function (and object) to use for the tag
4744 * @throws MWException
4745 * @return callable|null The old value of the mTagHooks array associated with the hook
4747 public function setHook( $tag, callable
$callback ) {
4748 $tag = strtolower( $tag );
4749 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4750 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4752 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4753 $this->mTagHooks
[$tag] = $callback;
4754 if ( !in_array( $tag, $this->mStripList
) ) {
4755 $this->mStripList
[] = $tag;
4762 * As setHook(), but letting the contents be parsed.
4764 * Transparent tag hooks are like regular XML-style tag hooks, except they
4765 * operate late in the transformation sequence, on HTML instead of wikitext.
4767 * This is probably obsoleted by things dealing with parser frames?
4768 * The only extension currently using it is geoserver.
4771 * @todo better document or deprecate this
4773 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4774 * @param callable $callback The callback function (and object) to use for the tag
4775 * @throws MWException
4776 * @return callable|null The old value of the mTagHooks array associated with the hook
4778 public function setTransparentTagHook( $tag, callable
$callback ) {
4779 $tag = strtolower( $tag );
4780 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4781 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4783 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4784 $this->mTransparentTagHooks
[$tag] = $callback;
4790 * Remove all tag hooks
4792 public function clearTagHooks() {
4793 $this->mTagHooks
= [];
4794 $this->mFunctionTagHooks
= [];
4795 $this->mStripList
= $this->mDefaultStripList
;
4799 * Create a function, e.g. {{sum:1|2|3}}
4800 * The callback function should have the form:
4801 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4803 * Or with Parser::SFH_OBJECT_ARGS:
4804 * function myParserFunction( $parser, $frame, $args ) { ... }
4806 * The callback may either return the text result of the function, or an array with the text
4807 * in element 0, and a number of flags in the other elements. The names of the flags are
4808 * specified in the keys. Valid flags are:
4809 * found The text returned is valid, stop processing the template. This
4811 * nowiki Wiki markup in the return value should be escaped
4812 * isHTML The returned text is HTML, armour it against wikitext transformation
4814 * @param string $id The magic word ID
4815 * @param callable $callback The callback function (and object) to use
4816 * @param int $flags A combination of the following flags:
4817 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4819 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4820 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4821 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4822 * the arguments, and to control the way they are expanded.
4824 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4825 * arguments, for instance:
4826 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4828 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4829 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4830 * working if/when this is changed.
4832 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4835 * Please read the documentation in includes/parser/Preprocessor.php for more information
4836 * about the methods available in PPFrame and PPNode.
4838 * @throws MWException
4839 * @return string|callable The old callback function for this name, if any
4841 public function setFunctionHook( $id, callable
$callback, $flags = 0 ) {
4844 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4845 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4847 # Add to function cache
4848 $mw = MagicWord
::get( $id );
4850 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4853 $synonyms = $mw->getSynonyms();
4854 $sensitive = intval( $mw->isCaseSensitive() );
4856 foreach ( $synonyms as $syn ) {
4858 if ( !$sensitive ) {
4859 $syn = $wgContLang->lc( $syn );
4862 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4865 # Remove trailing colon
4866 if ( substr( $syn, -1, 1 ) === ':' ) {
4867 $syn = substr( $syn, 0, -1 );
4869 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4875 * Get all registered function hook identifiers
4879 public function getFunctionHooks() {
4880 return array_keys( $this->mFunctionHooks
);
4884 * Create a tag function, e.g. "<test>some stuff</test>".
4885 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4886 * Unlike parser functions, their content is not preprocessed.
4887 * @param string $tag
4888 * @param callable $callback
4890 * @throws MWException
4893 public function setFunctionTagHook( $tag, callable
$callback, $flags ) {
4894 $tag = strtolower( $tag );
4895 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4896 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4898 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4899 $this->mFunctionTagHooks
[$tag] : null;
4900 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4902 if ( !in_array( $tag, $this->mStripList
) ) {
4903 $this->mStripList
[] = $tag;
4910 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4911 * Placeholders created in Linker::link()
4913 * @param string $text
4914 * @param int $options
4916 public function replaceLinkHolders( &$text, $options = 0 ) {
4917 $this->mLinkHolders
->replace( $text );
4921 * Replace "<!--LINK-->" link placeholders with plain text of links
4922 * (not HTML-formatted).
4924 * @param string $text
4927 public function replaceLinkHoldersText( $text ) {
4928 return $this->mLinkHolders
->replaceText( $text );
4932 * Renders an image gallery from a text with one line per image.
4933 * text labels may be given by using |-style alternative text. E.g.
4934 * Image:one.jpg|The number "1"
4935 * Image:tree.jpg|A tree
4936 * given as text will return the HTML of a gallery with two images,
4937 * labeled 'The number "1"' and
4940 * @param string $text
4941 * @param array $params
4942 * @return string HTML
4944 public function renderImageGallery( $text, $params ) {
4946 if ( isset( $params['mode'] ) ) {
4947 $mode = $params['mode'];
4951 $ig = ImageGalleryBase
::factory( $mode );
4952 } catch ( Exception
$e ) {
4953 // If invalid type set, fallback to default.
4954 $ig = ImageGalleryBase
::factory( false );
4957 $ig->setContextTitle( $this->mTitle
);
4958 $ig->setShowBytes( false );
4959 $ig->setShowDimensions( false );
4960 $ig->setShowFilename( false );
4961 $ig->setParser( $this );
4962 $ig->setHideBadImages();
4963 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'ul' ) );
4965 if ( isset( $params['showfilename'] ) ) {
4966 $ig->setShowFilename( true );
4968 $ig->setShowFilename( false );
4970 if ( isset( $params['caption'] ) ) {
4971 $caption = $params['caption'];
4972 $caption = htmlspecialchars( $caption );
4973 $caption = $this->replaceInternalLinks( $caption );
4974 $ig->setCaptionHtml( $caption );
4976 if ( isset( $params['perrow'] ) ) {
4977 $ig->setPerRow( $params['perrow'] );
4979 if ( isset( $params['widths'] ) ) {
4980 $ig->setWidths( $params['widths'] );
4982 if ( isset( $params['heights'] ) ) {
4983 $ig->setHeights( $params['heights'] );
4985 $ig->setAdditionalOptions( $params );
4987 // Avoid PHP 7.1 warning from passing $this by reference
4989 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
4991 $lines = StringUtils
::explode( "\n", $text );
4992 foreach ( $lines as $line ) {
4993 # match lines like these:
4994 # Image:someimage.jpg|This is some image
4996 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4998 if ( count( $matches ) == 0 ) {
5002 if ( strpos( $matches[0], '%' ) !== false ) {
5003 $matches[1] = rawurldecode( $matches[1] );
5005 $title = Title
::newFromText( $matches[1], NS_FILE
);
5006 if ( is_null( $title ) ) {
5007 # Bogus title. Ignore these so we don't bomb out later.
5011 # We need to get what handler the file uses, to figure out parameters.
5012 # Note, a hook can overide the file name, and chose an entirely different
5013 # file (which potentially could be of a different type and have different handler).
5016 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5017 [ $this, $title, &$options, &$descQuery ] );
5018 # Don't register it now, as TraditionalImageGallery does that later.
5019 $file = $this->fetchFileNoRegister( $title, $options );
5020 $handler = $file ?
$file->getHandler() : false;
5023 'img_alt' => 'gallery-internal-alt',
5024 'img_link' => 'gallery-internal-link',
5027 $paramMap = $paramMap +
$handler->getParamMap();
5028 // We don't want people to specify per-image widths.
5029 // Additionally the width parameter would need special casing anyhow.
5030 unset( $paramMap['img_width'] );
5033 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5038 $handlerOptions = [];
5039 if ( isset( $matches[3] ) ) {
5040 // look for an |alt= definition while trying not to break existing
5041 // captions with multiple pipes (|) in it, until a more sensible grammar
5042 // is defined for images in galleries
5044 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5045 // splitting on '|' is a bit odd, and different from makeImage.
5046 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5047 // Protect LanguageConverter markup
5048 $parameterMatches = StringUtils
::delimiterExplode(
5049 '-{', '}-', '|', $matches[3], true /* nested */
5052 foreach ( $parameterMatches as $parameterMatch ) {
5053 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5055 $paramName = $paramMap[$magicName];
5057 switch ( $paramName ) {
5058 case 'gallery-internal-alt':
5059 $alt = $this->stripAltText( $match, false );
5061 case 'gallery-internal-link':
5062 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5063 $chars = self
::EXT_LINK_URL_CLASS
;
5064 $addr = self
::EXT_LINK_ADDR
;
5065 $prots = $this->mUrlProtocols
;
5066 // check to see if link matches an absolute url, if not then it must be a wiki link.
5067 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5068 // Result of LanguageConverter::markNoConversion
5069 // invoked on an external link.
5070 $linkValue = substr( $linkValue, 4, -2 );
5072 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5074 $this->mOutput
->addExternalLink( $link );
5076 $localLinkTitle = Title
::newFromText( $linkValue );
5077 if ( $localLinkTitle !== null ) {
5078 $this->mOutput
->addLink( $localLinkTitle );
5079 $link = $localLinkTitle->getLinkURL();
5084 // Must be a handler specific parameter.
5085 if ( $handler->validateParam( $paramName, $match ) ) {
5086 $handlerOptions[$paramName] = $match;
5088 // Guess not, consider it as caption.
5089 wfDebug( "$parameterMatch failed parameter validation\n" );
5090 $label = '|' . $parameterMatch;
5096 $label = '|' . $parameterMatch;
5100 $label = substr( $label, 1 );
5103 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5105 $html = $ig->toHTML();
5106 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5111 * @param MediaHandler $handler
5114 public function getImageParams( $handler ) {
5116 $handlerClass = get_class( $handler );
5120 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5121 # Initialise static lists
5122 static $internalParamNames = [
5123 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5124 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5125 'bottom', 'text-bottom' ],
5126 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5127 'upright', 'border', 'link', 'alt', 'class' ],
5129 static $internalParamMap;
5130 if ( !$internalParamMap ) {
5131 $internalParamMap = [];
5132 foreach ( $internalParamNames as $type => $names ) {
5133 foreach ( $names as $name ) {
5134 // For grep: img_left, img_right, img_center, img_none,
5135 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5136 // img_bottom, img_text_bottom,
5137 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5138 // img_border, img_link, img_alt, img_class
5139 $magicName = str_replace( '-', '_', "img_$name" );
5140 $internalParamMap[$magicName] = [ $type, $name ];
5145 # Add handler params
5146 $paramMap = $internalParamMap;
5148 $handlerParamMap = $handler->getParamMap();
5149 foreach ( $handlerParamMap as $magic => $paramName ) {
5150 $paramMap[$magic] = [ 'handler', $paramName ];
5153 $this->mImageParams
[$handlerClass] = $paramMap;
5154 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5156 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5160 * Parse image options text and use it to make an image
5162 * @param Title $title
5163 * @param string $options
5164 * @param LinkHolderArray|bool $holders
5165 * @return string HTML
5167 public function makeImage( $title, $options, $holders = false ) {
5168 # Check if the options text is of the form "options|alt text"
5170 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5171 # * left no resizing, just left align. label is used for alt= only
5172 # * right same, but right aligned
5173 # * none same, but not aligned
5174 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5175 # * center center the image
5176 # * frame Keep original image size, no magnify-button.
5177 # * framed Same as "frame"
5178 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5179 # * upright reduce width for upright images, rounded to full __0 px
5180 # * border draw a 1px border around the image
5181 # * alt Text for HTML alt attribute (defaults to empty)
5182 # * class Set a class for img node
5183 # * link Set the target of the image link. Can be external, interwiki, or local
5184 # vertical-align values (no % or length right now):
5194 # Protect LanguageConverter markup when splitting into parts
5195 $parts = StringUtils
::delimiterExplode(
5196 '-{', '}-', '|', $options, true /* allow nesting */
5199 # Give extensions a chance to select the file revision for us
5202 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5203 [ $this, $title, &$options, &$descQuery ] );
5204 # Fetch and register the file (file title may be different via hooks)
5205 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5208 $handler = $file ?
$file->getHandler() : false;
5210 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5213 $this->addTrackingCategory( 'broken-file-category' );
5216 # Process the input parameters
5218 $params = [ 'frame' => [], 'handler' => [],
5219 'horizAlign' => [], 'vertAlign' => [] ];
5220 $seenformat = false;
5221 foreach ( $parts as $part ) {
5222 $part = trim( $part );
5223 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5225 if ( isset( $paramMap[$magicName] ) ) {
5226 list( $type, $paramName ) = $paramMap[$magicName];
5228 # Special case; width and height come in one variable together
5229 if ( $type === 'handler' && $paramName === 'width' ) {
5230 $parsedWidthParam = $this->parseWidthParam( $value );
5231 if ( isset( $parsedWidthParam['width'] ) ) {
5232 $width = $parsedWidthParam['width'];
5233 if ( $handler->validateParam( 'width', $width ) ) {
5234 $params[$type]['width'] = $width;
5238 if ( isset( $parsedWidthParam['height'] ) ) {
5239 $height = $parsedWidthParam['height'];
5240 if ( $handler->validateParam( 'height', $height ) ) {
5241 $params[$type]['height'] = $height;
5245 # else no validation -- T15436
5247 if ( $type === 'handler' ) {
5248 # Validate handler parameter
5249 $validated = $handler->validateParam( $paramName, $value );
5251 # Validate internal parameters
5252 switch ( $paramName ) {
5256 # @todo FIXME: Possibly check validity here for
5257 # manualthumb? downstream behavior seems odd with
5258 # missing manual thumbs.
5260 $value = $this->stripAltText( $value, $holders );
5263 $chars = self
::EXT_LINK_URL_CLASS
;
5264 $addr = self
::EXT_LINK_ADDR
;
5265 $prots = $this->mUrlProtocols
;
5266 if ( $value === '' ) {
5267 $paramName = 'no-link';
5270 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5271 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5272 $paramName = 'link-url';
5273 $this->mOutput
->addExternalLink( $value );
5274 if ( $this->mOptions
->getExternalLinkTarget() ) {
5275 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5280 $linkTitle = Title
::newFromText( $value );
5282 $paramName = 'link-title';
5283 $value = $linkTitle;
5284 $this->mOutput
->addLink( $linkTitle );
5292 // use first appearing option, discard others.
5293 $validated = !$seenformat;
5297 # Most other things appear to be empty or numeric...
5298 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5303 $params[$type][$paramName] = $value;
5307 if ( !$validated ) {
5312 # Process alignment parameters
5313 if ( $params['horizAlign'] ) {
5314 $params['frame']['align'] = key( $params['horizAlign'] );
5316 if ( $params['vertAlign'] ) {
5317 $params['frame']['valign'] = key( $params['vertAlign'] );
5320 $params['frame']['caption'] = $caption;
5322 # Will the image be presented in a frame, with the caption below?
5323 $imageIsFramed = isset( $params['frame']['frame'] )
5324 ||
isset( $params['frame']['framed'] )
5325 ||
isset( $params['frame']['thumbnail'] )
5326 ||
isset( $params['frame']['manualthumb'] );
5328 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5329 # came to also set the caption, ordinary text after the image -- which
5330 # makes no sense, because that just repeats the text multiple times in
5331 # screen readers. It *also* came to set the title attribute.
5332 # Now that we have an alt attribute, we should not set the alt text to
5333 # equal the caption: that's worse than useless, it just repeats the
5334 # text. This is the framed/thumbnail case. If there's no caption, we
5335 # use the unnamed parameter for alt text as well, just for the time be-
5336 # ing, if the unnamed param is set and the alt param is not.
5337 # For the future, we need to figure out if we want to tweak this more,
5338 # e.g., introducing a title= parameter for the title; ignoring the un-
5339 # named parameter entirely for images without a caption; adding an ex-
5340 # plicit caption= parameter and preserving the old magic unnamed para-
5342 if ( $imageIsFramed ) { # Framed image
5343 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5344 # No caption or alt text, add the filename as the alt text so
5345 # that screen readers at least get some description of the image
5346 $params['frame']['alt'] = $title->getText();
5348 # Do not set $params['frame']['title'] because tooltips don't make sense
5350 } else { # Inline image
5351 if ( !isset( $params['frame']['alt'] ) ) {
5352 # No alt text, use the "caption" for the alt text
5353 if ( $caption !== '' ) {
5354 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5356 # No caption, fall back to using the filename for the
5358 $params['frame']['alt'] = $title->getText();
5361 # Use the "caption" for the tooltip text
5362 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5365 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5367 # Linker does the rest
5368 $time = isset( $options['time'] ) ?
$options['time'] : false;
5369 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5370 $time, $descQuery, $this->mOptions
->getThumbSize() );
5372 # Give the handler a chance to modify the parser object
5374 $handler->parserTransformHook( $this, $file );
5381 * @param string $caption
5382 * @param LinkHolderArray|bool $holders
5383 * @return mixed|string
5385 protected function stripAltText( $caption, $holders ) {
5386 # Strip bad stuff out of the title (tooltip). We can't just use
5387 # replaceLinkHoldersText() here, because if this function is called
5388 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5390 $tooltip = $holders->replaceText( $caption );
5392 $tooltip = $this->replaceLinkHoldersText( $caption );
5395 # make sure there are no placeholders in thumbnail attributes
5396 # that are later expanded to html- so expand them now and
5398 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5399 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5405 * Set a flag in the output object indicating that the content is dynamic and
5406 * shouldn't be cached.
5407 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5409 public function disableCache() {
5410 wfDebug( "Parser output marked as uncacheable.\n" );
5411 if ( !$this->mOutput
) {
5412 throw new MWException( __METHOD__
.
5413 " can only be called when actually parsing something" );
5415 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5419 * Callback from the Sanitizer for expanding items found in HTML attribute
5420 * values, so they can be safely tested and escaped.
5422 * @param string $text
5423 * @param bool|PPFrame $frame
5426 public function attributeStripCallback( &$text, $frame = false ) {
5427 $text = $this->replaceVariables( $text, $frame );
5428 $text = $this->mStripState
->unstripBoth( $text );
5437 public function getTags() {
5439 array_keys( $this->mTransparentTagHooks
),
5440 array_keys( $this->mTagHooks
),
5441 array_keys( $this->mFunctionTagHooks
)
5446 * Replace transparent tags in $text with the values given by the callbacks.
5448 * Transparent tag hooks are like regular XML-style tag hooks, except they
5449 * operate late in the transformation sequence, on HTML instead of wikitext.
5451 * @param string $text
5455 public function replaceTransparentTags( $text ) {
5457 $elements = array_keys( $this->mTransparentTagHooks
);
5458 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5461 foreach ( $matches as $marker => $data ) {
5462 list( $element, $content, $params, $tag ) = $data;
5463 $tagName = strtolower( $element );
5464 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5465 $output = call_user_func_array(
5466 $this->mTransparentTagHooks
[$tagName],
5467 [ $content, $params, $this ]
5472 $replacements[$marker] = $output;
5474 return strtr( $text, $replacements );
5478 * Break wikitext input into sections, and either pull or replace
5479 * some particular section's text.
5481 * External callers should use the getSection and replaceSection methods.
5483 * @param string $text Page wikitext
5484 * @param string|int $sectionId A section identifier string of the form:
5485 * "<flag1> - <flag2> - ... - <section number>"
5487 * Currently the only recognised flag is "T", which means the target section number
5488 * was derived during a template inclusion parse, in other words this is a template
5489 * section edit link. If no flags are given, it was an ordinary section edit link.
5490 * This flag is required to avoid a section numbering mismatch when a section is
5491 * enclosed by "<includeonly>" (T8563).
5493 * The section number 0 pulls the text before the first heading; other numbers will
5494 * pull the given section along with its lower-level subsections. If the section is
5495 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5497 * Section 0 is always considered to exist, even if it only contains the empty
5498 * string. If $text is the empty string and section 0 is replaced, $newText is
5501 * @param string $mode One of "get" or "replace"
5502 * @param string $newText Replacement text for section data.
5503 * @return string For "get", the extracted section text.
5504 * for "replace", the whole page with the section replaced.
5506 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5507 global $wgTitle; # not generally used but removes an ugly failure mode
5509 $magicScopeVariable = $this->lock();
5510 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5512 $frame = $this->getPreprocessor()->newFrame();
5514 # Process section extraction flags
5516 $sectionParts = explode( '-', $sectionId );
5517 $sectionIndex = array_pop( $sectionParts );
5518 foreach ( $sectionParts as $part ) {
5519 if ( $part === 'T' ) {
5520 $flags |
= self
::PTD_FOR_INCLUSION
;
5524 # Check for empty input
5525 if ( strval( $text ) === '' ) {
5526 # Only sections 0 and T-0 exist in an empty document
5527 if ( $sectionIndex == 0 ) {
5528 if ( $mode === 'get' ) {
5534 if ( $mode === 'get' ) {
5542 # Preprocess the text
5543 $root = $this->preprocessToDom( $text, $flags );
5545 # <h> nodes indicate section breaks
5546 # They can only occur at the top level, so we can find them by iterating the root's children
5547 $node = $root->getFirstChild();
5549 # Find the target section
5550 if ( $sectionIndex == 0 ) {
5551 # Section zero doesn't nest, level=big
5552 $targetLevel = 1000;
5555 if ( $node->getName() === 'h' ) {
5556 $bits = $node->splitHeading();
5557 if ( $bits['i'] == $sectionIndex ) {
5558 $targetLevel = $bits['level'];
5562 if ( $mode === 'replace' ) {
5563 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5565 $node = $node->getNextSibling();
5571 if ( $mode === 'get' ) {
5578 # Find the end of the section, including nested sections
5580 if ( $node->getName() === 'h' ) {
5581 $bits = $node->splitHeading();
5582 $curLevel = $bits['level'];
5583 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5587 if ( $mode === 'get' ) {
5588 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5590 $node = $node->getNextSibling();
5593 # Write out the remainder (in replace mode only)
5594 if ( $mode === 'replace' ) {
5595 # Output the replacement text
5596 # Add two newlines on -- trailing whitespace in $newText is conventionally
5597 # stripped by the editor, so we need both newlines to restore the paragraph gap
5598 # Only add trailing whitespace if there is newText
5599 if ( $newText != "" ) {
5600 $outText .= $newText . "\n\n";
5604 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5605 $node = $node->getNextSibling();
5609 if ( is_string( $outText ) ) {
5610 # Re-insert stripped tags
5611 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5618 * This function returns the text of a section, specified by a number ($section).
5619 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5620 * the first section before any such heading (section 0).
5622 * If a section contains subsections, these are also returned.
5624 * @param string $text Text to look in
5625 * @param string|int $sectionId Section identifier as a number or string
5626 * (e.g. 0, 1 or 'T-1').
5627 * @param string $defaultText Default to return if section is not found
5629 * @return string Text of the requested section
5631 public function getSection( $text, $sectionId, $defaultText = '' ) {
5632 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5636 * This function returns $oldtext after the content of the section
5637 * specified by $section has been replaced with $text. If the target
5638 * section does not exist, $oldtext is returned unchanged.
5640 * @param string $oldText Former text of the article
5641 * @param string|int $sectionId Section identifier as a number or string
5642 * (e.g. 0, 1 or 'T-1').
5643 * @param string $newText Replacing text
5645 * @return string Modified text
5647 public function replaceSection( $oldText, $sectionId, $newText ) {
5648 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5652 * Get the ID of the revision we are parsing
5656 public function getRevisionId() {
5657 return $this->mRevisionId
;
5661 * Get the revision object for $this->mRevisionId
5663 * @return Revision|null Either a Revision object or null
5664 * @since 1.23 (public since 1.23)
5666 public function getRevisionObject() {
5667 if ( !is_null( $this->mRevisionObject
) ) {
5668 return $this->mRevisionObject
;
5670 if ( is_null( $this->mRevisionId
) ) {
5674 $rev = call_user_func(
5675 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5678 # If the parse is for a new revision, then the callback should have
5679 # already been set to force the object and should match mRevisionId.
5680 # If not, try to fetch by mRevisionId for sanity.
5681 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5682 $rev = Revision
::newFromId( $this->mRevisionId
);
5685 $this->mRevisionObject
= $rev;
5687 return $this->mRevisionObject
;
5691 * Get the timestamp associated with the current revision, adjusted for
5692 * the default server-local timestamp
5695 public function getRevisionTimestamp() {
5696 if ( is_null( $this->mRevisionTimestamp
) ) {
5699 $revObject = $this->getRevisionObject();
5700 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5702 # The cryptic '' timezone parameter tells to use the site-default
5703 # timezone offset instead of the user settings.
5704 # Since this value will be saved into the parser cache, served
5705 # to other users, and potentially even used inside links and such,
5706 # it needs to be consistent for all visitors.
5707 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5710 return $this->mRevisionTimestamp
;
5714 * Get the name of the user that edited the last revision
5716 * @return string User name
5718 public function getRevisionUser() {
5719 if ( is_null( $this->mRevisionUser
) ) {
5720 $revObject = $this->getRevisionObject();
5722 # if this template is subst: the revision id will be blank,
5723 # so just use the current user's name
5725 $this->mRevisionUser
= $revObject->getUserText();
5726 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5727 $this->mRevisionUser
= $this->getUser()->getName();
5730 return $this->mRevisionUser
;
5734 * Get the size of the revision
5736 * @return int|null Revision size
5738 public function getRevisionSize() {
5739 if ( is_null( $this->mRevisionSize
) ) {
5740 $revObject = $this->getRevisionObject();
5742 # if this variable is subst: the revision id will be blank,
5743 # so just use the parser input size, because the own substituation
5744 # will change the size.
5746 $this->mRevisionSize
= $revObject->getSize();
5748 $this->mRevisionSize
= $this->mInputSize
;
5751 return $this->mRevisionSize
;
5755 * Mutator for $mDefaultSort
5757 * @param string $sort New value
5759 public function setDefaultSort( $sort ) {
5760 $this->mDefaultSort
= $sort;
5761 $this->mOutput
->setProperty( 'defaultsort', $sort );
5765 * Accessor for $mDefaultSort
5766 * Will use the empty string if none is set.
5768 * This value is treated as a prefix, so the
5769 * empty string is equivalent to sorting by
5774 public function getDefaultSort() {
5775 if ( $this->mDefaultSort
!== false ) {
5776 return $this->mDefaultSort
;
5783 * Accessor for $mDefaultSort
5784 * Unlike getDefaultSort(), will return false if none is set
5786 * @return string|bool
5788 public function getCustomDefaultSort() {
5789 return $this->mDefaultSort
;
5793 * Try to guess the section anchor name based on a wikitext fragment
5794 * presumably extracted from a heading, for example "Header" from
5797 * @param string $text
5801 public function guessSectionNameFromWikiText( $text ) {
5802 # Strip out wikitext links(they break the anchor)
5803 $text = $this->stripSectionName( $text );
5804 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5805 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5809 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5810 * instead. For use in redirects, since IE6 interprets Redirect: headers
5811 * as something other than UTF-8 (apparently?), resulting in breakage.
5813 * @param string $text The section name
5814 * @return string An anchor
5816 public function guessLegacySectionNameFromWikiText( $text ) {
5817 # Strip out wikitext links(they break the anchor)
5818 $text = $this->stripSectionName( $text );
5819 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5820 return '#' . Sanitizer
::escapeId( $text, [ 'noninitial', 'legacy' ] );
5824 * Strips a text string of wikitext for use in a section anchor
5826 * Accepts a text string and then removes all wikitext from the
5827 * string and leaves only the resultant text (i.e. the result of
5828 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5829 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5830 * to create valid section anchors by mimicing the output of the
5831 * parser when headings are parsed.
5833 * @param string $text Text string to be stripped of wikitext
5834 * for use in a Section anchor
5835 * @return string Filtered text string
5837 public function stripSectionName( $text ) {
5838 # Strip internal link markup
5839 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5840 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5842 # Strip external link markup
5843 # @todo FIXME: Not tolerant to blank link text
5844 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5845 # on how many empty links there are on the page - need to figure that out.
5846 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5848 # Parse wikitext quotes (italics & bold)
5849 $text = $this->doQuotes( $text );
5852 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5857 * strip/replaceVariables/unstrip for preprocessor regression testing
5859 * @param string $text
5860 * @param Title $title
5861 * @param ParserOptions $options
5862 * @param int $outputType
5866 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5867 $outputType = self
::OT_HTML
5869 $magicScopeVariable = $this->lock();
5870 $this->startParse( $title, $options, $outputType, true );
5872 $text = $this->replaceVariables( $text );
5873 $text = $this->mStripState
->unstripBoth( $text );
5874 $text = Sanitizer
::removeHTMLtags( $text );
5879 * @param string $text
5880 * @param Title $title
5881 * @param ParserOptions $options
5884 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5885 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5889 * @param string $text
5890 * @param Title $title
5891 * @param ParserOptions $options
5894 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5895 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5899 * Call a callback function on all regions of the given text that are not
5900 * inside strip markers, and replace those regions with the return value
5901 * of the callback. For example, with input:
5905 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5906 * two strings will be replaced with the value returned by the callback in
5910 * @param callable $callback
5914 public function markerSkipCallback( $s, $callback ) {
5917 while ( $i < strlen( $s ) ) {
5918 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
5919 if ( $markerStart === false ) {
5920 $out .= call_user_func( $callback, substr( $s, $i ) );
5923 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5924 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5925 if ( $markerEnd === false ) {
5926 $out .= substr( $s, $markerStart );
5929 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5930 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5939 * Remove any strip markers found in the given text.
5941 * @param string $text Input string
5944 public function killMarkers( $text ) {
5945 return $this->mStripState
->killMarkers( $text );
5949 * Save the parser state required to convert the given half-parsed text to
5950 * HTML. "Half-parsed" in this context means the output of
5951 * recursiveTagParse() or internalParse(). This output has strip markers
5952 * from replaceVariables (extensionSubstitution() etc.), and link
5953 * placeholders from replaceLinkHolders().
5955 * Returns an array which can be serialized and stored persistently. This
5956 * array can later be loaded into another parser instance with
5957 * unserializeHalfParsedText(). The text can then be safely incorporated into
5958 * the return value of a parser hook.
5960 * @param string $text
5964 public function serializeHalfParsedText( $text ) {
5967 'version' => self
::HALF_PARSED_VERSION
,
5968 'stripState' => $this->mStripState
->getSubState( $text ),
5969 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5975 * Load the parser state given in the $data array, which is assumed to
5976 * have been generated by serializeHalfParsedText(). The text contents is
5977 * extracted from the array, and its markers are transformed into markers
5978 * appropriate for the current Parser instance. This transformed text is
5979 * returned, and can be safely included in the return value of a parser
5982 * If the $data array has been stored persistently, the caller should first
5983 * check whether it is still valid, by calling isValidHalfParsedText().
5985 * @param array $data Serialized data
5986 * @throws MWException
5989 public function unserializeHalfParsedText( $data ) {
5990 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5991 throw new MWException( __METHOD__
. ': invalid version' );
5994 # First, extract the strip state.
5995 $texts = [ $data['text'] ];
5996 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5998 # Now renumber links
5999 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6001 # Should be good to go.
6006 * Returns true if the given array, presumed to be generated by
6007 * serializeHalfParsedText(), is compatible with the current version of the
6010 * @param array $data
6014 public function isValidHalfParsedText( $data ) {
6015 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6019 * Parsed a width param of imagelink like 300px or 200x300px
6021 * @param string $value
6026 public function parseWidthParam( $value ) {
6027 $parsedWidthParam = [];
6028 if ( $value === '' ) {
6029 return $parsedWidthParam;
6032 # (T15500) In both cases (width/height and width only),
6033 # permit trailing "px" for backward compatibility.
6034 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6035 $width = intval( $m[1] );
6036 $height = intval( $m[2] );
6037 $parsedWidthParam['width'] = $width;
6038 $parsedWidthParam['height'] = $height;
6039 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6040 $width = intval( $value );
6041 $parsedWidthParam['width'] = $width;
6043 return $parsedWidthParam;
6047 * Lock the current instance of the parser.
6049 * This is meant to stop someone from calling the parser
6050 * recursively and messing up all the strip state.
6052 * @throws MWException If parser is in a parse
6053 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6055 protected function lock() {
6056 if ( $this->mInParse
) {
6057 throw new MWException( "Parser state cleared while parsing. "
6058 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse
);
6061 // Save the backtrace when locking, so that if some code tries locking again,
6062 // we can print the lock owner's backtrace for easier debugging
6064 $this->mInParse
= $e->getTraceAsString();
6066 $recursiveCheck = new ScopedCallback( function () {
6067 $this->mInParse
= false;
6070 return $recursiveCheck;
6074 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6076 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6077 * or if there is more than one <p/> tag in the input HTML.
6079 * @param string $html
6083 public static function stripOuterParagraph( $html ) {
6085 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6086 if ( strpos( $m[1], '</p>' ) === false ) {
6095 * Return this parser if it is not doing anything, otherwise
6096 * get a fresh parser. You can use this method by doing
6097 * $myParser = $wgParser->getFreshParser(), or more simply
6098 * $wgParser->getFreshParser()->parse( ... );
6099 * if you're unsure if $wgParser is safe to use.
6102 * @return Parser A parser object that is not parsing anything
6104 public function getFreshParser() {
6105 global $wgParserConf;
6106 if ( $this->mInParse
) {
6107 return new $wgParserConf['class']( $wgParserConf );
6114 * Set's up the PHP implementation of OOUI for use in this request
6115 * and instructs OutputPage to enable OOUI for itself.
6119 public function enableOOUI() {
6120 OutputPage
::setupOOUI();
6121 $this->mOutput
->setEnableOOUI( true );