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 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
93 # Simplified expression to match an IPv4 or IPv6 address, or
94 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
95 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}])';
96 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
97 // @codingStandardsIgnoreStart Generic.Files.LineLength
98 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
99 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
100 // @codingStandardsIgnoreEnd
102 # Regular expression for a non-newline space
103 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
105 # Flags for preprocessToDom
106 const PTD_FOR_INCLUSION
= 1;
108 # Allowed values for $this->mOutputType
109 # Parameter to startExternalParse().
110 const OT_HTML
= 1; # like parse()
111 const OT_WIKI
= 2; # like preSaveTransform()
112 const OT_PREPROCESS
= 3; # like preprocess()
114 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
117 * @var string Prefix and suffix for temporary replacement strings
118 * for the multipass parser.
120 * \x7f should never appear in input as it's disallowed in XML.
121 * Using it at the front also gives us a little extra robustness
122 * since it shouldn't match when butted up against identifier-like
125 * Must not consist of all title characters, or else it will change
126 * the behavior of <nowiki> in a link.
128 * Must have a character that needs escaping in attributes, otherwise
129 * someone could put a strip marker in an attribute, to get around
130 * escaping quote marks, and break out of the attribute. Thus we add
133 const MARKER_SUFFIX
= "-QINU`\"'\x7f";
134 const MARKER_PREFIX
= "\x7f'\"`UNIQ-";
136 # Markers used for wrapping the table of contents
137 const TOC_START
= '<mw:toc>';
138 const TOC_END
= '</mw:toc>';
141 public $mTagHooks = [];
142 public $mTransparentTagHooks = [];
143 public $mFunctionHooks = [];
144 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
145 public $mFunctionTagHooks = [];
146 public $mStripList = [];
147 public $mDefaultStripList = [];
148 public $mVarCache = [];
149 public $mImageParams = [];
150 public $mImageParamsMagicArray = [];
151 public $mMarkerIndex = 0;
152 public $mFirstCall = true;
154 # Initialised by initialiseVariables()
157 * @var MagicWordArray
162 * @var MagicWordArray
165 # Initialised in constructor
166 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
168 # Initialized in getPreprocessor()
169 /** @var Preprocessor */
170 public $mPreprocessor;
172 # Cleared with clearState():
184 public $mIncludeCount;
186 * @var LinkHolderArray
188 public $mLinkHolders;
191 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
192 public $mDefaultSort;
193 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
194 public $mExpensiveFunctionCount; # number of expensive parser function calls
195 public $mShowToc, $mForceTocPosition;
200 public $mUser; # User object; only used when doing pre-save transform
203 # These are variables reset at least once per parse regardless of $clearState
213 public $mTitle; # Title context, used for self-link rendering and similar things
214 public $mOutputType; # Output type, one of the OT_xxx constants
215 public $ot; # Shortcut alias, see setOutputType()
216 public $mRevisionObject; # The revision object of the specified revision ID
217 public $mRevisionId; # ID to display in {{REVISIONID}} tags
218 public $mRevisionTimestamp; # The timestamp of the specified revision ID
219 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
220 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
221 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
222 public $mInputSize = false; # For {{PAGESIZE}} on current page.
225 * @var string Deprecated accessor for the strip marker prefix.
226 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
228 public $mUniqPrefix = Parser
::MARKER_PREFIX
;
231 * @var array Array with the language name of each language link (i.e. the
232 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
233 * duplicate language links to the ParserOutput.
235 public $mLangLinkLanguages;
238 * @var MapCacheLRU|null
241 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
243 public $currentRevisionCache;
246 * @var bool Recursive call protection.
247 * This variable should be treated as if it were private.
249 public $mInParse = false;
251 /** @var SectionProfiler */
252 protected $mProfiler;
257 protected $mLinkRenderer;
262 public function __construct( $conf = [] ) {
263 $this->mConf
= $conf;
264 $this->mUrlProtocols
= wfUrlProtocols();
265 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
266 self
::EXT_LINK_ADDR
.
267 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
268 if ( isset( $conf['preprocessorClass'] ) ) {
269 $this->mPreprocessorClass
= $conf['preprocessorClass'];
270 } elseif ( defined( 'HPHP_VERSION' ) ) {
271 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
272 $this->mPreprocessorClass
= 'Preprocessor_Hash';
273 } elseif ( extension_loaded( 'domxml' ) ) {
274 # PECL extension that conflicts with the core DOM extension (T15770)
275 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
276 $this->mPreprocessorClass
= 'Preprocessor_Hash';
277 } elseif ( extension_loaded( 'dom' ) ) {
278 $this->mPreprocessorClass
= 'Preprocessor_DOM';
280 $this->mPreprocessorClass
= 'Preprocessor_Hash';
282 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
286 * Reduce memory usage to reduce the impact of circular references
288 public function __destruct() {
289 if ( isset( $this->mLinkHolders
) ) {
290 unset( $this->mLinkHolders
);
292 foreach ( $this as $name => $value ) {
293 unset( $this->$name );
298 * Allow extensions to clean up when the parser is cloned
300 public function __clone() {
301 $this->mInParse
= false;
303 // T58226: When you create a reference "to" an object field, that
304 // makes the object field itself be a reference too (until the other
305 // reference goes out of scope). When cloning, any field that's a
306 // reference is copied as a reference in the new object. Both of these
307 // are defined PHP5 behaviors, as inconvenient as it is for us when old
308 // hooks from PHP4 days are passing fields by reference.
309 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
310 // Make a non-reference copy of the field, then rebind the field to
311 // reference the new copy.
317 Hooks
::run( 'ParserCloned', [ $this ] );
321 * Do various kinds of initialisation on the first call of the parser
323 public function firstCallInit() {
324 if ( !$this->mFirstCall
) {
327 $this->mFirstCall
= false;
329 CoreParserFunctions
::register( $this );
330 CoreTagHooks
::register( $this );
331 $this->initialiseVariables();
333 Hooks
::run( 'ParserFirstCallInit', [ &$this ] );
341 public function clearState() {
342 if ( $this->mFirstCall
) {
343 $this->firstCallInit();
345 $this->mOutput
= new ParserOutput
;
346 $this->mOptions
->registerWatcher( [ $this->mOutput
, 'recordOption' ] );
347 $this->mAutonumber
= 0;
348 $this->mIncludeCount
= [];
349 $this->mLinkHolders
= new LinkHolderArray( $this );
351 $this->mRevisionObject
= $this->mRevisionTimestamp
=
352 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
353 $this->mVarCache
= [];
355 $this->mLangLinkLanguages
= [];
356 $this->currentRevisionCache
= null;
358 $this->mStripState
= new StripState
;
360 # Clear these on every parse, T6549
361 $this->mTplRedirCache
= $this->mTplDomCache
= [];
363 $this->mShowToc
= true;
364 $this->mForceTocPosition
= false;
365 $this->mIncludeSizes
= [
369 $this->mPPNodeCount
= 0;
370 $this->mGeneratedPPNodeCount
= 0;
371 $this->mHighestExpansionDepth
= 0;
372 $this->mDefaultSort
= false;
373 $this->mHeadings
= [];
374 $this->mDoubleUnderscores
= [];
375 $this->mExpensiveFunctionCount
= 0;
378 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
379 $this->mPreprocessor
= null;
382 $this->mProfiler
= new SectionProfiler();
384 Hooks
::run( 'ParserClearState', [ &$this ] );
388 * Convert wikitext to HTML
389 * Do not call this function recursively.
391 * @param string $text Text we want to parse
392 * @param Title $title
393 * @param ParserOptions $options
394 * @param bool $linestart
395 * @param bool $clearState
396 * @param int $revid Number to pass in {{REVISIONID}}
397 * @return ParserOutput A ParserOutput
399 public function parse(
400 $text, Title
$title, ParserOptions
$options,
401 $linestart = true, $clearState = true, $revid = null
404 * First pass--just handle <nowiki> sections, pass the rest off
405 * to internalParse() which does all the real work.
408 global $wgShowHostnames;
411 // We use U+007F DELETE to construct strip markers, so we have to make
412 // sure that this character does not occur in the input text.
413 $text = strtr( $text, "\x7f", "?" );
414 $magicScopeVariable = $this->lock();
417 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
419 $this->currentRevisionCache
= null;
420 $this->mInputSize
= strlen( $text );
421 if ( $this->mOptions
->getEnableLimitReport() ) {
422 $this->mOutput
->resetParseStartTime();
425 $oldRevisionId = $this->mRevisionId
;
426 $oldRevisionObject = $this->mRevisionObject
;
427 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
428 $oldRevisionUser = $this->mRevisionUser
;
429 $oldRevisionSize = $this->mRevisionSize
;
430 if ( $revid !== null ) {
431 $this->mRevisionId
= $revid;
432 $this->mRevisionObject
= null;
433 $this->mRevisionTimestamp
= null;
434 $this->mRevisionUser
= null;
435 $this->mRevisionSize
= null;
438 Hooks
::run( 'ParserBeforeStrip', [ &$this, &$text, &$this->mStripState
] );
440 Hooks
::run( 'ParserAfterStrip', [ &$this, &$text, &$this->mStripState
] );
441 $text = $this->internalParse( $text );
442 Hooks
::run( 'ParserAfterParse', [ &$this, &$text, &$this->mStripState
] );
444 $text = $this->internalParseHalfParsed( $text, true, $linestart );
447 * A converted title will be provided in the output object if title and
448 * content conversion are enabled, the article text does not contain
449 * a conversion-suppressing double-underscore tag, and no
450 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
451 * automatic link conversion.
453 if ( !( $options->getDisableTitleConversion()
454 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
455 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
456 ||
$this->mOutput
->getDisplayTitle() !== false )
458 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
459 if ( $convruletitle ) {
460 $this->mOutput
->setTitleText( $convruletitle );
462 $titleText = $this->getConverterLanguage()->convertTitle( $title );
463 $this->mOutput
->setTitleText( $titleText );
467 # Done parsing! Compute runtime adaptive expiry if set
468 $this->mOutput
->finalizeAdaptiveCacheExpiry();
470 # Warn if too many heavyweight parser functions were used
471 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
472 $this->limitationWarn( 'expensive-parserfunction',
473 $this->mExpensiveFunctionCount
,
474 $this->mOptions
->getExpensiveParserFunctionLimit()
478 # Information on include size limits, for the benefit of users who try to skirt them
479 if ( $this->mOptions
->getEnableLimitReport() ) {
480 $max = $this->mOptions
->getMaxIncludeSize();
482 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
483 if ( $cpuTime !== null ) {
484 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
485 sprintf( "%.3f", $cpuTime )
489 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
490 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
491 sprintf( "%.3f", $wallTime )
494 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
495 [ $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() ]
497 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
498 [ $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() ]
500 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
501 [ $this->mIncludeSizes
['post-expand'], $max ]
503 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
504 [ $this->mIncludeSizes
['arg'], $max ]
506 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
507 [ $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() ]
509 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
510 [ $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() ]
512 Hooks
::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput
] );
514 $limitReport = "NewPP limit report\n";
515 if ( $wgShowHostnames ) {
516 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
518 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
519 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
520 $limitReport .= 'Dynamic content: ' .
521 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
524 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
525 if ( Hooks
::run( 'ParserLimitReportFormat',
526 [ $key, &$value, &$limitReport, false, false ]
528 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
529 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
530 ->inLanguage( 'en' )->useDatabase( false );
531 if ( !$valueMsg->exists() ) {
532 $valueMsg = new RawMessage( '$1' );
534 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
535 $valueMsg->params( $value );
536 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
540 // Since we're not really outputting HTML, decode the entities and
541 // then re-encode the things that need hiding inside HTML comments.
542 $limitReport = htmlspecialchars_decode( $limitReport );
543 Hooks
::run( 'ParserLimitReport', [ $this, &$limitReport ] );
545 // Sanitize for comment. Note '‐' in the replacement is U+2010,
546 // which looks much like the problematic '-'.
547 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&' ], $limitReport );
548 $text .= "\n<!-- \n$limitReport-->\n";
550 // Add on template profiling data in human/machine readable way
551 $dataByFunc = $this->mProfiler
->getFunctionStats();
552 uasort( $dataByFunc, function ( $a, $b ) {
553 return $a['real'] < $b['real']; // descending order
556 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
557 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
558 $item['%real'], $item['real'], $item['calls'],
559 htmlspecialchars( $item['name'] ) );
561 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
562 $text .= implode( "\n", $profileReport ) . "\n-->\n";
564 $this->mOutput
->setLimitReportData( 'limitreport-timingprofile', $profileReport );
566 // Add other cache related metadata
567 if ( $wgShowHostnames ) {
568 $this->mOutput
->setLimitReportData( 'cachereport-origin', wfHostname() );
570 $this->mOutput
->setLimitReportData( 'cachereport-timestamp',
571 $this->mOutput
->getCacheTime() );
572 $this->mOutput
->setLimitReportData( 'cachereport-ttl',
573 $this->mOutput
->getCacheExpiry() );
574 $this->mOutput
->setLimitReportData( 'cachereport-transientcontent',
575 $this->mOutput
->hasDynamicContent() );
577 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
578 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
579 $this->mTitle
->getPrefixedDBkey() );
582 $this->mOutput
->setText( $text );
584 $this->mRevisionId
= $oldRevisionId;
585 $this->mRevisionObject
= $oldRevisionObject;
586 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
587 $this->mRevisionUser
= $oldRevisionUser;
588 $this->mRevisionSize
= $oldRevisionSize;
589 $this->mInputSize
= false;
590 $this->currentRevisionCache
= null;
592 return $this->mOutput
;
596 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
597 * can be called from an extension tag hook.
599 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
600 * instead, which means that lists and links have not been fully parsed yet,
601 * and strip markers are still present.
603 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
605 * Use this function if you're a parser tag hook and you want to parse
606 * wikitext before or after applying additional transformations, and you
607 * intend to *return the result as hook output*, which will cause it to go
608 * through the rest of parsing process automatically.
610 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
611 * $text are not expanded
613 * @param string $text Text extension wants to have parsed
614 * @param bool|PPFrame $frame The frame to use for expanding any template variables
615 * @return string UNSAFE half-parsed HTML
617 public function recursiveTagParse( $text, $frame = false ) {
618 Hooks
::run( 'ParserBeforeStrip', [ &$this, &$text, &$this->mStripState
] );
619 Hooks
::run( 'ParserAfterStrip', [ &$this, &$text, &$this->mStripState
] );
620 $text = $this->internalParse( $text, false, $frame );
625 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
626 * point can be called from an extension tag hook.
628 * The output of this function is fully-parsed HTML that is safe for output.
629 * If you're a parser tag hook, you might want to use recursiveTagParse()
632 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
633 * $text are not expanded
637 * @param string $text Text extension wants to have parsed
638 * @param bool|PPFrame $frame The frame to use for expanding any template variables
639 * @return string Fully parsed HTML
641 public function recursiveTagParseFully( $text, $frame = false ) {
642 $text = $this->recursiveTagParse( $text, $frame );
643 $text = $this->internalParseHalfParsed( $text, false );
648 * Expand templates and variables in the text, producing valid, static wikitext.
649 * Also removes comments.
650 * Do not call this function recursively.
651 * @param string $text
652 * @param Title $title
653 * @param ParserOptions $options
654 * @param int|null $revid
655 * @param bool|PPFrame $frame
656 * @return mixed|string
658 public function preprocess( $text, Title
$title = null,
659 ParserOptions
$options, $revid = null, $frame = false
661 $magicScopeVariable = $this->lock();
662 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
663 if ( $revid !== null ) {
664 $this->mRevisionId
= $revid;
666 Hooks
::run( 'ParserBeforeStrip', [ &$this, &$text, &$this->mStripState
] );
667 Hooks
::run( 'ParserAfterStrip', [ &$this, &$text, &$this->mStripState
] );
668 $text = $this->replaceVariables( $text, $frame );
669 $text = $this->mStripState
->unstripBoth( $text );
674 * Recursive parser entry point that can be called from an extension tag
677 * @param string $text Text to be expanded
678 * @param bool|PPFrame $frame The frame to use for expanding any template variables
682 public function recursivePreprocess( $text, $frame = false ) {
683 $text = $this->replaceVariables( $text, $frame );
684 $text = $this->mStripState
->unstripBoth( $text );
689 * Process the wikitext for the "?preload=" feature. (T7210)
691 * "<noinclude>", "<includeonly>" etc. are parsed as for template
692 * transclusion, comments, templates, arguments, tags hooks and parser
693 * functions are untouched.
695 * @param string $text
696 * @param Title $title
697 * @param ParserOptions $options
698 * @param array $params
701 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = [] ) {
702 $msg = new RawMessage( $text );
703 $text = $msg->params( $params )->plain();
705 # Parser (re)initialisation
706 $magicScopeVariable = $this->lock();
707 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
709 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
710 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
711 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
712 $text = $this->mStripState
->unstripBoth( $text );
717 * Get a random string
720 * @deprecated since 1.26; use wfRandomString() instead.
722 public static function getRandomString() {
723 wfDeprecated( __METHOD__
, '1.26' );
724 return wfRandomString( 16 );
728 * Set the current user.
729 * Should only be used when doing pre-save transform.
731 * @param User|null $user User object or null (to reset)
733 public function setUser( $user ) {
734 $this->mUser
= $user;
738 * Accessor for mUniqPrefix.
741 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
743 public function uniqPrefix() {
744 wfDeprecated( __METHOD__
, '1.26' );
745 return self
::MARKER_PREFIX
;
749 * Set the context title
753 public function setTitle( $t ) {
755 $t = Title
::newFromText( 'NO TITLE' );
758 if ( $t->hasFragment() ) {
759 # Strip the fragment to avoid various odd effects
760 $this->mTitle
= $t->createFragmentTarget( '' );
767 * Accessor for the Title object
771 public function getTitle() {
772 return $this->mTitle
;
776 * Accessor/mutator for the Title object
778 * @param Title $x Title object or null to just get the current one
781 public function Title( $x = null ) {
782 return wfSetVar( $this->mTitle
, $x );
786 * Set the output type
788 * @param int $ot New value
790 public function setOutputType( $ot ) {
791 $this->mOutputType
= $ot;
794 'html' => $ot == self
::OT_HTML
,
795 'wiki' => $ot == self
::OT_WIKI
,
796 'pre' => $ot == self
::OT_PREPROCESS
,
797 'plain' => $ot == self
::OT_PLAIN
,
802 * Accessor/mutator for the output type
804 * @param int|null $x New value or null to just get the current one
807 public function OutputType( $x = null ) {
808 return wfSetVar( $this->mOutputType
, $x );
812 * Get the ParserOutput object
814 * @return ParserOutput
816 public function getOutput() {
817 return $this->mOutput
;
821 * Get the ParserOptions object
823 * @return ParserOptions
825 public function getOptions() {
826 return $this->mOptions
;
830 * Accessor/mutator for the ParserOptions object
832 * @param ParserOptions $x New value or null to just get the current one
833 * @return ParserOptions Current ParserOptions object
835 public function Options( $x = null ) {
836 return wfSetVar( $this->mOptions
, $x );
842 public function nextLinkID() {
843 return $this->mLinkID++
;
849 public function setLinkID( $id ) {
850 $this->mLinkID
= $id;
854 * Get a language object for use in parser functions such as {{FORMATNUM:}}
857 public function getFunctionLang() {
858 return $this->getTargetLanguage();
862 * Get the target language for the content being parsed. This is usually the
863 * language that the content is in.
867 * @throws MWException
870 public function getTargetLanguage() {
871 $target = $this->mOptions
->getTargetLanguage();
873 if ( $target !== null ) {
875 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
876 return $this->mOptions
->getUserLangObj();
877 } elseif ( is_null( $this->mTitle
) ) {
878 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
881 return $this->mTitle
->getPageLanguage();
885 * Get the language object for language conversion
886 * @return Language|null
888 public function getConverterLanguage() {
889 return $this->getTargetLanguage();
893 * Get a User object either from $this->mUser, if set, or from the
894 * ParserOptions object otherwise
898 public function getUser() {
899 if ( !is_null( $this->mUser
) ) {
902 return $this->mOptions
->getUser();
906 * Get a preprocessor object
908 * @return Preprocessor
910 public function getPreprocessor() {
911 if ( !isset( $this->mPreprocessor
) ) {
912 $class = $this->mPreprocessorClass
;
913 $this->mPreprocessor
= new $class( $this );
915 return $this->mPreprocessor
;
919 * Get a LinkRenderer instance to make links with
922 * @return LinkRenderer
924 public function getLinkRenderer() {
925 if ( !$this->mLinkRenderer
) {
926 $this->mLinkRenderer
= MediaWikiServices
::getInstance()
927 ->getLinkRendererFactory()->create();
928 $this->mLinkRenderer
->setStubThreshold(
929 $this->getOptions()->getStubThreshold()
933 return $this->mLinkRenderer
;
937 * Replaces all occurrences of HTML-style comments and the given tags
938 * in the text with a random marker and returns the next text. The output
939 * parameter $matches will be an associative array filled with data in
946 * [ 'param' => 'x' ],
947 * '<element param="x">tag content</element>' ]
950 * @param array $elements List of element names. Comments are always extracted.
951 * @param string $text Source text string.
952 * @param array $matches Out parameter, Array: extracted tags
953 * @param string|null $uniq_prefix
954 * @return string Stripped text
955 * @since 1.26 The uniq_prefix argument is deprecated.
957 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
958 if ( $uniq_prefix !== null ) {
959 wfDeprecated( __METHOD__
. ' called with $prefix argument', '1.26' );
965 $taglist = implode( '|', $elements );
966 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
968 while ( $text != '' ) {
969 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
971 if ( count( $p ) < 5 ) {
974 if ( count( $p ) > 5 ) {
988 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
989 $stripped .= $marker;
991 if ( $close === '/>' ) {
992 # Empty element tag, <tag />
997 if ( $element === '!--' ) {
1000 $end = "/(<\\/$element\\s*>)/i";
1002 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1004 if ( count( $q ) < 3 ) {
1005 # No end tag -- let it run out to the end of the text.
1014 $matches[$marker] = [ $element,
1016 Sanitizer
::decodeTagAttributes( $attributes ),
1017 "<$element$attributes$close$content$tail" ];
1023 * Get a list of strippable XML-like elements
1027 public function getStripList() {
1028 return $this->mStripList
;
1032 * Add an item to the strip state
1033 * Returns the unique tag which must be inserted into the stripped text
1034 * The tag will be replaced with the original text in unstrip()
1036 * @param string $text
1040 public function insertStripItem( $text ) {
1041 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1042 $this->mMarkerIndex++
;
1043 $this->mStripState
->addGeneral( $marker, $text );
1048 * parse the wiki syntax used to render tables
1051 * @param string $text
1054 public function doTableStuff( $text ) {
1056 $lines = StringUtils
::explode( "\n", $text );
1058 $td_history = []; # Is currently a td tag open?
1059 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1060 $tr_history = []; # Is currently a tr tag open?
1061 $tr_attributes = []; # history of tr attributes
1062 $has_opened_tr = []; # Did this table open a <tr> element?
1063 $indent_level = 0; # indent level of the table
1065 foreach ( $lines as $outLine ) {
1066 $line = trim( $outLine );
1068 if ( $line === '' ) { # empty line, go to next line
1069 $out .= $outLine . "\n";
1073 $first_character = $line[0];
1074 $first_two = substr( $line, 0, 2 );
1077 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1078 # First check if we are starting a new table
1079 $indent_level = strlen( $matches[1] );
1081 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1082 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1084 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1085 array_push( $td_history, false );
1086 array_push( $last_tag_history, '' );
1087 array_push( $tr_history, false );
1088 array_push( $tr_attributes, '' );
1089 array_push( $has_opened_tr, false );
1090 } elseif ( count( $td_history ) == 0 ) {
1091 # Don't do any of the following
1092 $out .= $outLine . "\n";
1094 } elseif ( $first_two === '|}' ) {
1095 # We are ending a table
1096 $line = '</table>' . substr( $line, 2 );
1097 $last_tag = array_pop( $last_tag_history );
1099 if ( !array_pop( $has_opened_tr ) ) {
1100 $line = "<tr><td></td></tr>{$line}";
1103 if ( array_pop( $tr_history ) ) {
1104 $line = "</tr>{$line}";
1107 if ( array_pop( $td_history ) ) {
1108 $line = "</{$last_tag}>{$line}";
1110 array_pop( $tr_attributes );
1111 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1112 } elseif ( $first_two === '|-' ) {
1113 # Now we have a table row
1114 $line = preg_replace( '#^\|-+#', '', $line );
1116 # Whats after the tag is now only attributes
1117 $attributes = $this->mStripState
->unstripBoth( $line );
1118 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1119 array_pop( $tr_attributes );
1120 array_push( $tr_attributes, $attributes );
1123 $last_tag = array_pop( $last_tag_history );
1124 array_pop( $has_opened_tr );
1125 array_push( $has_opened_tr, true );
1127 if ( array_pop( $tr_history ) ) {
1131 if ( array_pop( $td_history ) ) {
1132 $line = "</{$last_tag}>{$line}";
1136 array_push( $tr_history, false );
1137 array_push( $td_history, false );
1138 array_push( $last_tag_history, '' );
1139 } elseif ( $first_character === '|'
1140 ||
$first_character === '!'
1141 ||
$first_two === '|+'
1143 # This might be cell elements, td, th or captions
1144 if ( $first_two === '|+' ) {
1145 $first_character = '+';
1146 $line = substr( $line, 2 );
1148 $line = substr( $line, 1 );
1151 // Implies both are valid for table headings.
1152 if ( $first_character === '!' ) {
1153 $line = StringUtils
::replaceMarkup( '!!', '||', $line );
1156 # Split up multiple cells on the same line.
1157 # FIXME : This can result in improper nesting of tags processed
1158 # by earlier parser steps.
1159 $cells = explode( '||', $line );
1163 # Loop through each table cell
1164 foreach ( $cells as $cell ) {
1166 if ( $first_character !== '+' ) {
1167 $tr_after = array_pop( $tr_attributes );
1168 if ( !array_pop( $tr_history ) ) {
1169 $previous = "<tr{$tr_after}>\n";
1171 array_push( $tr_history, true );
1172 array_push( $tr_attributes, '' );
1173 array_pop( $has_opened_tr );
1174 array_push( $has_opened_tr, true );
1177 $last_tag = array_pop( $last_tag_history );
1179 if ( array_pop( $td_history ) ) {
1180 $previous = "</{$last_tag}>\n{$previous}";
1183 if ( $first_character === '|' ) {
1185 } elseif ( $first_character === '!' ) {
1187 } elseif ( $first_character === '+' ) {
1188 $last_tag = 'caption';
1193 array_push( $last_tag_history, $last_tag );
1195 # A cell could contain both parameters and data
1196 $cell_data = explode( '|', $cell, 2 );
1198 # T2553: Note that a '|' inside an invalid link should not
1199 # be mistaken as delimiting cell parameters
1200 # Bug T153140: Neither should language converter markup.
1201 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1202 $cell = "{$previous}<{$last_tag}>{$cell}";
1203 } elseif ( count( $cell_data ) == 1 ) {
1204 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1206 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1207 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1208 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1212 array_push( $td_history, true );
1215 $out .= $outLine . "\n";
1218 # Closing open td, tr && table
1219 while ( count( $td_history ) > 0 ) {
1220 if ( array_pop( $td_history ) ) {
1223 if ( array_pop( $tr_history ) ) {
1226 if ( !array_pop( $has_opened_tr ) ) {
1227 $out .= "<tr><td></td></tr>\n";
1230 $out .= "</table>\n";
1233 # Remove trailing line-ending (b/c)
1234 if ( substr( $out, -1 ) === "\n" ) {
1235 $out = substr( $out, 0, -1 );
1238 # special case: don't return empty table
1239 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1247 * Helper function for parse() that transforms wiki markup into half-parsed
1248 * HTML. Only called for $mOutputType == self::OT_HTML.
1252 * @param string $text The text to parse
1253 * @param bool $isMain Whether this is being called from the main parse() function
1254 * @param PPFrame|bool $frame A pre-processor frame
1258 public function internalParse( $text, $isMain = true, $frame = false ) {
1262 # Hook to suspend the parser in this state
1263 if ( !Hooks
::run( 'ParserBeforeInternalParse', [ &$this, &$text, &$this->mStripState
] ) ) {
1267 # if $frame is provided, then use $frame for replacing any variables
1269 # use frame depth to infer how include/noinclude tags should be handled
1270 # depth=0 means this is the top-level document; otherwise it's an included document
1271 if ( !$frame->depth
) {
1274 $flag = Parser
::PTD_FOR_INCLUSION
;
1276 $dom = $this->preprocessToDom( $text, $flag );
1277 $text = $frame->expand( $dom );
1279 # if $frame is not provided, then use old-style replaceVariables
1280 $text = $this->replaceVariables( $text );
1283 Hooks
::run( 'InternalParseBeforeSanitize', [ &$this, &$text, &$this->mStripState
] );
1284 $text = Sanitizer
::removeHTMLtags(
1286 [ &$this, 'attributeStripCallback' ],
1288 array_keys( $this->mTransparentTagHooks
),
1290 [ &$this, 'addTrackingCategory' ]
1292 Hooks
::run( 'InternalParseBeforeLinks', [ &$this, &$text, &$this->mStripState
] );
1294 # Tables need to come after variable replacement for things to work
1295 # properly; putting them before other transformations should keep
1296 # exciting things like link expansions from showing up in surprising
1298 $text = $this->doTableStuff( $text );
1300 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1302 $text = $this->doDoubleUnderscore( $text );
1304 $text = $this->doHeadings( $text );
1305 $text = $this->replaceInternalLinks( $text );
1306 $text = $this->doAllQuotes( $text );
1307 $text = $this->replaceExternalLinks( $text );
1309 # replaceInternalLinks may sometimes leave behind
1310 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1311 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1313 $text = $this->doMagicLinks( $text );
1314 $text = $this->formatHeadings( $text, $origText, $isMain );
1320 * Helper function for parse() that transforms half-parsed HTML into fully
1323 * @param string $text
1324 * @param bool $isMain
1325 * @param bool $linestart
1328 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1329 $text = $this->mStripState
->unstripGeneral( $text );
1332 Hooks
::run( 'ParserAfterUnstrip', [ &$this, &$text ] );
1335 # Clean up special characters, only run once, next-to-last before doBlockLevels
1337 # French spaces, last one Guillemet-left
1338 # only if there is something before the space
1339 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1340 # french spaces, Guillemet-right
1341 '/(\\302\\253) /' => '\\1 ',
1342 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1344 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1346 $text = $this->doBlockLevels( $text, $linestart );
1348 $this->replaceLinkHolders( $text );
1351 * The input doesn't get language converted if
1353 * b) Content isn't converted
1354 * c) It's a conversion table
1355 * d) it is an interface message (which is in the user language)
1357 if ( !( $this->mOptions
->getDisableContentConversion()
1358 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1360 if ( !$this->mOptions
->getInterfaceMessage() ) {
1361 # The position of the convert() call should not be changed. it
1362 # assumes that the links are all replaced and the only thing left
1363 # is the <nowiki> mark.
1364 $text = $this->getConverterLanguage()->convert( $text );
1368 $text = $this->mStripState
->unstripNoWiki( $text );
1371 Hooks
::run( 'ParserBeforeTidy', [ &$this, &$text ] );
1374 $text = $this->replaceTransparentTags( $text );
1375 $text = $this->mStripState
->unstripGeneral( $text );
1377 $text = Sanitizer
::normalizeCharReferences( $text );
1379 if ( MWTidy
::isEnabled() ) {
1380 if ( $this->mOptions
->getTidy() ) {
1381 $text = MWTidy
::tidy( $text );
1384 # attempt to sanitize at least some nesting problems
1385 # (T4702 and quite a few others)
1387 # ''Something [http://www.cool.com cool''] -->
1388 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1389 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1390 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1391 # fix up an anchor inside another anchor, only
1392 # at least for a single single nested link (T5695)
1393 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1394 '\\1\\2</a>\\3</a>\\1\\4</a>',
1395 # fix div inside inline elements- doBlockLevels won't wrap a line which
1396 # contains a div, so fix it up here; replace
1397 # div with escaped text
1398 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1399 '\\1\\3<div\\5>\\6</div>\\8\\9',
1400 # remove empty italic or bold tag pairs, some
1401 # introduced by rules above
1402 '/<([bi])><\/\\1>/' => '',
1405 $text = preg_replace(
1406 array_keys( $tidyregs ),
1407 array_values( $tidyregs ),
1412 Hooks
::run( 'ParserAfterTidy', [ &$this, &$text ] );
1419 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1420 * magic external links.
1425 * @param string $text
1429 public function doMagicLinks( $text ) {
1430 $prots = wfUrlProtocolsWithoutProtRel();
1431 $urlChar = self
::EXT_LINK_URL_CLASS
;
1432 $addr = self
::EXT_LINK_ADDR
;
1433 $space = self
::SPACE_NOT_NL
; # non-newline space
1434 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1435 $spaces = "$space++"; # possessive match of 1 or more spaces
1436 $text = preg_replace_callback(
1438 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1439 (<.*?>) | # m[2]: Skip stuff inside
1440 # HTML elements' . "
1441 (\b(?i:$prots)($addr$urlChar*)) | # m[3]: Free external links
1442 # m[4]: Post-protocol path
1443 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1445 \bISBN $spaces ( # m[6]: ISBN, capture number
1446 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1447 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1448 [0-9Xx] # check digit
1450 )!xu", [ &$this, 'magicLinkCallback' ], $text );
1455 * @throws MWException
1457 * @return HTML|string
1459 public function magicLinkCallback( $m ) {
1460 if ( isset( $m[1] ) && $m[1] !== '' ) {
1463 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1466 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1467 # Free external link
1468 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1469 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1471 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1472 if ( !$this->mOptions
->getMagicRFCLinks() ) {
1477 $cssClass = 'mw-magiclink-rfc';
1478 $trackingCat = 'magiclink-tracking-rfc';
1480 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1481 if ( !$this->mOptions
->getMagicPMIDLinks() ) {
1485 $urlmsg = 'pubmedurl';
1486 $cssClass = 'mw-magiclink-pmid';
1487 $trackingCat = 'magiclink-tracking-pmid';
1490 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1491 substr( $m[0], 0, 20 ) . '"' );
1493 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1494 $this->addTrackingCategory( $trackingCat );
1495 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle
);
1496 } elseif ( isset( $m[6] ) && $m[6] !== ''
1497 && $this->mOptions
->getMagicISBNLinks()
1501 $space = self
::SPACE_NOT_NL
; # non-newline space
1502 $isbn = preg_replace( "/$space/", ' ', $isbn );
1503 $num = strtr( $isbn, [
1508 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1509 return $this->getLinkRenderer()->makeKnownLink(
1510 SpecialPage
::getTitleFor( 'Booksources', $num ),
1513 'class' => 'internal mw-magiclink-isbn',
1514 'title' => false // suppress title attribute
1523 * Make a free external link, given a user-supplied URL
1525 * @param string $url
1526 * @param int $numPostProto
1527 * The number of characters after the protocol.
1528 * @return string HTML
1531 public function makeFreeExternalLink( $url, $numPostProto ) {
1534 # The characters '<' and '>' (which were escaped by
1535 # removeHTMLtags()) should not be included in
1536 # URLs, per RFC 2396.
1537 # Make terminate a URL as well (bug T84937)
1540 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1545 $trail = substr( $url, $m2[0][1] ) . $trail;
1546 $url = substr( $url, 0, $m2[0][1] );
1549 # Move trailing punctuation to $trail
1551 # If there is no left bracket, then consider right brackets fair game too
1552 if ( strpos( $url, '(' ) === false ) {
1556 $urlRev = strrev( $url );
1557 $numSepChars = strspn( $urlRev, $sep );
1558 # Don't break a trailing HTML entity by moving the ; into $trail
1559 # This is in hot code, so use substr_compare to avoid having to
1560 # create a new string object for the comparison
1561 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1562 # more optimization: instead of running preg_match with a $
1563 # anchor, which can be slow, do the match on the reversed
1564 # string starting at the desired offset.
1565 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1566 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1570 if ( $numSepChars ) {
1571 $trail = substr( $url, -$numSepChars ) . $trail;
1572 $url = substr( $url, 0, -$numSepChars );
1575 # Verify that we still have a real URL after trail removal, and
1576 # not just lone protocol
1577 if ( strlen( $trail ) >= $numPostProto ) {
1578 return $url . $trail;
1581 $url = Sanitizer
::cleanUrl( $url );
1583 # Is this an external image?
1584 $text = $this->maybeMakeExternalImage( $url );
1585 if ( $text === false ) {
1586 # Not an image, make a link
1587 $text = Linker
::makeExternalLink( $url,
1588 $this->getConverterLanguage()->markNoConversion( $url, true ),
1590 $this->getExternalLinkAttribs( $url ), $this->mTitle
);
1591 # Register it in the output object...
1592 # Replace unnecessary URL escape codes with their equivalent characters
1593 $pasteurized = self
::normalizeLinkUrl( $url );
1594 $this->mOutput
->addExternalLink( $pasteurized );
1596 return $text . $trail;
1600 * Parse headers and return html
1604 * @param string $text
1608 public function doHeadings( $text ) {
1609 for ( $i = 6; $i >= 1; --$i ) {
1610 $h = str_repeat( '=', $i );
1611 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1617 * Replace single quotes with HTML markup
1620 * @param string $text
1622 * @return string The altered text
1624 public function doAllQuotes( $text ) {
1626 $lines = StringUtils
::explode( "\n", $text );
1627 foreach ( $lines as $line ) {
1628 $outtext .= $this->doQuotes( $line ) . "\n";
1630 $outtext = substr( $outtext, 0, -1 );
1635 * Helper function for doAllQuotes()
1637 * @param string $text
1641 public function doQuotes( $text ) {
1642 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1643 $countarr = count( $arr );
1644 if ( $countarr == 1 ) {
1648 // First, do some preliminary work. This may shift some apostrophes from
1649 // being mark-up to being text. It also counts the number of occurrences
1650 // of bold and italics mark-ups.
1653 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1654 $thislen = strlen( $arr[$i] );
1655 // If there are ever four apostrophes, assume the first is supposed to
1656 // be text, and the remaining three constitute mark-up for bold text.
1657 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1658 if ( $thislen == 4 ) {
1659 $arr[$i - 1] .= "'";
1662 } elseif ( $thislen > 5 ) {
1663 // If there are more than 5 apostrophes in a row, assume they're all
1664 // text except for the last 5.
1665 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1666 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1670 // Count the number of occurrences of bold and italics mark-ups.
1671 if ( $thislen == 2 ) {
1673 } elseif ( $thislen == 3 ) {
1675 } elseif ( $thislen == 5 ) {
1681 // If there is an odd number of both bold and italics, it is likely
1682 // that one of the bold ones was meant to be an apostrophe followed
1683 // by italics. Which one we cannot know for certain, but it is more
1684 // likely to be one that has a single-letter word before it.
1685 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1686 $firstsingleletterword = -1;
1687 $firstmultiletterword = -1;
1689 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1690 if ( strlen( $arr[$i] ) == 3 ) {
1691 $x1 = substr( $arr[$i - 1], -1 );
1692 $x2 = substr( $arr[$i - 1], -2, 1 );
1693 if ( $x1 === ' ' ) {
1694 if ( $firstspace == -1 ) {
1697 } elseif ( $x2 === ' ' ) {
1698 $firstsingleletterword = $i;
1699 // if $firstsingleletterword is set, we don't
1700 // look at the other options, so we can bail early.
1703 if ( $firstmultiletterword == -1 ) {
1704 $firstmultiletterword = $i;
1710 // If there is a single-letter word, use it!
1711 if ( $firstsingleletterword > -1 ) {
1712 $arr[$firstsingleletterword] = "''";
1713 $arr[$firstsingleletterword - 1] .= "'";
1714 } elseif ( $firstmultiletterword > -1 ) {
1715 // If not, but there's a multi-letter word, use that one.
1716 $arr[$firstmultiletterword] = "''";
1717 $arr[$firstmultiletterword - 1] .= "'";
1718 } elseif ( $firstspace > -1 ) {
1719 // ... otherwise use the first one that has neither.
1720 // (notice that it is possible for all three to be -1 if, for example,
1721 // there is only one pentuple-apostrophe in the line)
1722 $arr[$firstspace] = "''";
1723 $arr[$firstspace - 1] .= "'";
1727 // Now let's actually convert our apostrophic mush to HTML!
1732 foreach ( $arr as $r ) {
1733 if ( ( $i %
2 ) == 0 ) {
1734 if ( $state === 'both' ) {
1740 $thislen = strlen( $r );
1741 if ( $thislen == 2 ) {
1742 if ( $state === 'i' ) {
1745 } elseif ( $state === 'bi' ) {
1748 } elseif ( $state === 'ib' ) {
1749 $output .= '</b></i><b>';
1751 } elseif ( $state === 'both' ) {
1752 $output .= '<b><i>' . $buffer . '</i>';
1754 } else { // $state can be 'b' or ''
1758 } elseif ( $thislen == 3 ) {
1759 if ( $state === 'b' ) {
1762 } elseif ( $state === 'bi' ) {
1763 $output .= '</i></b><i>';
1765 } elseif ( $state === 'ib' ) {
1768 } elseif ( $state === 'both' ) {
1769 $output .= '<i><b>' . $buffer . '</b>';
1771 } else { // $state can be 'i' or ''
1775 } elseif ( $thislen == 5 ) {
1776 if ( $state === 'b' ) {
1777 $output .= '</b><i>';
1779 } elseif ( $state === 'i' ) {
1780 $output .= '</i><b>';
1782 } elseif ( $state === 'bi' ) {
1783 $output .= '</i></b>';
1785 } elseif ( $state === 'ib' ) {
1786 $output .= '</b></i>';
1788 } elseif ( $state === 'both' ) {
1789 $output .= '<i><b>' . $buffer . '</b></i>';
1791 } else { // ($state == '')
1799 // Now close all remaining tags. Notice that the order is important.
1800 if ( $state === 'b' ||
$state === 'ib' ) {
1803 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1806 if ( $state === 'bi' ) {
1809 // There might be lonely ''''', so make sure we have a buffer
1810 if ( $state === 'both' && $buffer ) {
1811 $output .= '<b><i>' . $buffer . '</i></b>';
1817 * Replace external links (REL)
1819 * Note: this is all very hackish and the order of execution matters a lot.
1820 * Make sure to run tests/parser/parserTests.php if you change this code.
1824 * @param string $text
1826 * @throws MWException
1829 public function replaceExternalLinks( $text ) {
1831 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1832 if ( $bits === false ) {
1833 throw new MWException( "PCRE needs to be compiled with "
1834 . "--enable-unicode-properties in order for MediaWiki to function" );
1836 $s = array_shift( $bits );
1839 while ( $i < count( $bits ) ) {
1842 $text = $bits[$i++
];
1843 $trail = $bits[$i++
];
1845 # The characters '<' and '>' (which were escaped by
1846 # removeHTMLtags()) should not be included in
1847 # URLs, per RFC 2396.
1849 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1850 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1851 $url = substr( $url, 0, $m2[0][1] );
1854 # If the link text is an image URL, replace it with an <img> tag
1855 # This happened by accident in the original parser, but some people used it extensively
1856 $img = $this->maybeMakeExternalImage( $text );
1857 if ( $img !== false ) {
1863 # Set linktype for CSS - if URL==text, link is essentially free
1864 $linktype = ( $text === $url ) ?
'free' : 'text';
1866 # No link text, e.g. [http://domain.tld/some.link]
1867 if ( $text == '' ) {
1869 $langObj = $this->getTargetLanguage();
1870 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1871 $linktype = 'autonumber';
1873 # Have link text, e.g. [http://domain.tld/some.link text]s
1875 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1878 $text = $this->getConverterLanguage()->markNoConversion( $text );
1880 $url = Sanitizer
::cleanUrl( $url );
1882 # Use the encoded URL
1883 # This means that users can paste URLs directly into the text
1884 # Funny characters like ö aren't valid in URLs anyway
1885 # This was changed in August 2004
1886 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1887 $this->getExternalLinkAttribs( $url ), $this->mTitle
) . $dtrail . $trail;
1889 # Register link in the output object.
1890 # Replace unnecessary URL escape codes with the referenced character
1891 # This prevents spammers from hiding links from the filters
1892 $pasteurized = self
::normalizeLinkUrl( $url );
1893 $this->mOutput
->addExternalLink( $pasteurized );
1900 * Get the rel attribute for a particular external link.
1903 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1904 * nofollow if appropriate
1905 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1906 * @return string|null Rel attribute for $url
1908 public static function getExternalLinkRel( $url = false, $title = null ) {
1909 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1910 $ns = $title ?
$title->getNamespace() : false;
1911 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1912 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1920 * Get an associative array of additional HTML attributes appropriate for a
1921 * particular external link. This currently may include rel => nofollow
1922 * (depending on configuration, namespace, and the URL's domain) and/or a
1923 * target attribute (depending on configuration).
1925 * @param string $url URL to extract the domain from for rel =>
1926 * nofollow if appropriate
1927 * @return array Associative array of HTML attributes
1929 public function getExternalLinkAttribs( $url ) {
1931 $rel = self
::getExternalLinkRel( $url, $this->mTitle
);
1933 $target = $this->mOptions
->getExternalLinkTarget();
1935 $attribs['target'] = $target;
1936 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1937 // T133507. New windows can navigate parent cross-origin.
1938 // Including noreferrer due to lacking browser
1939 // support of noopener. Eventually noreferrer should be removed.
1940 if ( $rel !== '' ) {
1943 $rel .= 'noreferrer noopener';
1946 $attribs['rel'] = $rel;
1951 * Replace unusual escape codes in a URL with their equivalent characters
1953 * This generally follows the syntax defined in RFC 3986, with special
1954 * consideration for HTTP query strings.
1956 * @param string $url
1959 public static function normalizeLinkUrl( $url ) {
1960 # First, make sure unsafe characters are encoded
1961 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1963 return rawurlencode( $m[0] );
1969 $end = strlen( $url );
1971 # Fragment part - 'fragment'
1972 $start = strpos( $url, '#' );
1973 if ( $start !== false && $start < $end ) {
1974 $ret = self
::normalizeUrlComponent(
1975 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1979 # Query part - 'query' minus &=+;
1980 $start = strpos( $url, '?' );
1981 if ( $start !== false && $start < $end ) {
1982 $ret = self
::normalizeUrlComponent(
1983 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1987 # Scheme and path part - 'pchar'
1988 # (we assume no userinfo or encoded colons in the host)
1989 $ret = self
::normalizeUrlComponent(
1990 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1995 private static function normalizeUrlComponent( $component, $unsafe ) {
1996 $callback = function ( $matches ) use ( $unsafe ) {
1997 $char = urldecode( $matches[0] );
1998 $ord = ord( $char );
1999 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2003 # Leave it escaped, but use uppercase for a-f
2004 return strtoupper( $matches[0] );
2007 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2011 * make an image if it's allowed, either through the global
2012 * option, through the exception, or through the on-wiki whitelist
2014 * @param string $url
2018 private function maybeMakeExternalImage( $url ) {
2019 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
2020 $imagesexception = !empty( $imagesfrom );
2022 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2023 if ( $imagesexception && is_array( $imagesfrom ) ) {
2024 $imagematch = false;
2025 foreach ( $imagesfrom as $match ) {
2026 if ( strpos( $url, $match ) === 0 ) {
2031 } elseif ( $imagesexception ) {
2032 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2034 $imagematch = false;
2037 if ( $this->mOptions
->getAllowExternalImages()
2038 ||
( $imagesexception && $imagematch )
2040 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
2042 $text = Linker
::makeExternalImage( $url );
2045 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
2046 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
2048 $whitelist = explode(
2050 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2053 foreach ( $whitelist as $entry ) {
2054 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2055 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2058 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2059 # Image matches a whitelist entry
2060 $text = Linker
::makeExternalImage( $url );
2069 * Process [[ ]] wikilinks
2073 * @return string Processed text
2077 public function replaceInternalLinks( $s ) {
2078 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2083 * Process [[ ]] wikilinks (RIL)
2085 * @throws MWException
2086 * @return LinkHolderArray
2090 public function replaceInternalLinks2( &$s ) {
2091 global $wgExtraInterlanguageLinkPrefixes;
2093 static $tc = false, $e1, $e1_img;
2094 # the % is needed to support urlencoded titles as well
2096 $tc = Title
::legalChars() . '#%';
2097 # Match a link having the form [[namespace:link|alternate]]trail
2098 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2099 # Match cases where there is no "]]", which might still be images
2100 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2103 $holders = new LinkHolderArray( $this );
2105 # split the entire text string on occurrences of [[
2106 $a = StringUtils
::explode( '[[', ' ' . $s );
2107 # get the first element (all text up to first [[), and remove the space we added
2110 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2111 $s = substr( $s, 1 );
2113 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2115 if ( $useLinkPrefixExtension ) {
2116 # Match the end of a line for a word that's not followed by whitespace,
2117 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2119 $charset = $wgContLang->linkPrefixCharset();
2120 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2123 if ( is_null( $this->mTitle
) ) {
2124 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2126 $nottalk = !$this->mTitle
->isTalkPage();
2128 if ( $useLinkPrefixExtension ) {
2130 if ( preg_match( $e2, $s, $m ) ) {
2131 $first_prefix = $m[2];
2133 $first_prefix = false;
2139 $useSubpages = $this->areSubpagesAllowed();
2141 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2142 # Loop for each link
2143 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2144 // @codingStandardsIgnoreEnd
2146 # Check for excessive memory usage
2147 if ( $holders->isBig() ) {
2149 # Do the existence check, replace the link holders and clear the array
2150 $holders->replace( $s );
2154 if ( $useLinkPrefixExtension ) {
2155 if ( preg_match( $e2, $s, $m ) ) {
2162 if ( $first_prefix ) {
2163 $prefix = $first_prefix;
2164 $first_prefix = false;
2168 $might_be_img = false;
2170 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2172 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2173 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2174 # the real problem is with the $e1 regex
2176 # Still some problems for cases where the ] is meant to be outside punctuation,
2177 # and no image is in sight. See T4095.
2179 && substr( $m[3], 0, 1 ) === ']'
2180 && strpos( $text, '[' ) !== false
2182 $text .= ']'; # so that replaceExternalLinks($text) works later
2183 $m[3] = substr( $m[3], 1 );
2185 # fix up urlencoded title texts
2186 if ( strpos( $m[1], '%' ) !== false ) {
2187 # Should anchors '#' also be rejected?
2188 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2191 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2192 # Invalid, but might be an image with a link in its caption
2193 $might_be_img = true;
2195 if ( strpos( $m[1], '%' ) !== false ) {
2196 $m[1] = str_replace( [ '<', '>' ], [ '<', '>' ], rawurldecode( $m[1] ) );
2199 } else { # Invalid form; output directly
2200 $s .= $prefix . '[[' . $line;
2206 # Don't allow internal links to pages containing
2207 # PROTO: where PROTO is a valid URL protocol; these
2208 # should be external links.
2209 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2210 $s .= $prefix . '[[' . $line;
2214 # Make subpage if necessary
2215 if ( $useSubpages ) {
2216 $link = $this->maybeDoSubpageLink( $origLink, $text );
2221 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2223 # Strip off leading ':'
2224 $link = substr( $link, 1 );
2227 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2228 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2229 if ( $nt === null ) {
2230 $s .= $prefix . '[[' . $line;
2234 $ns = $nt->getNamespace();
2235 $iw = $nt->getInterwiki();
2237 if ( $might_be_img ) { # if this is actually an invalid link
2238 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2241 # look at the next 'line' to see if we can close it there
2243 $next_line = $a->current();
2244 if ( $next_line === false ||
$next_line === null ) {
2247 $m = explode( ']]', $next_line, 3 );
2248 if ( count( $m ) == 3 ) {
2249 # the first ]] closes the inner link, the second the image
2251 $text .= "[[{$m[0]}]]{$m[1]}";
2254 } elseif ( count( $m ) == 2 ) {
2255 # if there's exactly one ]] that's fine, we'll keep looking
2256 $text .= "[[{$m[0]}]]{$m[1]}";
2258 # if $next_line is invalid too, we need look no further
2259 $text .= '[[' . $next_line;
2264 # we couldn't find the end of this imageLink, so output it raw
2265 # but don't ignore what might be perfectly normal links in the text we've examined
2266 $holders->merge( $this->replaceInternalLinks2( $text ) );
2267 $s .= "{$prefix}[[$link|$text";
2268 # note: no $trail, because without an end, there *is* no trail
2271 } else { # it's not an image, so output it raw
2272 $s .= "{$prefix}[[$link|$text";
2273 # note: no $trail, because without an end, there *is* no trail
2278 $wasblank = ( $text == '' );
2282 # T6598 madness. Handle the quotes only if they come from the alternate part
2283 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2284 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2285 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2286 $text = $this->doQuotes( $text );
2289 # Link not escaped by : , create the various objects
2290 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2293 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2294 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2295 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2298 # T26502: filter duplicates
2299 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2300 $this->mLangLinkLanguages
[$iw] = true;
2301 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2304 $s = rtrim( $s . $prefix );
2305 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2309 if ( $ns == NS_FILE
) {
2310 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2312 # if no parameters were passed, $text
2313 # becomes something like "File:Foo.png",
2314 # which we don't want to pass on to the
2318 # recursively parse links inside the image caption
2319 # actually, this will parse them in any other parameters, too,
2320 # but it might be hard to fix that, and it doesn't matter ATM
2321 $text = $this->replaceExternalLinks( $text );
2322 $holders->merge( $this->replaceInternalLinks2( $text ) );
2324 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2325 $s .= $prefix . $this->armorLinks(
2326 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2329 } elseif ( $ns == NS_CATEGORY
) {
2330 $s = rtrim( $s . "\n" ); # T2087
2333 $sortkey = $this->getDefaultSort();
2337 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2338 $sortkey = str_replace( "\n", '', $sortkey );
2339 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2340 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2343 * Strip the whitespace Category links produce, see T2087
2345 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2351 # Self-link checking. For some languages, variants of the title are checked in
2352 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2353 # for linking to a different variant.
2354 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2355 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2359 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2360 # @todo FIXME: Should do batch file existence checks, see comment below
2361 if ( $ns == NS_MEDIA
) {
2362 # Give extensions a chance to select the file revision for us
2365 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2366 [ $this, $nt, &$options, &$descQuery ] );
2367 # Fetch and register the file (file title may be different via hooks)
2368 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2369 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2370 $s .= $prefix . $this->armorLinks(
2371 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2375 # Some titles, such as valid special pages or files in foreign repos, should
2376 # be shown as bluelinks even though they're not included in the page table
2377 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2378 # batch file existence checks for NS_FILE and NS_MEDIA
2379 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2380 $this->mOutput
->addLink( $nt );
2381 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2383 # Links will be added to the output link list after checking
2384 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2391 * Render a forced-blue link inline; protect against double expansion of
2392 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2393 * Since this little disaster has to split off the trail text to avoid
2394 * breaking URLs in the following text without breaking trails on the
2395 * wiki links, it's been made into a horrible function.
2398 * @param string $text
2399 * @param string $trail
2400 * @param string $prefix
2401 * @return string HTML-wikitext mix oh yuck
2403 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2404 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2406 if ( $text == '' ) {
2407 $text = htmlspecialchars( $nt->getPrefixedText() );
2410 $link = $this->getLinkRenderer()->makeKnownLink(
2411 $nt, new HtmlArmor( "$prefix$text$inside" )
2414 return $this->armorLinks( $link ) . $trail;
2418 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2419 * going to go through further parsing steps before inline URL expansion.
2421 * Not needed quite as much as it used to be since free links are a bit
2422 * more sensible these days. But bracketed links are still an issue.
2424 * @param string $text More-or-less HTML
2425 * @return string Less-or-more HTML with NOPARSE bits
2427 public function armorLinks( $text ) {
2428 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2429 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2433 * Return true if subpage links should be expanded on this page.
2436 public function areSubpagesAllowed() {
2437 # Some namespaces don't allow subpages
2438 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2442 * Handle link to subpage if necessary
2444 * @param string $target The source of the link
2445 * @param string &$text The link text, modified as necessary
2446 * @return string The full name of the link
2449 public function maybeDoSubpageLink( $target, &$text ) {
2450 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2454 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2456 * @param string $text
2457 * @param bool $linestart Whether or not this is at the start of a line.
2459 * @return string The lists rendered as HTML
2461 public function doBlockLevels( $text, $linestart ) {
2462 return BlockLevelPass
::doBlockLevels( $text, $linestart );
2466 * Return value of a magic variable (like PAGENAME)
2471 * @param bool|PPFrame $frame
2473 * @throws MWException
2476 public function getVariableValue( $index, $frame = false ) {
2477 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2478 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2480 if ( is_null( $this->mTitle
) ) {
2481 // If no title set, bad things are going to happen
2482 // later. Title should always be set since this
2483 // should only be called in the middle of a parse
2484 // operation (but the unit-tests do funky stuff)
2485 throw new MWException( __METHOD__
. ' Should only be '
2486 . ' called while parsing (no title set)' );
2490 * Some of these require message or data lookups and can be
2491 * expensive to check many times.
2493 if ( Hooks
::run( 'ParserGetVariableValueVarCache', [ &$this, &$this->mVarCache
] ) ) {
2494 if ( isset( $this->mVarCache
[$index] ) ) {
2495 return $this->mVarCache
[$index];
2499 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2500 Hooks
::run( 'ParserGetVariableValueTs', [ &$this, &$ts ] );
2502 $pageLang = $this->getFunctionLang();
2508 case 'currentmonth':
2509 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2511 case 'currentmonth1':
2512 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2514 case 'currentmonthname':
2515 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2517 case 'currentmonthnamegen':
2518 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2520 case 'currentmonthabbrev':
2521 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2524 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2527 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2530 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2533 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2535 case 'localmonthname':
2536 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2538 case 'localmonthnamegen':
2539 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2541 case 'localmonthabbrev':
2542 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2545 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2548 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2551 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2554 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2556 case 'fullpagename':
2557 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2559 case 'fullpagenamee':
2560 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2563 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2565 case 'subpagenamee':
2566 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2568 case 'rootpagename':
2569 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2571 case 'rootpagenamee':
2572 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2575 $this->mTitle
->getRootText()
2578 case 'basepagename':
2579 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2581 case 'basepagenamee':
2582 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2585 $this->mTitle
->getBaseText()
2588 case 'talkpagename':
2589 if ( $this->mTitle
->canTalk() ) {
2590 $talkPage = $this->mTitle
->getTalkPage();
2591 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2596 case 'talkpagenamee':
2597 if ( $this->mTitle
->canTalk() ) {
2598 $talkPage = $this->mTitle
->getTalkPage();
2599 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2604 case 'subjectpagename':
2605 $subjPage = $this->mTitle
->getSubjectPage();
2606 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2608 case 'subjectpagenamee':
2609 $subjPage = $this->mTitle
->getSubjectPage();
2610 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2612 case 'pageid': // requested in T25427
2613 $pageid = $this->getTitle()->getArticleID();
2614 if ( $pageid == 0 ) {
2615 # 0 means the page doesn't exist in the database,
2616 # which means the user is previewing a new page.
2617 # The vary-revision flag must be set, because the magic word
2618 # will have a different value once the page is saved.
2619 $this->mOutput
->setFlag( 'vary-revision' );
2620 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2622 $value = $pageid ?
$pageid : null;
2625 # Let the edit saving system know we should parse the page
2626 # *after* a revision ID has been assigned.
2627 $this->mOutput
->setFlag( 'vary-revision-id' );
2628 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2629 $value = $this->mRevisionId
;
2630 if ( !$value && $this->mOptions
->getSpeculativeRevIdCallback() ) {
2631 $value = call_user_func( $this->mOptions
->getSpeculativeRevIdCallback() );
2632 $this->mOutput
->setSpeculativeRevIdUsed( $value );
2636 # Let the edit saving system know we should parse the page
2637 # *after* a revision ID has been assigned. This is for null edits.
2638 $this->mOutput
->setFlag( 'vary-revision' );
2639 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2640 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2642 case 'revisionday2':
2643 # Let the edit saving system know we should parse the page
2644 # *after* a revision ID has been assigned. This is for null edits.
2645 $this->mOutput
->setFlag( 'vary-revision' );
2646 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2647 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2649 case 'revisionmonth':
2650 # Let the edit saving system know we should parse the page
2651 # *after* a revision ID has been assigned. This is for null edits.
2652 $this->mOutput
->setFlag( 'vary-revision' );
2653 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2654 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2656 case 'revisionmonth1':
2657 # Let the edit saving system know we should parse the page
2658 # *after* a revision ID has been assigned. This is for null edits.
2659 $this->mOutput
->setFlag( 'vary-revision' );
2660 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2661 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2663 case 'revisionyear':
2664 # Let the edit saving system know we should parse the page
2665 # *after* a revision ID has been assigned. This is for null edits.
2666 $this->mOutput
->setFlag( 'vary-revision' );
2667 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2668 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2670 case 'revisiontimestamp':
2671 # Let the edit saving system know we should parse the page
2672 # *after* a revision ID has been assigned. This is for null edits.
2673 $this->mOutput
->setFlag( 'vary-revision' );
2674 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2675 $value = $this->getRevisionTimestamp();
2677 case 'revisionuser':
2678 # Let the edit saving system know we should parse the page
2679 # *after* a revision ID has been assigned for null edits.
2680 $this->mOutput
->setFlag( 'vary-user' );
2681 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-user...\n" );
2682 $value = $this->getRevisionUser();
2684 case 'revisionsize':
2685 $value = $this->getRevisionSize();
2688 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2691 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2693 case 'namespacenumber':
2694 $value = $this->mTitle
->getNamespace();
2697 $value = $this->mTitle
->canTalk()
2698 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
2702 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2704 case 'subjectspace':
2705 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2707 case 'subjectspacee':
2708 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2710 case 'currentdayname':
2711 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2714 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2717 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2720 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2723 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2724 # int to remove the padding
2725 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2728 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2730 case 'localdayname':
2731 $value = $pageLang->getWeekdayName(
2732 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
2736 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2739 $value = $pageLang->time(
2740 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
2746 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2749 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2750 # int to remove the padding
2751 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2754 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2756 case 'numberofarticles':
2757 $value = $pageLang->formatNum( SiteStats
::articles() );
2759 case 'numberoffiles':
2760 $value = $pageLang->formatNum( SiteStats
::images() );
2762 case 'numberofusers':
2763 $value = $pageLang->formatNum( SiteStats
::users() );
2765 case 'numberofactiveusers':
2766 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2768 case 'numberofpages':
2769 $value = $pageLang->formatNum( SiteStats
::pages() );
2771 case 'numberofadmins':
2772 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2774 case 'numberofedits':
2775 $value = $pageLang->formatNum( SiteStats
::edits() );
2777 case 'currenttimestamp':
2778 $value = wfTimestamp( TS_MW
, $ts );
2780 case 'localtimestamp':
2781 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2783 case 'currentversion':
2784 $value = SpecialVersion
::getVersion();
2787 return $wgArticlePath;
2793 return $wgServerName;
2795 return $wgScriptPath;
2797 return $wgStylePath;
2798 case 'directionmark':
2799 return $pageLang->getDirMark();
2800 case 'contentlanguage':
2801 global $wgLanguageCode;
2802 return $wgLanguageCode;
2803 case 'pagelanguage':
2804 $value = $pageLang->getCode();
2806 case 'cascadingsources':
2807 $value = CoreParserFunctions
::cascadingsources( $this );
2812 'ParserGetVariableValueSwitch',
2813 [ &$this, &$this->mVarCache
, &$index, &$ret, &$frame ]
2820 $this->mVarCache
[$index] = $value;
2827 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2831 public function initialiseVariables() {
2832 $variableIDs = MagicWord
::getVariableIDs();
2833 $substIDs = MagicWord
::getSubstIDs();
2835 $this->mVariables
= new MagicWordArray( $variableIDs );
2836 $this->mSubstWords
= new MagicWordArray( $substIDs );
2840 * Preprocess some wikitext and return the document tree.
2841 * This is the ghost of replace_variables().
2843 * @param string $text The text to parse
2844 * @param int $flags Bitwise combination of:
2845 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2846 * included. Default is to assume a direct page view.
2848 * The generated DOM tree must depend only on the input text and the flags.
2849 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2851 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2852 * change in the DOM tree for a given text, must be passed through the section identifier
2853 * in the section edit link and thus back to extractSections().
2855 * The output of this function is currently only cached in process memory, but a persistent
2856 * cache may be implemented at a later date which takes further advantage of these strict
2857 * dependency requirements.
2861 public function preprocessToDom( $text, $flags = 0 ) {
2862 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2867 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2873 public static function splitWhitespace( $s ) {
2874 $ltrimmed = ltrim( $s );
2875 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2876 $trimmed = rtrim( $ltrimmed );
2877 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2879 $w2 = substr( $ltrimmed, -$diff );
2883 return [ $w1, $trimmed, $w2 ];
2887 * Replace magic variables, templates, and template arguments
2888 * with the appropriate text. Templates are substituted recursively,
2889 * taking care to avoid infinite loops.
2891 * Note that the substitution depends on value of $mOutputType:
2892 * self::OT_WIKI: only {{subst:}} templates
2893 * self::OT_PREPROCESS: templates but not extension tags
2894 * self::OT_HTML: all templates and extension tags
2896 * @param string $text The text to transform
2897 * @param bool|PPFrame $frame Object describing the arguments passed to the
2898 * template. Arguments may also be provided as an associative array, as
2899 * was the usual case before MW1.12. Providing arguments this way may be
2900 * useful for extensions wishing to perform variable replacement
2902 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2903 * double-brace expansion.
2906 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2907 # Is there any text? Also, Prevent too big inclusions!
2908 $textSize = strlen( $text );
2909 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
2913 if ( $frame === false ) {
2914 $frame = $this->getPreprocessor()->newFrame();
2915 } elseif ( !( $frame instanceof PPFrame
) ) {
2916 wfDebug( __METHOD__
. " called using plain parameters instead of "
2917 . "a PPFrame instance. Creating custom frame.\n" );
2918 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2921 $dom = $this->preprocessToDom( $text );
2922 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2923 $text = $frame->expand( $dom, $flags );
2929 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2931 * @param array $args
2935 public static function createAssocArgs( $args ) {
2938 foreach ( $args as $arg ) {
2939 $eqpos = strpos( $arg, '=' );
2940 if ( $eqpos === false ) {
2941 $assocArgs[$index++
] = $arg;
2943 $name = trim( substr( $arg, 0, $eqpos ) );
2944 $value = trim( substr( $arg, $eqpos +
1 ) );
2945 if ( $value === false ) {
2948 if ( $name !== false ) {
2949 $assocArgs[$name] = $value;
2958 * Warn the user when a parser limitation is reached
2959 * Will warn at most once the user per limitation type
2961 * The results are shown during preview and run through the Parser (See EditPage.php)
2963 * @param string $limitationType Should be one of:
2964 * 'expensive-parserfunction' (corresponding messages:
2965 * 'expensive-parserfunction-warning',
2966 * 'expensive-parserfunction-category')
2967 * 'post-expand-template-argument' (corresponding messages:
2968 * 'post-expand-template-argument-warning',
2969 * 'post-expand-template-argument-category')
2970 * 'post-expand-template-inclusion' (corresponding messages:
2971 * 'post-expand-template-inclusion-warning',
2972 * 'post-expand-template-inclusion-category')
2973 * 'node-count-exceeded' (corresponding messages:
2974 * 'node-count-exceeded-warning',
2975 * 'node-count-exceeded-category')
2976 * 'expansion-depth-exceeded' (corresponding messages:
2977 * 'expansion-depth-exceeded-warning',
2978 * 'expansion-depth-exceeded-category')
2979 * @param string|int|null $current Current value
2980 * @param string|int|null $max Maximum allowed, when an explicit limit has been
2981 * exceeded, provide the values (optional)
2983 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
2984 # does no harm if $current and $max are present but are unnecessary for the message
2985 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
2986 # only during preview, and that would split the parser cache unnecessarily.
2987 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
2989 $this->mOutput
->addWarning( $warning );
2990 $this->addTrackingCategory( "$limitationType-category" );
2994 * Return the text of a template, after recursively
2995 * replacing any variables or templates within the template.
2997 * @param array $piece The parts of the template
2998 * $piece['title']: the title, i.e. the part before the |
2999 * $piece['parts']: the parameter array
3000 * $piece['lineStart']: whether the brace was at the start of a line
3001 * @param PPFrame $frame The current frame, contains template arguments
3003 * @return string The text of the template
3005 public function braceSubstitution( $piece, $frame ) {
3009 // $text has been filled
3011 // wiki markup in $text should be escaped
3013 // $text is HTML, armour it against wikitext transformation
3015 // Force interwiki transclusion to be done in raw mode not rendered
3016 $forceRawInterwiki = false;
3017 // $text is a DOM node needing expansion in a child frame
3018 $isChildObj = false;
3019 // $text is a DOM node needing expansion in the current frame
3020 $isLocalObj = false;
3022 # Title object, where $text came from
3025 # $part1 is the bit before the first |, and must contain only title characters.
3026 # Various prefixes will be stripped from it later.
3027 $titleWithSpaces = $frame->expand( $piece['title'] );
3028 $part1 = trim( $titleWithSpaces );
3031 # Original title text preserved for various purposes
3032 $originalTitle = $part1;
3034 # $args is a list of argument nodes, starting from index 0, not including $part1
3035 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3036 # below won't work b/c this $args isn't an object
3037 $args = ( null == $piece['parts'] ) ?
[] : $piece['parts'];
3039 $profileSection = null; // profile templates
3043 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3045 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3046 # Decide whether to expand template or keep wikitext as-is.
3047 if ( $this->ot
['wiki'] ) {
3048 if ( $substMatch === false ) {
3049 $literal = true; # literal when in PST with no prefix
3051 $literal = false; # expand when in PST with subst: or safesubst:
3054 if ( $substMatch == 'subst' ) {
3055 $literal = true; # literal when not in PST with plain subst:
3057 $literal = false; # expand when not in PST with safesubst: or no prefix
3061 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3068 if ( !$found && $args->getLength() == 0 ) {
3069 $id = $this->mVariables
->matchStartToEnd( $part1 );
3070 if ( $id !== false ) {
3071 $text = $this->getVariableValue( $id, $frame );
3072 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3073 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3079 # MSG, MSGNW and RAW
3082 $mwMsgnw = MagicWord
::get( 'msgnw' );
3083 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3086 # Remove obsolete MSG:
3087 $mwMsg = MagicWord
::get( 'msg' );
3088 $mwMsg->matchStartAndRemove( $part1 );
3092 $mwRaw = MagicWord
::get( 'raw' );
3093 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3094 $forceRawInterwiki = true;
3100 $colonPos = strpos( $part1, ':' );
3101 if ( $colonPos !== false ) {
3102 $func = substr( $part1, 0, $colonPos );
3103 $funcArgs = [ trim( substr( $part1, $colonPos +
1 ) ) ];
3104 $argsLength = $args->getLength();
3105 for ( $i = 0; $i < $argsLength; $i++
) {
3106 $funcArgs[] = $args->item( $i );
3109 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3110 } catch ( Exception
$ex ) {
3114 # The interface for parser functions allows for extracting
3115 # flags into the local scope. Extract any forwarded flags
3121 # Finish mangling title and then check for loops.
3122 # Set $title to a Title object and $titleText to the PDBK
3125 # Split the title into page and subpage
3127 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3128 if ( $part1 !== $relative ) {
3130 $ns = $this->mTitle
->getNamespace();
3132 $title = Title
::newFromText( $part1, $ns );
3134 $titleText = $title->getPrefixedText();
3135 # Check for language variants if the template is not found
3136 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3137 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3139 # Do recursion depth check
3140 $limit = $this->mOptions
->getMaxTemplateDepth();
3141 if ( $frame->depth
>= $limit ) {
3143 $text = '<span class="error">'
3144 . wfMessage( 'parser-template-recursion-depth-warning' )
3145 ->numParams( $limit )->inContentLanguage()->text()
3151 # Load from database
3152 if ( !$found && $title ) {
3153 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3154 if ( !$title->isExternal() ) {
3155 if ( $title->isSpecialPage()
3156 && $this->mOptions
->getAllowSpecialInclusion()
3157 && $this->ot
['html']
3159 $specialPage = SpecialPageFactory
::getPage( $title->getDBkey() );
3160 // Pass the template arguments as URL parameters.
3161 // "uselang" will have no effect since the Language object
3162 // is forced to the one defined in ParserOptions.
3164 $argsLength = $args->getLength();
3165 for ( $i = 0; $i < $argsLength; $i++
) {
3166 $bits = $args->item( $i )->splitArg();
3167 if ( strval( $bits['index'] ) === '' ) {
3168 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3169 $value = trim( $frame->expand( $bits['value'] ) );
3170 $pageArgs[$name] = $value;
3174 // Create a new context to execute the special page
3175 $context = new RequestContext
;
3176 $context->setTitle( $title );
3177 $context->setRequest( new FauxRequest( $pageArgs ) );
3178 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3179 $context->setUser( $this->getUser() );
3181 // If this page is cached, then we better not be per user.
3182 $context->setUser( User
::newFromName( '127.0.0.1', false ) );
3184 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3185 $ret = SpecialPageFactory
::capturePath(
3186 $title, $context, $this->getLinkRenderer() );
3188 $text = $context->getOutput()->getHTML();
3189 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3192 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3193 $this->mOutput
->updateRuntimeAdaptiveExpiry(
3194 $specialPage->maxIncludeCacheTime()
3198 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3199 $found = false; # access denied
3200 wfDebug( __METHOD__
. ": template inclusion denied for " .
3201 $title->getPrefixedDBkey() . "\n" );
3203 list( $text, $title ) = $this->getTemplateDom( $title );
3204 if ( $text !== false ) {
3210 # If the title is valid but undisplayable, make a link to it
3211 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3212 $text = "[[:$titleText]]";
3215 } elseif ( $title->isTrans() ) {
3216 # Interwiki transclusion
3217 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3218 $text = $this->interwikiTransclude( $title, 'render' );
3221 $text = $this->interwikiTransclude( $title, 'raw' );
3222 # Preprocess it like a template
3223 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3229 # Do infinite loop check
3230 # This has to be done after redirect resolution to avoid infinite loops via redirects
3231 if ( !$frame->loopCheck( $title ) ) {
3233 $text = '<span class="error">'
3234 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3236 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3240 # If we haven't found text to substitute by now, we're done
3241 # Recover the source wikitext and return it
3243 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3244 if ( $profileSection ) {
3245 $this->mProfiler
->scopedProfileOut( $profileSection );
3247 return [ 'object' => $text ];
3250 # Expand DOM-style return values in a child frame
3251 if ( $isChildObj ) {
3252 # Clean up argument array
3253 $newFrame = $frame->newChild( $args, $title );
3256 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3257 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3258 # Expansion is eligible for the empty-frame cache
3259 $text = $newFrame->cachedExpand( $titleText, $text );
3261 # Uncached expansion
3262 $text = $newFrame->expand( $text );
3265 if ( $isLocalObj && $nowiki ) {
3266 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3267 $isLocalObj = false;
3270 if ( $profileSection ) {
3271 $this->mProfiler
->scopedProfileOut( $profileSection );
3274 # Replace raw HTML by a placeholder
3276 $text = $this->insertStripItem( $text );
3277 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3278 # Escape nowiki-style return values
3279 $text = wfEscapeWikiText( $text );
3280 } elseif ( is_string( $text )
3281 && !$piece['lineStart']
3282 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3284 # T2529: if the template begins with a table or block-level
3285 # element, it should be treated as beginning a new line.
3286 # This behavior is somewhat controversial.
3287 $text = "\n" . $text;
3290 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3291 # Error, oversize inclusion
3292 if ( $titleText !== false ) {
3293 # Make a working, properly escaped link if possible (T25588)
3294 $text = "[[:$titleText]]";
3296 # This will probably not be a working link, but at least it may
3297 # provide some hint of where the problem is
3298 preg_replace( '/^:/', '', $originalTitle );
3299 $text = "[[:$originalTitle]]";
3301 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3302 . 'post-expand include size too large -->' );
3303 $this->limitationWarn( 'post-expand-template-inclusion' );
3306 if ( $isLocalObj ) {
3307 $ret = [ 'object' => $text ];
3309 $ret = [ 'text' => $text ];
3316 * Call a parser function and return an array with text and flags.
3318 * The returned array will always contain a boolean 'found', indicating
3319 * whether the parser function was found or not. It may also contain the
3321 * text: string|object, resulting wikitext or PP DOM object
3322 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3323 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3324 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3325 * nowiki: bool, wiki markup in $text should be escaped
3328 * @param PPFrame $frame The current frame, contains template arguments
3329 * @param string $function Function name
3330 * @param array $args Arguments to the function
3331 * @throws MWException
3334 public function callParserFunction( $frame, $function, array $args = [] ) {
3337 # Case sensitive functions
3338 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3339 $function = $this->mFunctionSynonyms
[1][$function];
3341 # Case insensitive functions
3342 $function = $wgContLang->lc( $function );
3343 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3344 $function = $this->mFunctionSynonyms
[0][$function];
3346 return [ 'found' => false ];
3350 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3352 # Workaround for PHP bug 35229 and similar
3353 if ( !is_callable( $callback ) ) {
3354 throw new MWException( "Tag hook for $function is not callable\n" );
3357 $allArgs = [ &$this ];
3358 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3359 # Convert arguments to PPNodes and collect for appending to $allArgs
3361 foreach ( $args as $k => $v ) {
3362 if ( $v instanceof PPNode ||
$k === 0 ) {
3365 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( [ $k => $v ] )->item( 0 );
3369 # Add a frame parameter, and pass the arguments as an array
3370 $allArgs[] = $frame;
3371 $allArgs[] = $funcArgs;
3373 # Convert arguments to plain text and append to $allArgs
3374 foreach ( $args as $k => $v ) {
3375 if ( $v instanceof PPNode
) {
3376 $allArgs[] = trim( $frame->expand( $v ) );
3377 } elseif ( is_int( $k ) && $k >= 0 ) {
3378 $allArgs[] = trim( $v );
3380 $allArgs[] = trim( "$k=$v" );
3385 $result = call_user_func_array( $callback, $allArgs );
3387 # The interface for function hooks allows them to return a wikitext
3388 # string or an array containing the string and any flags. This mungs
3389 # things around to match what this method should return.
3390 if ( !is_array( $result ) ) {
3396 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3397 $result['text'] = $result[0];
3399 unset( $result[0] );
3406 $preprocessFlags = 0;
3407 if ( isset( $result['noparse'] ) ) {
3408 $noparse = $result['noparse'];
3410 if ( isset( $result['preprocessFlags'] ) ) {
3411 $preprocessFlags = $result['preprocessFlags'];
3415 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3416 $result['isChildObj'] = true;
3423 * Get the semi-parsed DOM representation of a template with a given title,
3424 * and its redirect destination title. Cached.
3426 * @param Title $title
3430 public function getTemplateDom( $title ) {
3431 $cacheTitle = $title;
3432 $titleText = $title->getPrefixedDBkey();
3434 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3435 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3436 $title = Title
::makeTitle( $ns, $dbk );
3437 $titleText = $title->getPrefixedDBkey();
3439 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3440 return [ $this->mTplDomCache
[$titleText], $title ];
3443 # Cache miss, go to the database
3444 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3446 if ( $text === false ) {
3447 $this->mTplDomCache
[$titleText] = false;
3448 return [ false, $title ];
3451 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3452 $this->mTplDomCache
[$titleText] = $dom;
3454 if ( !$title->equals( $cacheTitle ) ) {
3455 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3456 [ $title->getNamespace(), $cdb = $title->getDBkey() ];
3459 return [ $dom, $title ];
3463 * Fetch the current revision of a given title. Note that the revision
3464 * (and even the title) may not exist in the database, so everything
3465 * contributing to the output of the parser should use this method
3466 * where possible, rather than getting the revisions themselves. This
3467 * method also caches its results, so using it benefits performance.
3470 * @param Title $title
3473 public function fetchCurrentRevisionOfTitle( $title ) {
3474 $cacheKey = $title->getPrefixedDBkey();
3475 if ( !$this->currentRevisionCache
) {
3476 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3478 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3479 $this->currentRevisionCache
->set( $cacheKey,
3480 // Defaults to Parser::statelessFetchRevision()
3481 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3484 return $this->currentRevisionCache
->get( $cacheKey );
3488 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3489 * without passing them on to it.
3492 * @param Title $title
3493 * @param Parser|bool $parser
3494 * @return Revision|bool False if missing
3496 public static function statelessFetchRevision( Title
$title, $parser = false ) {
3497 $pageId = $title->getArticleID();
3498 $revId = $title->getLatestRevID();
3500 $rev = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $pageId, $revId );
3502 $rev->setTitle( $title );
3509 * Fetch the unparsed text of a template and register a reference to it.
3510 * @param Title $title
3511 * @return array ( string or false, Title )
3513 public function fetchTemplateAndTitle( $title ) {
3514 // Defaults to Parser::statelessFetchTemplate()
3515 $templateCb = $this->mOptions
->getTemplateCallback();
3516 $stuff = call_user_func( $templateCb, $title, $this );
3517 // We use U+007F DELETE to distinguish strip markers from regular text.
3518 $text = $stuff['text'];
3519 if ( is_string( $stuff['text'] ) ) {
3520 $text = strtr( $text, "\x7f", "?" );
3522 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3523 if ( isset( $stuff['deps'] ) ) {
3524 foreach ( $stuff['deps'] as $dep ) {
3525 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3526 if ( $dep['title']->equals( $this->getTitle() ) ) {
3527 // If we transclude ourselves, the final result
3528 // will change based on the new version of the page
3529 $this->mOutput
->setFlag( 'vary-revision' );
3533 return [ $text, $finalTitle ];
3537 * Fetch the unparsed text of a template and register a reference to it.
3538 * @param Title $title
3539 * @return string|bool
3541 public function fetchTemplate( $title ) {
3542 return $this->fetchTemplateAndTitle( $title )[0];
3546 * Static function to get a template
3547 * Can be overridden via ParserOptions::setTemplateCallback().
3549 * @param Title $title
3550 * @param bool|Parser $parser
3554 public static function statelessFetchTemplate( $title, $parser = false ) {
3555 $text = $skip = false;
3556 $finalTitle = $title;
3559 # Loop to fetch the article, with up to 1 redirect
3560 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3561 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3562 // @codingStandardsIgnoreEnd
3563 # Give extensions a chance to select the revision instead
3564 $id = false; # Assume current
3565 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3566 [ $parser, $title, &$skip, &$id ] );
3572 'page_id' => $title->getArticleID(),
3579 $rev = Revision
::newFromId( $id );
3580 } elseif ( $parser ) {
3581 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3583 $rev = Revision
::newFromTitle( $title );
3585 $rev_id = $rev ?
$rev->getId() : 0;
3586 # If there is no current revision, there is no page
3587 if ( $id === false && !$rev ) {
3588 $linkCache = LinkCache
::singleton();
3589 $linkCache->addBadLinkObj( $title );
3594 'page_id' => $title->getArticleID(),
3595 'rev_id' => $rev_id ];
3596 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3597 # We fetched a rev from a different title; register it too...
3599 'title' => $rev->getTitle(),
3600 'page_id' => $rev->getPage(),
3601 'rev_id' => $rev_id ];
3605 $content = $rev->getContent();
3606 $text = $content ?
$content->getWikitextForTransclusion() : null;
3608 Hooks
::run( 'ParserFetchTemplate',
3609 [ $parser, $title, $rev, &$text, &$deps ] );
3611 if ( $text === false ||
$text === null ) {
3615 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3617 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3618 if ( !$message->exists() ) {
3622 $content = $message->content();
3623 $text = $message->plain();
3631 $finalTitle = $title;
3632 $title = $content->getRedirectTarget();
3636 'finalTitle' => $finalTitle,
3641 * Fetch a file and its title and register a reference to it.
3642 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3643 * @param Title $title
3644 * @param array $options Array of options to RepoGroup::findFile
3647 public function fetchFile( $title, $options = [] ) {
3648 return $this->fetchFileAndTitle( $title, $options )[0];
3652 * Fetch a file and its title and register a reference to it.
3653 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3654 * @param Title $title
3655 * @param array $options Array of options to RepoGroup::findFile
3656 * @return array ( File or false, Title of file )
3658 public function fetchFileAndTitle( $title, $options = [] ) {
3659 $file = $this->fetchFileNoRegister( $title, $options );
3661 $time = $file ?
$file->getTimestamp() : false;
3662 $sha1 = $file ?
$file->getSha1() : false;
3663 # Register the file as a dependency...
3664 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3665 if ( $file && !$title->equals( $file->getTitle() ) ) {
3666 # Update fetched file title
3667 $title = $file->getTitle();
3668 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3670 return [ $file, $title ];
3674 * Helper function for fetchFileAndTitle.
3676 * Also useful if you need to fetch a file but not use it yet,
3677 * for example to get the file's handler.
3679 * @param Title $title
3680 * @param array $options Array of options to RepoGroup::findFile
3683 protected function fetchFileNoRegister( $title, $options = [] ) {
3684 if ( isset( $options['broken'] ) ) {
3685 $file = false; // broken thumbnail forced by hook
3686 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3687 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3688 } else { // get by (name,timestamp)
3689 $file = wfFindFile( $title, $options );
3695 * Transclude an interwiki link.
3697 * @param Title $title
3698 * @param string $action
3702 public function interwikiTransclude( $title, $action ) {
3703 global $wgEnableScaryTranscluding;
3705 if ( !$wgEnableScaryTranscluding ) {
3706 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3709 $url = $title->getFullURL( [ 'action' => $action ] );
3711 if ( strlen( $url ) > 255 ) {
3712 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3714 return $this->fetchScaryTemplateMaybeFromCache( $url );
3718 * @param string $url
3719 * @return mixed|string
3721 public function fetchScaryTemplateMaybeFromCache( $url ) {
3722 global $wgTranscludeCacheExpiry;
3723 $dbr = wfGetDB( DB_REPLICA
);
3724 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3725 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3726 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3728 return $obj->tc_contents
;
3731 $req = MWHttpRequest
::factory( $url, [], __METHOD__
);
3732 $status = $req->execute(); // Status object
3733 if ( $status->isOK() ) {
3734 $text = $req->getContent();
3735 } elseif ( $req->getStatus() != 200 ) {
3736 // Though we failed to fetch the content, this status is useless.
3737 return wfMessage( 'scarytranscludefailed-httpstatus' )
3738 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3740 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3743 $dbw = wfGetDB( DB_MASTER
);
3744 $dbw->replace( 'transcache', [ 'tc_url' ], [
3746 'tc_time' => $dbw->timestamp( time() ),
3747 'tc_contents' => $text
3753 * Triple brace replacement -- used for template arguments
3756 * @param array $piece
3757 * @param PPFrame $frame
3761 public function argSubstitution( $piece, $frame ) {
3764 $parts = $piece['parts'];
3765 $nameWithSpaces = $frame->expand( $piece['title'] );
3766 $argName = trim( $nameWithSpaces );
3768 $text = $frame->getArgument( $argName );
3769 if ( $text === false && $parts->getLength() > 0
3770 && ( $this->ot
['html']
3772 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3775 # No match in frame, use the supplied default
3776 $object = $parts->item( 0 )->getChildren();
3778 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3779 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3780 $this->limitationWarn( 'post-expand-template-argument' );
3783 if ( $text === false && $object === false ) {
3785 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3787 if ( $error !== false ) {
3790 if ( $object !== false ) {
3791 $ret = [ 'object' => $object ];
3793 $ret = [ 'text' => $text ];
3800 * Return the text to be used for a given extension tag.
3801 * This is the ghost of strip().
3803 * @param array $params Associative array of parameters:
3804 * name PPNode for the tag name
3805 * attr PPNode for unparsed text where tag attributes are thought to be
3806 * attributes Optional associative array of parsed attributes
3807 * inner Contents of extension element
3808 * noClose Original text did not have a close tag
3809 * @param PPFrame $frame
3811 * @throws MWException
3814 public function extensionSubstitution( $params, $frame ) {
3815 static $errorStr = '<span class="error">';
3816 static $errorLen = 20;
3818 $name = $frame->expand( $params['name'] );
3819 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3820 // Probably expansion depth or node count exceeded. Just punt the
3825 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3826 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3831 // We can't safely check if the expansion for $content resulted in an
3832 // error, because the content could happen to be the error string
3834 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3836 $marker = self
::MARKER_PREFIX
. "-$name-"
3837 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3839 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3840 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3841 if ( $isFunctionTag ) {
3842 $markerType = 'none';
3844 $markerType = 'general';
3846 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3847 $name = strtolower( $name );
3848 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3849 if ( isset( $params['attributes'] ) ) {
3850 $attributes = $attributes +
$params['attributes'];
3853 if ( isset( $this->mTagHooks
[$name] ) ) {
3854 # Workaround for PHP bug 35229 and similar
3855 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3856 throw new MWException( "Tag hook for $name is not callable\n" );
3858 $output = call_user_func_array( $this->mTagHooks
[$name],
3859 [ $content, $attributes, $this, $frame ] );
3860 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3861 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3862 if ( !is_callable( $callback ) ) {
3863 throw new MWException( "Tag hook for $name is not callable\n" );
3866 $output = call_user_func_array( $callback, [ &$this, $frame, $content, $attributes ] );
3868 $output = '<span class="error">Invalid tag extension name: ' .
3869 htmlspecialchars( $name ) . '</span>';
3872 if ( is_array( $output ) ) {
3873 # Extract flags to local scope (to override $markerType)
3875 $output = $flags[0];
3880 if ( is_null( $attrText ) ) {
3883 if ( isset( $params['attributes'] ) ) {
3884 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3885 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3886 htmlspecialchars( $attrValue ) . '"';
3889 if ( $content === null ) {
3890 $output = "<$name$attrText/>";
3892 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3893 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3897 $output = "<$name$attrText>$content$close";
3901 if ( $markerType === 'none' ) {
3903 } elseif ( $markerType === 'nowiki' ) {
3904 $this->mStripState
->addNoWiki( $marker, $output );
3905 } elseif ( $markerType === 'general' ) {
3906 $this->mStripState
->addGeneral( $marker, $output );
3908 throw new MWException( __METHOD__
. ': invalid marker type' );
3914 * Increment an include size counter
3916 * @param string $type The type of expansion
3917 * @param int $size The size of the text
3918 * @return bool False if this inclusion would take it over the maximum, true otherwise
3920 public function incrementIncludeSize( $type, $size ) {
3921 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3924 $this->mIncludeSizes
[$type] +
= $size;
3930 * Increment the expensive function count
3932 * @return bool False if the limit has been exceeded
3934 public function incrementExpensiveFunctionCount() {
3935 $this->mExpensiveFunctionCount++
;
3936 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3940 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3941 * Fills $this->mDoubleUnderscores, returns the modified text
3943 * @param string $text
3947 public function doDoubleUnderscore( $text ) {
3949 # The position of __TOC__ needs to be recorded
3950 $mw = MagicWord
::get( 'toc' );
3951 if ( $mw->match( $text ) ) {
3952 $this->mShowToc
= true;
3953 $this->mForceTocPosition
= true;
3955 # Set a placeholder. At the end we'll fill it in with the TOC.
3956 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3958 # Only keep the first one.
3959 $text = $mw->replace( '', $text );
3962 # Now match and remove the rest of them
3963 $mwa = MagicWord
::getDoubleUnderscoreArray();
3964 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3966 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3967 $this->mOutput
->mNoGallery
= true;
3969 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3970 $this->mShowToc
= false;
3972 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
3973 && $this->mTitle
->getNamespace() == NS_CATEGORY
3975 $this->addTrackingCategory( 'hidden-category-category' );
3977 # (T10068) Allow control over whether robots index a page.
3978 # __INDEX__ always overrides __NOINDEX__, see T16899
3979 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3980 $this->mOutput
->setIndexPolicy( 'noindex' );
3981 $this->addTrackingCategory( 'noindex-category' );
3983 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3984 $this->mOutput
->setIndexPolicy( 'index' );
3985 $this->addTrackingCategory( 'index-category' );
3988 # Cache all double underscores in the database
3989 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3990 $this->mOutput
->setProperty( $key, '' );
3997 * @see ParserOutput::addTrackingCategory()
3998 * @param string $msg Message key
3999 * @return bool Whether the addition was successful
4001 public function addTrackingCategory( $msg ) {
4002 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4006 * This function accomplishes several tasks:
4007 * 1) Auto-number headings if that option is enabled
4008 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4009 * 3) Add a Table of contents on the top for users who have enabled the option
4010 * 4) Auto-anchor headings
4012 * It loops through all headlines, collects the necessary data, then splits up the
4013 * string and re-inserts the newly formatted headlines.
4015 * @param string $text
4016 * @param string $origText Original, untouched wikitext
4017 * @param bool $isMain
4018 * @return mixed|string
4021 public function formatHeadings( $text, $origText, $isMain = true ) {
4022 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4024 # Inhibit editsection links if requested in the page
4025 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4026 $maybeShowEditLink = $showEditLink = false;
4028 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4029 $showEditLink = $this->mOptions
->getEditSection();
4031 if ( $showEditLink ) {
4032 $this->mOutput
->setEditSectionTokens( true );
4035 # Get all headlines for numbering them and adding funky stuff like [edit]
4036 # links - this is for later, but we need the number of headlines right now
4038 $numMatches = preg_match_all(
4039 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4044 # if there are fewer than 4 headlines in the article, do not show TOC
4045 # unless it's been explicitly enabled.
4046 $enoughToc = $this->mShowToc
&&
4047 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4049 # Allow user to stipulate that a page should have a "new section"
4050 # link added via __NEWSECTIONLINK__
4051 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4052 $this->mOutput
->setNewSection( true );
4055 # Allow user to remove the "new section"
4056 # link via __NONEWSECTIONLINK__
4057 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4058 $this->mOutput
->hideNewSection( true );
4061 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4062 # override above conditions and always show TOC above first header
4063 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4064 $this->mShowToc
= true;
4072 # Ugh .. the TOC should have neat indentation levels which can be
4073 # passed to the skin functions. These are determined here
4077 $sublevelCount = [];
4083 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4084 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4085 $oldType = $this->mOutputType
;
4086 $this->setOutputType( self
::OT_WIKI
);
4087 $frame = $this->getPreprocessor()->newFrame();
4088 $root = $this->preprocessToDom( $origText );
4089 $node = $root->getFirstChild();
4094 $headlines = $numMatches !== false ?
$matches[3] : [];
4096 foreach ( $headlines as $headline ) {
4097 $isTemplate = false;
4099 $sectionIndex = false;
4101 $markerMatches = [];
4102 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4103 $serial = $markerMatches[1];
4104 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4105 $isTemplate = ( $titleText != $baseTitleText );
4106 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4110 $prevlevel = $level;
4112 $level = $matches[1][$headlineCount];
4114 if ( $level > $prevlevel ) {
4115 # Increase TOC level
4117 $sublevelCount[$toclevel] = 0;
4118 if ( $toclevel < $wgMaxTocLevel ) {
4119 $prevtoclevel = $toclevel;
4120 $toc .= Linker
::tocIndent();
4123 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4124 # Decrease TOC level, find level to jump to
4126 for ( $i = $toclevel; $i > 0; $i-- ) {
4127 if ( $levelCount[$i] == $level ) {
4128 # Found last matching level
4131 } elseif ( $levelCount[$i] < $level ) {
4132 # Found first matching level below current level
4140 if ( $toclevel < $wgMaxTocLevel ) {
4141 if ( $prevtoclevel < $wgMaxTocLevel ) {
4142 # Unindent only if the previous toc level was shown :p
4143 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4144 $prevtoclevel = $toclevel;
4146 $toc .= Linker
::tocLineEnd();
4150 # No change in level, end TOC line
4151 if ( $toclevel < $wgMaxTocLevel ) {
4152 $toc .= Linker
::tocLineEnd();
4156 $levelCount[$toclevel] = $level;
4158 # count number of headlines for each level
4159 $sublevelCount[$toclevel]++
;
4161 for ( $i = 1; $i <= $toclevel; $i++
) {
4162 if ( !empty( $sublevelCount[$i] ) ) {
4166 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4171 # The safe header is a version of the header text safe to use for links
4173 # Remove link placeholders by the link text.
4174 # <!--LINK number-->
4176 # link text with suffix
4177 # Do this before unstrip since link text can contain strip markers
4178 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4180 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4181 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4183 # Strip out HTML (first regex removes any tag not allowed)
4185 # * <sup> and <sub> (T10393)
4189 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4190 # * <s> and <strike> (T35715)
4191 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4192 # to allow setting directionality in toc items.
4193 $tocline = preg_replace(
4195 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4196 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4202 # Strip '<span></span>', which is the result from the above if
4203 # <span id="foo"></span> is used to produce an additional anchor
4205 $tocline = str_replace( '<span></span>', '', $tocline );
4207 $tocline = trim( $tocline );
4209 # For the anchor, strip out HTML-y stuff period
4210 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4211 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4213 # Save headline for section edit hint before it's escaped
4214 $headlineHint = $safeHeadline;
4216 if ( $wgExperimentalHtmlIds ) {
4217 # For reverse compatibility, provide an id that's
4218 # HTML4-compatible, like we used to.
4219 # It may be worth noting, academically, that it's possible for
4220 # the legacy anchor to conflict with a non-legacy headline
4221 # anchor on the page. In this case likely the "correct" thing
4222 # would be to either drop the legacy anchors or make sure
4223 # they're numbered first. However, this would require people
4224 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4225 # manually, so let's not bother worrying about it.
4226 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4227 [ 'noninitial', 'legacy' ] );
4228 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4230 if ( $legacyHeadline == $safeHeadline ) {
4231 # No reason to have both (in fact, we can't)
4232 $legacyHeadline = false;
4235 $legacyHeadline = false;
4236 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4240 # HTML names must be case-insensitively unique (T12721).
4241 # This does not apply to Unicode characters per
4242 # https://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4243 # @todo FIXME: We may be changing them depending on the current locale.
4244 $arrayKey = strtolower( $safeHeadline );
4245 if ( $legacyHeadline === false ) {
4246 $legacyArrayKey = false;
4248 $legacyArrayKey = strtolower( $legacyHeadline );
4251 # Create the anchor for linking from the TOC to the section
4252 $anchor = $safeHeadline;
4253 $legacyAnchor = $legacyHeadline;
4254 if ( isset( $refers[$arrayKey] ) ) {
4255 // @codingStandardsIgnoreStart
4256 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4257 // @codingStandardsIgnoreEnd
4259 $refers["${arrayKey}_$i"] = true;
4261 $refers[$arrayKey] = true;
4263 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4264 // @codingStandardsIgnoreStart
4265 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4266 // @codingStandardsIgnoreEnd
4267 $legacyAnchor .= "_$i";
4268 $refers["${legacyArrayKey}_$i"] = true;
4270 $refers[$legacyArrayKey] = true;
4273 # Don't number the heading if it is the only one (looks silly)
4274 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4275 # the two are different if the line contains a link
4276 $headline = Html
::element(
4278 [ 'class' => 'mw-headline-number' ],
4280 ) . ' ' . $headline;
4283 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4284 $toc .= Linker
::tocLine( $anchor, $tocline,
4285 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4288 # Add the section to the section tree
4289 # Find the DOM node for this header
4290 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4291 while ( $node && !$noOffset ) {
4292 if ( $node->getName() === 'h' ) {
4293 $bits = $node->splitHeading();
4294 if ( $bits['i'] == $sectionIndex ) {
4298 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4299 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4300 $node = $node->getNextSibling();
4303 'toclevel' => $toclevel,
4306 'number' => $numbering,
4307 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4308 'fromtitle' => $titleText,
4309 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4310 'anchor' => $anchor,
4313 # give headline the correct <h#> tag
4314 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4315 // Output edit section links as markers with styles that can be customized by skins
4316 if ( $isTemplate ) {
4317 # Put a T flag in the section identifier, to indicate to extractSections()
4318 # that sections inside <includeonly> should be counted.
4319 $editsectionPage = $titleText;
4320 $editsectionSection = "T-$sectionIndex";
4321 $editsectionContent = null;
4323 $editsectionPage = $this->mTitle
->getPrefixedText();
4324 $editsectionSection = $sectionIndex;
4325 $editsectionContent = $headlineHint;
4327 // We use a bit of pesudo-xml for editsection markers. The
4328 // language converter is run later on. Using a UNIQ style marker
4329 // leads to the converter screwing up the tokens when it
4330 // converts stuff. And trying to insert strip tags fails too. At
4331 // this point all real inputted tags have already been escaped,
4332 // so we don't have to worry about a user trying to input one of
4333 // these markers directly. We use a page and section attribute
4334 // to stop the language converter from converting these
4335 // important bits of data, but put the headline hint inside a
4336 // content block because the language converter is supposed to
4337 // be able to convert that piece of data.
4338 // Gets replaced with html in ParserOutput::getText
4339 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4340 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4341 if ( $editsectionContent !== null ) {
4342 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4349 $head[$headlineCount] = Linker
::makeHeadline( $level,
4350 $matches['attrib'][$headlineCount], $anchor, $headline,
4351 $editlink, $legacyAnchor );
4356 $this->setOutputType( $oldType );
4358 # Never ever show TOC if no headers
4359 if ( $numVisible < 1 ) {
4364 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4365 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4367 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4368 $this->mOutput
->setTOCHTML( $toc );
4369 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4370 $this->mOutput
->addModules( 'mediawiki.toc' );
4374 $this->mOutput
->setSections( $tocraw );
4377 # split up and insert constructed headlines
4378 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4381 // build an array of document sections
4383 foreach ( $blocks as $block ) {
4384 // $head is zero-based, sections aren't.
4385 if ( empty( $head[$i - 1] ) ) {
4386 $sections[$i] = $block;
4388 $sections[$i] = $head[$i - 1] . $block;
4392 * Send a hook, one per section.
4393 * The idea here is to be able to make section-level DIVs, but to do so in a
4394 * lower-impact, more correct way than r50769
4397 * $section : the section number
4398 * &$sectionContent : ref to the content of the section
4399 * $showEditLinks : boolean describing whether this section has an edit link
4401 Hooks
::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $showEditLink ] );
4406 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4407 // append the TOC at the beginning
4408 // Top anchor now in skin
4409 $sections[0] = $sections[0] . $toc . "\n";
4412 $full .= implode( '', $sections );
4414 if ( $this->mForceTocPosition
) {
4415 return str_replace( '<!--MWTOC-->', $toc, $full );
4422 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4423 * conversion, substituting signatures, {{subst:}} templates, etc.
4425 * @param string $text The text to transform
4426 * @param Title $title The Title object for the current article
4427 * @param User $user The User object describing the current user
4428 * @param ParserOptions $options Parsing options
4429 * @param bool $clearState Whether to clear the parser state first
4430 * @return string The altered wiki markup
4432 public function preSaveTransform( $text, Title
$title, User
$user,
4433 ParserOptions
$options, $clearState = true
4435 if ( $clearState ) {
4436 $magicScopeVariable = $this->lock();
4438 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4439 $this->setUser( $user );
4441 // We still normalize line endings for backwards-compatibility
4442 // with other code that just calls PST, but this should already
4443 // be handled in TextContent subclasses
4444 $text = TextContent
::normalizeLineEndings( $text );
4446 if ( $options->getPreSaveTransform() ) {
4447 $text = $this->pstPass2( $text, $user );
4449 $text = $this->mStripState
->unstripBoth( $text );
4451 $this->setUser( null ); # Reset
4457 * Pre-save transform helper function
4459 * @param string $text
4464 private function pstPass2( $text, $user ) {
4467 # Note: This is the timestamp saved as hardcoded wikitext to
4468 # the database, we use $wgContLang here in order to give
4469 # everyone the same signature and use the default one rather
4470 # than the one selected in each user's preferences.
4472 $ts = $this->mOptions
->getTimestamp();
4473 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4474 $ts = $timestamp->format( 'YmdHis' );
4475 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4477 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4479 # Variable replacement
4480 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4481 $text = $this->replaceVariables( $text );
4483 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4484 # which may corrupt this parser instance via its wfMessage()->text() call-
4487 $sigText = $this->getUserSig( $user );
4488 $text = strtr( $text, [
4490 '~~~~' => "$sigText $d",
4494 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4495 $tc = '[' . Title
::legalChars() . ']';
4496 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4498 // [[ns:page (context)|]]
4499 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4500 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4501 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4502 // [[ns:page (context), context|]] (using either single or double-width comma)
4503 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4504 // [[|page]] (reverse pipe trick: add context from page title)
4505 $p2 = "/\[\[\\|($tc+)]]/";
4507 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4508 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4509 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4510 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4512 $t = $this->mTitle
->getText();
4514 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4515 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4516 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4517 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4519 # if there's no context, don't bother duplicating the title
4520 $text = preg_replace( $p2, '[[\\1]]', $text );
4527 * Fetch the user's signature text, if any, and normalize to
4528 * validated, ready-to-insert wikitext.
4529 * If you have pre-fetched the nickname or the fancySig option, you can
4530 * specify them here to save a database query.
4531 * Do not reuse this parser instance after calling getUserSig(),
4532 * as it may have changed if it's the $wgParser.
4535 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4536 * @param bool|null $fancySig whether the nicknname is the complete signature
4537 * or null to use default value
4540 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4541 global $wgMaxSigChars;
4543 $username = $user->getName();
4545 # If not given, retrieve from the user object.
4546 if ( $nickname === false ) {
4547 $nickname = $user->getOption( 'nickname' );
4550 if ( is_null( $fancySig ) ) {
4551 $fancySig = $user->getBoolOption( 'fancysig' );
4554 $nickname = $nickname == null ?
$username : $nickname;
4556 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4557 $nickname = $username;
4558 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4559 } elseif ( $fancySig !== false ) {
4560 # Sig. might contain markup; validate this
4561 if ( $this->validateSig( $nickname ) !== false ) {
4562 # Validated; clean up (if needed) and return it
4563 return $this->cleanSig( $nickname, true );
4565 # Failed to validate; fall back to the default
4566 $nickname = $username;
4567 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4571 # Make sure nickname doesnt get a sig in a sig
4572 $nickname = self
::cleanSigInSig( $nickname );
4574 # If we're still here, make it a link to the user page
4575 $userText = wfEscapeWikiText( $username );
4576 $nickText = wfEscapeWikiText( $nickname );
4577 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4579 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4580 ->title( $this->getTitle() )->text();
4584 * Check that the user's signature contains no bad XML
4586 * @param string $text
4587 * @return string|bool An expanded string, or false if invalid.
4589 public function validateSig( $text ) {
4590 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4594 * Clean up signature text
4596 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4597 * 2) Substitute all transclusions
4599 * @param string $text
4600 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4601 * @return string Signature text
4603 public function cleanSig( $text, $parsing = false ) {
4606 $magicScopeVariable = $this->lock();
4607 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4610 # Option to disable this feature
4611 if ( !$this->mOptions
->getCleanSignatures() ) {
4615 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4616 # => Move this logic to braceSubstitution()
4617 $substWord = MagicWord
::get( 'subst' );
4618 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4619 $substText = '{{' . $substWord->getSynonym( 0 );
4621 $text = preg_replace( $substRegex, $substText, $text );
4622 $text = self
::cleanSigInSig( $text );
4623 $dom = $this->preprocessToDom( $text );
4624 $frame = $this->getPreprocessor()->newFrame();
4625 $text = $frame->expand( $dom );
4628 $text = $this->mStripState
->unstripBoth( $text );
4635 * Strip 3, 4 or 5 tildes out of signatures.
4637 * @param string $text
4638 * @return string Signature text with /~{3,5}/ removed
4640 public static function cleanSigInSig( $text ) {
4641 $text = preg_replace( '/~{3,5}/', '', $text );
4646 * Set up some variables which are usually set up in parse()
4647 * so that an external function can call some class members with confidence
4649 * @param Title|null $title
4650 * @param ParserOptions $options
4651 * @param int $outputType
4652 * @param bool $clearState
4654 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4655 $outputType, $clearState = true
4657 $this->startParse( $title, $options, $outputType, $clearState );
4661 * @param Title|null $title
4662 * @param ParserOptions $options
4663 * @param int $outputType
4664 * @param bool $clearState
4666 private function startParse( Title
$title = null, ParserOptions
$options,
4667 $outputType, $clearState = true
4669 $this->setTitle( $title );
4670 $this->mOptions
= $options;
4671 $this->setOutputType( $outputType );
4672 if ( $clearState ) {
4673 $this->clearState();
4678 * Wrapper for preprocess()
4680 * @param string $text The text to preprocess
4681 * @param ParserOptions $options Options
4682 * @param Title|null $title Title object or null to use $wgTitle
4685 public function transformMsg( $text, $options, $title = null ) {
4686 static $executing = false;
4688 # Guard against infinite recursion
4699 $text = $this->preprocess( $text, $title, $options );
4706 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4707 * The callback should have the following form:
4708 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4710 * Transform and return $text. Use $parser for any required context, e.g. use
4711 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4713 * Hooks may return extended information by returning an array, of which the
4714 * first numbered element (index 0) must be the return string, and all other
4715 * entries are extracted into local variables within an internal function
4716 * in the Parser class.
4718 * This interface (introduced r61913) appears to be undocumented, but
4719 * 'markerType' is used by some core tag hooks to override which strip
4720 * array their results are placed in. **Use great caution if attempting
4721 * this interface, as it is not documented and injudicious use could smash
4722 * private variables.**
4724 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4725 * @param callable $callback The callback function (and object) to use for the tag
4726 * @throws MWException
4727 * @return callable|null The old value of the mTagHooks array associated with the hook
4729 public function setHook( $tag, $callback ) {
4730 $tag = strtolower( $tag );
4731 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4732 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4734 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4735 $this->mTagHooks
[$tag] = $callback;
4736 if ( !in_array( $tag, $this->mStripList
) ) {
4737 $this->mStripList
[] = $tag;
4744 * As setHook(), but letting the contents be parsed.
4746 * Transparent tag hooks are like regular XML-style tag hooks, except they
4747 * operate late in the transformation sequence, on HTML instead of wikitext.
4749 * This is probably obsoleted by things dealing with parser frames?
4750 * The only extension currently using it is geoserver.
4753 * @todo better document or deprecate this
4755 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4756 * @param callable $callback The callback function (and object) to use for the tag
4757 * @throws MWException
4758 * @return callable|null The old value of the mTagHooks array associated with the hook
4760 public function setTransparentTagHook( $tag, $callback ) {
4761 $tag = strtolower( $tag );
4762 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4763 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4765 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4766 $this->mTransparentTagHooks
[$tag] = $callback;
4772 * Remove all tag hooks
4774 public function clearTagHooks() {
4775 $this->mTagHooks
= [];
4776 $this->mFunctionTagHooks
= [];
4777 $this->mStripList
= $this->mDefaultStripList
;
4781 * Create a function, e.g. {{sum:1|2|3}}
4782 * The callback function should have the form:
4783 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4785 * Or with Parser::SFH_OBJECT_ARGS:
4786 * function myParserFunction( $parser, $frame, $args ) { ... }
4788 * The callback may either return the text result of the function, or an array with the text
4789 * in element 0, and a number of flags in the other elements. The names of the flags are
4790 * specified in the keys. Valid flags are:
4791 * found The text returned is valid, stop processing the template. This
4793 * nowiki Wiki markup in the return value should be escaped
4794 * isHTML The returned text is HTML, armour it against wikitext transformation
4796 * @param string $id The magic word ID
4797 * @param callable $callback The callback function (and object) to use
4798 * @param int $flags A combination of the following flags:
4799 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4801 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4802 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4803 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4804 * the arguments, and to control the way they are expanded.
4806 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4807 * arguments, for instance:
4808 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4810 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4811 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4812 * working if/when this is changed.
4814 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4817 * Please read the documentation in includes/parser/Preprocessor.php for more information
4818 * about the methods available in PPFrame and PPNode.
4820 * @throws MWException
4821 * @return string|callable The old callback function for this name, if any
4823 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4826 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4827 $this->mFunctionHooks
[$id] = [ $callback, $flags ];
4829 # Add to function cache
4830 $mw = MagicWord
::get( $id );
4832 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4835 $synonyms = $mw->getSynonyms();
4836 $sensitive = intval( $mw->isCaseSensitive() );
4838 foreach ( $synonyms as $syn ) {
4840 if ( !$sensitive ) {
4841 $syn = $wgContLang->lc( $syn );
4844 if ( !( $flags & self
::SFH_NO_HASH
) ) {
4847 # Remove trailing colon
4848 if ( substr( $syn, -1, 1 ) === ':' ) {
4849 $syn = substr( $syn, 0, -1 );
4851 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4857 * Get all registered function hook identifiers
4861 public function getFunctionHooks() {
4862 return array_keys( $this->mFunctionHooks
);
4866 * Create a tag function, e.g. "<test>some stuff</test>".
4867 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4868 * Unlike parser functions, their content is not preprocessed.
4869 * @param string $tag
4870 * @param callable $callback
4872 * @throws MWException
4875 public function setFunctionTagHook( $tag, $callback, $flags ) {
4876 $tag = strtolower( $tag );
4877 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4878 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4880 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4881 $this->mFunctionTagHooks
[$tag] : null;
4882 $this->mFunctionTagHooks
[$tag] = [ $callback, $flags ];
4884 if ( !in_array( $tag, $this->mStripList
) ) {
4885 $this->mStripList
[] = $tag;
4892 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4893 * Placeholders created in Linker::link()
4895 * @param string $text
4896 * @param int $options
4898 public function replaceLinkHolders( &$text, $options = 0 ) {
4899 $this->mLinkHolders
->replace( $text );
4903 * Replace "<!--LINK-->" link placeholders with plain text of links
4904 * (not HTML-formatted).
4906 * @param string $text
4909 public function replaceLinkHoldersText( $text ) {
4910 return $this->mLinkHolders
->replaceText( $text );
4914 * Renders an image gallery from a text with one line per image.
4915 * text labels may be given by using |-style alternative text. E.g.
4916 * Image:one.jpg|The number "1"
4917 * Image:tree.jpg|A tree
4918 * given as text will return the HTML of a gallery with two images,
4919 * labeled 'The number "1"' and
4922 * @param string $text
4923 * @param array $params
4924 * @return string HTML
4926 public function renderImageGallery( $text, $params ) {
4929 if ( isset( $params['mode'] ) ) {
4930 $mode = $params['mode'];
4934 $ig = ImageGalleryBase
::factory( $mode );
4935 } catch ( Exception
$e ) {
4936 // If invalid type set, fallback to default.
4937 $ig = ImageGalleryBase
::factory( false );
4940 $ig->setContextTitle( $this->mTitle
);
4941 $ig->setShowBytes( false );
4942 $ig->setShowFilename( false );
4943 $ig->setParser( $this );
4944 $ig->setHideBadImages();
4945 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4947 if ( isset( $params['showfilename'] ) ) {
4948 $ig->setShowFilename( true );
4950 $ig->setShowFilename( false );
4952 if ( isset( $params['caption'] ) ) {
4953 $caption = $params['caption'];
4954 $caption = htmlspecialchars( $caption );
4955 $caption = $this->replaceInternalLinks( $caption );
4956 $ig->setCaptionHtml( $caption );
4958 if ( isset( $params['perrow'] ) ) {
4959 $ig->setPerRow( $params['perrow'] );
4961 if ( isset( $params['widths'] ) ) {
4962 $ig->setWidths( $params['widths'] );
4964 if ( isset( $params['heights'] ) ) {
4965 $ig->setHeights( $params['heights'] );
4967 $ig->setAdditionalOptions( $params );
4969 Hooks
::run( 'BeforeParserrenderImageGallery', [ &$this, &$ig ] );
4971 $lines = StringUtils
::explode( "\n", $text );
4972 foreach ( $lines as $line ) {
4973 # match lines like these:
4974 # Image:someimage.jpg|This is some image
4976 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4978 if ( count( $matches ) == 0 ) {
4982 if ( strpos( $matches[0], '%' ) !== false ) {
4983 $matches[1] = rawurldecode( $matches[1] );
4985 $title = Title
::newFromText( $matches[1], NS_FILE
);
4986 if ( is_null( $title ) ) {
4987 # Bogus title. Ignore these so we don't bomb out later.
4991 # We need to get what handler the file uses, to figure out parameters.
4992 # Note, a hook can overide the file name, and chose an entirely different
4993 # file (which potentially could be of a different type and have different handler).
4996 Hooks
::run( 'BeforeParserFetchFileAndTitle',
4997 [ $this, $title, &$options, &$descQuery ] );
4998 # Don't register it now, as TraditionalImageGallery does that later.
4999 $file = $this->fetchFileNoRegister( $title, $options );
5000 $handler = $file ?
$file->getHandler() : false;
5003 'img_alt' => 'gallery-internal-alt',
5004 'img_link' => 'gallery-internal-link',
5007 $paramMap = $paramMap +
$handler->getParamMap();
5008 // We don't want people to specify per-image widths.
5009 // Additionally the width parameter would need special casing anyhow.
5010 unset( $paramMap['img_width'] );
5013 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5018 $handlerOptions = [];
5019 if ( isset( $matches[3] ) ) {
5020 // look for an |alt= definition while trying not to break existing
5021 // captions with multiple pipes (|) in it, until a more sensible grammar
5022 // is defined for images in galleries
5024 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5025 // splitting on '|' is a bit odd, and different from makeImage.
5026 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5027 // Protect LanguageConverter markup
5028 $parameterMatches = StringUtils
::delimiterExplode(
5029 '-{', '}-', '|', $matches[3], true /* nested */
5032 foreach ( $parameterMatches as $parameterMatch ) {
5033 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5035 $paramName = $paramMap[$magicName];
5037 switch ( $paramName ) {
5038 case 'gallery-internal-alt':
5039 $alt = $this->stripAltText( $match, false );
5041 case 'gallery-internal-link':
5042 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5043 $chars = self
::EXT_LINK_URL_CLASS
;
5044 $addr = self
::EXT_LINK_ADDR
;
5045 $prots = $this->mUrlProtocols
;
5046 // check to see if link matches an absolute url, if not then it must be a wiki link.
5047 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5048 // Result of LanguageConverter::markNoConversion
5049 // invoked on an external link.
5050 $linkValue = substr( $linkValue, 4, -2 );
5052 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5055 $localLinkTitle = Title
::newFromText( $linkValue );
5056 if ( $localLinkTitle !== null ) {
5057 $link = $localLinkTitle->getLinkURL();
5062 // Must be a handler specific parameter.
5063 if ( $handler->validateParam( $paramName, $match ) ) {
5064 $handlerOptions[$paramName] = $match;
5066 // Guess not, consider it as caption.
5067 wfDebug( "$parameterMatch failed parameter validation\n" );
5068 $label = '|' . $parameterMatch;
5074 $label = '|' . $parameterMatch;
5078 $label = substr( $label, 1 );
5081 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5083 $html = $ig->toHTML();
5084 Hooks
::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5089 * @param MediaHandler $handler
5092 public function getImageParams( $handler ) {
5094 $handlerClass = get_class( $handler );
5098 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5099 # Initialise static lists
5100 static $internalParamNames = [
5101 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5102 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5103 'bottom', 'text-bottom' ],
5104 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5105 'upright', 'border', 'link', 'alt', 'class' ],
5107 static $internalParamMap;
5108 if ( !$internalParamMap ) {
5109 $internalParamMap = [];
5110 foreach ( $internalParamNames as $type => $names ) {
5111 foreach ( $names as $name ) {
5112 $magicName = str_replace( '-', '_', "img_$name" );
5113 $internalParamMap[$magicName] = [ $type, $name ];
5118 # Add handler params
5119 $paramMap = $internalParamMap;
5121 $handlerParamMap = $handler->getParamMap();
5122 foreach ( $handlerParamMap as $magic => $paramName ) {
5123 $paramMap[$magic] = [ 'handler', $paramName ];
5126 $this->mImageParams
[$handlerClass] = $paramMap;
5127 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5129 return [ $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] ];
5133 * Parse image options text and use it to make an image
5135 * @param Title $title
5136 * @param string $options
5137 * @param LinkHolderArray|bool $holders
5138 * @return string HTML
5140 public function makeImage( $title, $options, $holders = false ) {
5141 # Check if the options text is of the form "options|alt text"
5143 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5144 # * left no resizing, just left align. label is used for alt= only
5145 # * right same, but right aligned
5146 # * none same, but not aligned
5147 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5148 # * center center the image
5149 # * frame Keep original image size, no magnify-button.
5150 # * framed Same as "frame"
5151 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5152 # * upright reduce width for upright images, rounded to full __0 px
5153 # * border draw a 1px border around the image
5154 # * alt Text for HTML alt attribute (defaults to empty)
5155 # * class Set a class for img node
5156 # * link Set the target of the image link. Can be external, interwiki, or local
5157 # vertical-align values (no % or length right now):
5167 # Protect LanguageConverter markup when splitting into parts
5168 $parts = StringUtils
::delimiterExplode(
5169 '-{', '}-', '|', $options, true /* allow nesting */
5172 # Give extensions a chance to select the file revision for us
5175 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5176 [ $this, $title, &$options, &$descQuery ] );
5177 # Fetch and register the file (file title may be different via hooks)
5178 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5181 $handler = $file ?
$file->getHandler() : false;
5183 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5186 $this->addTrackingCategory( 'broken-file-category' );
5189 # Process the input parameters
5191 $params = [ 'frame' => [], 'handler' => [],
5192 'horizAlign' => [], 'vertAlign' => [] ];
5193 $seenformat = false;
5194 foreach ( $parts as $part ) {
5195 $part = trim( $part );
5196 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5198 if ( isset( $paramMap[$magicName] ) ) {
5199 list( $type, $paramName ) = $paramMap[$magicName];
5201 # Special case; width and height come in one variable together
5202 if ( $type === 'handler' && $paramName === 'width' ) {
5203 $parsedWidthParam = $this->parseWidthParam( $value );
5204 if ( isset( $parsedWidthParam['width'] ) ) {
5205 $width = $parsedWidthParam['width'];
5206 if ( $handler->validateParam( 'width', $width ) ) {
5207 $params[$type]['width'] = $width;
5211 if ( isset( $parsedWidthParam['height'] ) ) {
5212 $height = $parsedWidthParam['height'];
5213 if ( $handler->validateParam( 'height', $height ) ) {
5214 $params[$type]['height'] = $height;
5218 # else no validation -- T15436
5220 if ( $type === 'handler' ) {
5221 # Validate handler parameter
5222 $validated = $handler->validateParam( $paramName, $value );
5224 # Validate internal parameters
5225 switch ( $paramName ) {
5229 # @todo FIXME: Possibly check validity here for
5230 # manualthumb? downstream behavior seems odd with
5231 # missing manual thumbs.
5233 $value = $this->stripAltText( $value, $holders );
5236 $chars = self
::EXT_LINK_URL_CLASS
;
5237 $addr = self
::EXT_LINK_ADDR
;
5238 $prots = $this->mUrlProtocols
;
5239 if ( $value === '' ) {
5240 $paramName = 'no-link';
5243 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5244 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5245 $paramName = 'link-url';
5246 $this->mOutput
->addExternalLink( $value );
5247 if ( $this->mOptions
->getExternalLinkTarget() ) {
5248 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5253 $linkTitle = Title
::newFromText( $value );
5255 $paramName = 'link-title';
5256 $value = $linkTitle;
5257 $this->mOutput
->addLink( $linkTitle );
5265 // use first appearing option, discard others.
5266 $validated = !$seenformat;
5270 # Most other things appear to be empty or numeric...
5271 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5276 $params[$type][$paramName] = $value;
5280 if ( !$validated ) {
5285 # Process alignment parameters
5286 if ( $params['horizAlign'] ) {
5287 $params['frame']['align'] = key( $params['horizAlign'] );
5289 if ( $params['vertAlign'] ) {
5290 $params['frame']['valign'] = key( $params['vertAlign'] );
5293 $params['frame']['caption'] = $caption;
5295 # Will the image be presented in a frame, with the caption below?
5296 $imageIsFramed = isset( $params['frame']['frame'] )
5297 ||
isset( $params['frame']['framed'] )
5298 ||
isset( $params['frame']['thumbnail'] )
5299 ||
isset( $params['frame']['manualthumb'] );
5301 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5302 # came to also set the caption, ordinary text after the image -- which
5303 # makes no sense, because that just repeats the text multiple times in
5304 # screen readers. It *also* came to set the title attribute.
5305 # Now that we have an alt attribute, we should not set the alt text to
5306 # equal the caption: that's worse than useless, it just repeats the
5307 # text. This is the framed/thumbnail case. If there's no caption, we
5308 # use the unnamed parameter for alt text as well, just for the time be-
5309 # ing, if the unnamed param is set and the alt param is not.
5310 # For the future, we need to figure out if we want to tweak this more,
5311 # e.g., introducing a title= parameter for the title; ignoring the un-
5312 # named parameter entirely for images without a caption; adding an ex-
5313 # plicit caption= parameter and preserving the old magic unnamed para-
5315 if ( $imageIsFramed ) { # Framed image
5316 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5317 # No caption or alt text, add the filename as the alt text so
5318 # that screen readers at least get some description of the image
5319 $params['frame']['alt'] = $title->getText();
5321 # Do not set $params['frame']['title'] because tooltips don't make sense
5323 } else { # Inline image
5324 if ( !isset( $params['frame']['alt'] ) ) {
5325 # No alt text, use the "caption" for the alt text
5326 if ( $caption !== '' ) {
5327 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5329 # No caption, fall back to using the filename for the
5331 $params['frame']['alt'] = $title->getText();
5334 # Use the "caption" for the tooltip text
5335 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5338 Hooks
::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5340 # Linker does the rest
5341 $time = isset( $options['time'] ) ?
$options['time'] : false;
5342 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5343 $time, $descQuery, $this->mOptions
->getThumbSize() );
5345 # Give the handler a chance to modify the parser object
5347 $handler->parserTransformHook( $this, $file );
5354 * @param string $caption
5355 * @param LinkHolderArray|bool $holders
5356 * @return mixed|string
5358 protected function stripAltText( $caption, $holders ) {
5359 # Strip bad stuff out of the title (tooltip). We can't just use
5360 # replaceLinkHoldersText() here, because if this function is called
5361 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5363 $tooltip = $holders->replaceText( $caption );
5365 $tooltip = $this->replaceLinkHoldersText( $caption );
5368 # make sure there are no placeholders in thumbnail attributes
5369 # that are later expanded to html- so expand them now and
5371 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5372 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5378 * Set a flag in the output object indicating that the content is dynamic and
5379 * shouldn't be cached.
5380 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5382 public function disableCache() {
5383 wfDebug( "Parser output marked as uncacheable.\n" );
5384 if ( !$this->mOutput
) {
5385 throw new MWException( __METHOD__
.
5386 " can only be called when actually parsing something" );
5388 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5392 * Callback from the Sanitizer for expanding items found in HTML attribute
5393 * values, so they can be safely tested and escaped.
5395 * @param string $text
5396 * @param bool|PPFrame $frame
5399 public function attributeStripCallback( &$text, $frame = false ) {
5400 $text = $this->replaceVariables( $text, $frame );
5401 $text = $this->mStripState
->unstripBoth( $text );
5410 public function getTags() {
5412 array_keys( $this->mTransparentTagHooks
),
5413 array_keys( $this->mTagHooks
),
5414 array_keys( $this->mFunctionTagHooks
)
5419 * Replace transparent tags in $text with the values given by the callbacks.
5421 * Transparent tag hooks are like regular XML-style tag hooks, except they
5422 * operate late in the transformation sequence, on HTML instead of wikitext.
5424 * @param string $text
5428 public function replaceTransparentTags( $text ) {
5430 $elements = array_keys( $this->mTransparentTagHooks
);
5431 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5434 foreach ( $matches as $marker => $data ) {
5435 list( $element, $content, $params, $tag ) = $data;
5436 $tagName = strtolower( $element );
5437 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5438 $output = call_user_func_array(
5439 $this->mTransparentTagHooks
[$tagName],
5440 [ $content, $params, $this ]
5445 $replacements[$marker] = $output;
5447 return strtr( $text, $replacements );
5451 * Break wikitext input into sections, and either pull or replace
5452 * some particular section's text.
5454 * External callers should use the getSection and replaceSection methods.
5456 * @param string $text Page wikitext
5457 * @param string|int $sectionId A section identifier string of the form:
5458 * "<flag1> - <flag2> - ... - <section number>"
5460 * Currently the only recognised flag is "T", which means the target section number
5461 * was derived during a template inclusion parse, in other words this is a template
5462 * section edit link. If no flags are given, it was an ordinary section edit link.
5463 * This flag is required to avoid a section numbering mismatch when a section is
5464 * enclosed by "<includeonly>" (T8563).
5466 * The section number 0 pulls the text before the first heading; other numbers will
5467 * pull the given section along with its lower-level subsections. If the section is
5468 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5470 * Section 0 is always considered to exist, even if it only contains the empty
5471 * string. If $text is the empty string and section 0 is replaced, $newText is
5474 * @param string $mode One of "get" or "replace"
5475 * @param string $newText Replacement text for section data.
5476 * @return string For "get", the extracted section text.
5477 * for "replace", the whole page with the section replaced.
5479 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5480 global $wgTitle; # not generally used but removes an ugly failure mode
5482 $magicScopeVariable = $this->lock();
5483 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5485 $frame = $this->getPreprocessor()->newFrame();
5487 # Process section extraction flags
5489 $sectionParts = explode( '-', $sectionId );
5490 $sectionIndex = array_pop( $sectionParts );
5491 foreach ( $sectionParts as $part ) {
5492 if ( $part === 'T' ) {
5493 $flags |
= self
::PTD_FOR_INCLUSION
;
5497 # Check for empty input
5498 if ( strval( $text ) === '' ) {
5499 # Only sections 0 and T-0 exist in an empty document
5500 if ( $sectionIndex == 0 ) {
5501 if ( $mode === 'get' ) {
5507 if ( $mode === 'get' ) {
5515 # Preprocess the text
5516 $root = $this->preprocessToDom( $text, $flags );
5518 # <h> nodes indicate section breaks
5519 # They can only occur at the top level, so we can find them by iterating the root's children
5520 $node = $root->getFirstChild();
5522 # Find the target section
5523 if ( $sectionIndex == 0 ) {
5524 # Section zero doesn't nest, level=big
5525 $targetLevel = 1000;
5528 if ( $node->getName() === 'h' ) {
5529 $bits = $node->splitHeading();
5530 if ( $bits['i'] == $sectionIndex ) {
5531 $targetLevel = $bits['level'];
5535 if ( $mode === 'replace' ) {
5536 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5538 $node = $node->getNextSibling();
5544 if ( $mode === 'get' ) {
5551 # Find the end of the section, including nested sections
5553 if ( $node->getName() === 'h' ) {
5554 $bits = $node->splitHeading();
5555 $curLevel = $bits['level'];
5556 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5560 if ( $mode === 'get' ) {
5561 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5563 $node = $node->getNextSibling();
5566 # Write out the remainder (in replace mode only)
5567 if ( $mode === 'replace' ) {
5568 # Output the replacement text
5569 # Add two newlines on -- trailing whitespace in $newText is conventionally
5570 # stripped by the editor, so we need both newlines to restore the paragraph gap
5571 # Only add trailing whitespace if there is newText
5572 if ( $newText != "" ) {
5573 $outText .= $newText . "\n\n";
5577 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5578 $node = $node->getNextSibling();
5582 if ( is_string( $outText ) ) {
5583 # Re-insert stripped tags
5584 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5591 * This function returns the text of a section, specified by a number ($section).
5592 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5593 * the first section before any such heading (section 0).
5595 * If a section contains subsections, these are also returned.
5597 * @param string $text Text to look in
5598 * @param string|int $sectionId Section identifier as a number or string
5599 * (e.g. 0, 1 or 'T-1').
5600 * @param string $defaultText Default to return if section is not found
5602 * @return string Text of the requested section
5604 public function getSection( $text, $sectionId, $defaultText = '' ) {
5605 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5609 * This function returns $oldtext after the content of the section
5610 * specified by $section has been replaced with $text. If the target
5611 * section does not exist, $oldtext is returned unchanged.
5613 * @param string $oldText Former text of the article
5614 * @param string|int $sectionId Section identifier as a number or string
5615 * (e.g. 0, 1 or 'T-1').
5616 * @param string $newText Replacing text
5618 * @return string Modified text
5620 public function replaceSection( $oldText, $sectionId, $newText ) {
5621 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5625 * Get the ID of the revision we are parsing
5629 public function getRevisionId() {
5630 return $this->mRevisionId
;
5634 * Get the revision object for $this->mRevisionId
5636 * @return Revision|null Either a Revision object or null
5637 * @since 1.23 (public since 1.23)
5639 public function getRevisionObject() {
5640 if ( !is_null( $this->mRevisionObject
) ) {
5641 return $this->mRevisionObject
;
5643 if ( is_null( $this->mRevisionId
) ) {
5647 $rev = call_user_func(
5648 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5651 # If the parse is for a new revision, then the callback should have
5652 # already been set to force the object and should match mRevisionId.
5653 # If not, try to fetch by mRevisionId for sanity.
5654 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5655 $rev = Revision
::newFromId( $this->mRevisionId
);
5658 $this->mRevisionObject
= $rev;
5660 return $this->mRevisionObject
;
5664 * Get the timestamp associated with the current revision, adjusted for
5665 * the default server-local timestamp
5668 public function getRevisionTimestamp() {
5669 if ( is_null( $this->mRevisionTimestamp
) ) {
5672 $revObject = $this->getRevisionObject();
5673 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5675 # The cryptic '' timezone parameter tells to use the site-default
5676 # timezone offset instead of the user settings.
5677 # Since this value will be saved into the parser cache, served
5678 # to other users, and potentially even used inside links and such,
5679 # it needs to be consistent for all visitors.
5680 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5683 return $this->mRevisionTimestamp
;
5687 * Get the name of the user that edited the last revision
5689 * @return string User name
5691 public function getRevisionUser() {
5692 if ( is_null( $this->mRevisionUser
) ) {
5693 $revObject = $this->getRevisionObject();
5695 # if this template is subst: the revision id will be blank,
5696 # so just use the current user's name
5698 $this->mRevisionUser
= $revObject->getUserText();
5699 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5700 $this->mRevisionUser
= $this->getUser()->getName();
5703 return $this->mRevisionUser
;
5707 * Get the size of the revision
5709 * @return int|null Revision size
5711 public function getRevisionSize() {
5712 if ( is_null( $this->mRevisionSize
) ) {
5713 $revObject = $this->getRevisionObject();
5715 # if this variable is subst: the revision id will be blank,
5716 # so just use the parser input size, because the own substituation
5717 # will change the size.
5719 $this->mRevisionSize
= $revObject->getSize();
5721 $this->mRevisionSize
= $this->mInputSize
;
5724 return $this->mRevisionSize
;
5728 * Mutator for $mDefaultSort
5730 * @param string $sort New value
5732 public function setDefaultSort( $sort ) {
5733 $this->mDefaultSort
= $sort;
5734 $this->mOutput
->setProperty( 'defaultsort', $sort );
5738 * Accessor for $mDefaultSort
5739 * Will use the empty string if none is set.
5741 * This value is treated as a prefix, so the
5742 * empty string is equivalent to sorting by
5747 public function getDefaultSort() {
5748 if ( $this->mDefaultSort
!== false ) {
5749 return $this->mDefaultSort
;
5756 * Accessor for $mDefaultSort
5757 * Unlike getDefaultSort(), will return false if none is set
5759 * @return string|bool
5761 public function getCustomDefaultSort() {
5762 return $this->mDefaultSort
;
5766 * Try to guess the section anchor name based on a wikitext fragment
5767 * presumably extracted from a heading, for example "Header" from
5770 * @param string $text
5774 public function guessSectionNameFromWikiText( $text ) {
5775 # Strip out wikitext links(they break the anchor)
5776 $text = $this->stripSectionName( $text );
5777 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5778 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5782 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5783 * instead. For use in redirects, since IE6 interprets Redirect: headers
5784 * as something other than UTF-8 (apparently?), resulting in breakage.
5786 * @param string $text The section name
5787 * @return string An anchor
5789 public function guessLegacySectionNameFromWikiText( $text ) {
5790 # Strip out wikitext links(they break the anchor)
5791 $text = $this->stripSectionName( $text );
5792 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5793 return '#' . Sanitizer
::escapeId( $text, [ 'noninitial', 'legacy' ] );
5797 * Strips a text string of wikitext for use in a section anchor
5799 * Accepts a text string and then removes all wikitext from the
5800 * string and leaves only the resultant text (i.e. the result of
5801 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5802 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5803 * to create valid section anchors by mimicing the output of the
5804 * parser when headings are parsed.
5806 * @param string $text Text string to be stripped of wikitext
5807 * for use in a Section anchor
5808 * @return string Filtered text string
5810 public function stripSectionName( $text ) {
5811 # Strip internal link markup
5812 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5813 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5815 # Strip external link markup
5816 # @todo FIXME: Not tolerant to blank link text
5817 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5818 # on how many empty links there are on the page - need to figure that out.
5819 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5821 # Parse wikitext quotes (italics & bold)
5822 $text = $this->doQuotes( $text );
5825 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5830 * strip/replaceVariables/unstrip for preprocessor regression testing
5832 * @param string $text
5833 * @param Title $title
5834 * @param ParserOptions $options
5835 * @param int $outputType
5839 public function testSrvus( $text, Title
$title, ParserOptions
$options,
5840 $outputType = self
::OT_HTML
5842 $magicScopeVariable = $this->lock();
5843 $this->startParse( $title, $options, $outputType, true );
5845 $text = $this->replaceVariables( $text );
5846 $text = $this->mStripState
->unstripBoth( $text );
5847 $text = Sanitizer
::removeHTMLtags( $text );
5852 * @param string $text
5853 * @param Title $title
5854 * @param ParserOptions $options
5857 public function testPst( $text, Title
$title, ParserOptions
$options ) {
5858 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5862 * @param string $text
5863 * @param Title $title
5864 * @param ParserOptions $options
5867 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5868 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5872 * Call a callback function on all regions of the given text that are not
5873 * inside strip markers, and replace those regions with the return value
5874 * of the callback. For example, with input:
5878 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5879 * two strings will be replaced with the value returned by the callback in
5883 * @param callable $callback
5887 public function markerSkipCallback( $s, $callback ) {
5890 while ( $i < strlen( $s ) ) {
5891 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
5892 if ( $markerStart === false ) {
5893 $out .= call_user_func( $callback, substr( $s, $i ) );
5896 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5897 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5898 if ( $markerEnd === false ) {
5899 $out .= substr( $s, $markerStart );
5902 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5903 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5912 * Remove any strip markers found in the given text.
5914 * @param string $text Input string
5917 public function killMarkers( $text ) {
5918 return $this->mStripState
->killMarkers( $text );
5922 * Save the parser state required to convert the given half-parsed text to
5923 * HTML. "Half-parsed" in this context means the output of
5924 * recursiveTagParse() or internalParse(). This output has strip markers
5925 * from replaceVariables (extensionSubstitution() etc.), and link
5926 * placeholders from replaceLinkHolders().
5928 * Returns an array which can be serialized and stored persistently. This
5929 * array can later be loaded into another parser instance with
5930 * unserializeHalfParsedText(). The text can then be safely incorporated into
5931 * the return value of a parser hook.
5933 * @param string $text
5937 public function serializeHalfParsedText( $text ) {
5940 'version' => self
::HALF_PARSED_VERSION
,
5941 'stripState' => $this->mStripState
->getSubState( $text ),
5942 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5948 * Load the parser state given in the $data array, which is assumed to
5949 * have been generated by serializeHalfParsedText(). The text contents is
5950 * extracted from the array, and its markers are transformed into markers
5951 * appropriate for the current Parser instance. This transformed text is
5952 * returned, and can be safely included in the return value of a parser
5955 * If the $data array has been stored persistently, the caller should first
5956 * check whether it is still valid, by calling isValidHalfParsedText().
5958 * @param array $data Serialized data
5959 * @throws MWException
5962 public function unserializeHalfParsedText( $data ) {
5963 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5964 throw new MWException( __METHOD__
. ': invalid version' );
5967 # First, extract the strip state.
5968 $texts = [ $data['text'] ];
5969 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5971 # Now renumber links
5972 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5974 # Should be good to go.
5979 * Returns true if the given array, presumed to be generated by
5980 * serializeHalfParsedText(), is compatible with the current version of the
5983 * @param array $data
5987 public function isValidHalfParsedText( $data ) {
5988 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5992 * Parsed a width param of imagelink like 300px or 200x300px
5994 * @param string $value
5999 public function parseWidthParam( $value ) {
6000 $parsedWidthParam = [];
6001 if ( $value === '' ) {
6002 return $parsedWidthParam;
6005 # (T15500) In both cases (width/height and width only),
6006 # permit trailing "px" for backward compatibility.
6007 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6008 $width = intval( $m[1] );
6009 $height = intval( $m[2] );
6010 $parsedWidthParam['width'] = $width;
6011 $parsedWidthParam['height'] = $height;
6012 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6013 $width = intval( $value );
6014 $parsedWidthParam['width'] = $width;
6016 return $parsedWidthParam;
6020 * Lock the current instance of the parser.
6022 * This is meant to stop someone from calling the parser
6023 * recursively and messing up all the strip state.
6025 * @throws MWException If parser is in a parse
6026 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6028 protected function lock() {
6029 if ( $this->mInParse
) {
6030 throw new MWException( "Parser state cleared while parsing. "
6031 . "Did you call Parser::parse recursively?" );
6033 $this->mInParse
= true;
6035 $recursiveCheck = new ScopedCallback( function() {
6036 $this->mInParse
= false;
6039 return $recursiveCheck;
6043 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6045 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6046 * or if there is more than one <p/> tag in the input HTML.
6048 * @param string $html
6052 public static function stripOuterParagraph( $html ) {
6054 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6055 if ( strpos( $m[1], '</p>' ) === false ) {
6064 * Return this parser if it is not doing anything, otherwise
6065 * get a fresh parser. You can use this method by doing
6066 * $myParser = $wgParser->getFreshParser(), or more simply
6067 * $wgParser->getFreshParser()->parse( ... );
6068 * if you're unsure if $wgParser is safe to use.
6071 * @return Parser A parser object that is not parsing anything
6073 public function getFreshParser() {
6074 global $wgParserConf;
6075 if ( $this->mInParse
) {
6076 return new $wgParserConf['class']( $wgParserConf );
6083 * Set's up the PHP implementation of OOUI for use in this request
6084 * and instructs OutputPage to enable OOUI for itself.
6088 public function enableOOUI() {
6089 OutputPage
::setupOOUI();
6090 $this->mOutput
->setEnableOOUI( true );