d8722bac5b7b7b8e52708fb1a14898037161093e
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * PHP parser that converts wiki markup to HTML.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Parser
22 */
23 use MediaWiki\Linker\LinkRenderer;
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\ScopedCallback;
26
27 /**
28 * @defgroup Parser Parser
29 */
30
31 /**
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).
36 *
37 * There are seven main entry points into the Parser class:
38 *
39 * - Parser::parse()
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
53 *
54 * Globals used:
55 * object: $wgContLang
56 *
57 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
58 *
59 * @par Settings:
60 * $wgNamespacesWithSubpages
61 *
62 * @par Settings only within ParserOptions:
63 * $wgAllowExternalImages
64 * $wgAllowSpecialInclusion
65 * $wgInterwikiMagic
66 * $wgMaxArticleSize
67 *
68 * @ingroup Parser
69 */
70 class Parser {
71 /**
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.
75 */
76 const VERSION = '1.6.4';
77
78 /**
79 * Update this version number when the output of serialiseHalfParsedText()
80 * changes in an incompatible way
81 */
82 const HALF_PARSED_VERSION = 2;
83
84 # Flags for Parser::setFunctionHook
85 const SFH_NO_HASH = 1;
86 const SFH_OBJECT_ARGS = 2;
87
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
92 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
93 # uses to replace invalid HTML characters.
94 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
95 # Simplified expression to match an IPv4 or IPv6 address, or
96 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
97 const EXT_LINK_ADDR = '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
98 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
99 // @codingStandardsIgnoreStart Generic.Files.LineLength
100 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
101 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
102 // @codingStandardsIgnoreEnd
103
104 # Regular expression for a non-newline space
105 const SPACE_NOT_NL = '(?:\t|&nbsp;|&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
106
107 # Flags for preprocessToDom
108 const PTD_FOR_INCLUSION = 1;
109
110 # Allowed values for $this->mOutputType
111 # Parameter to startExternalParse().
112 const OT_HTML = 1; # like parse()
113 const OT_WIKI = 2; # like preSaveTransform()
114 const OT_PREPROCESS = 3; # like preprocess()
115 const OT_MSG = 3;
116 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
117
118 /**
119 * @var string Prefix and suffix for temporary replacement strings
120 * for the multipass parser.
121 *
122 * \x7f should never appear in input as it's disallowed in XML.
123 * Using it at the front also gives us a little extra robustness
124 * since it shouldn't match when butted up against identifier-like
125 * string constructs.
126 *
127 * Must not consist of all title characters, or else it will change
128 * the behavior of <nowiki> in a link.
129 *
130 * Must have a character that needs escaping in attributes, otherwise
131 * someone could put a strip marker in an attribute, to get around
132 * escaping quote marks, and break out of the attribute. Thus we add
133 * `'".
134 */
135 const MARKER_SUFFIX = "-QINU`\"'\x7f";
136 const MARKER_PREFIX = "\x7f'\"`UNIQ-";
137
138 # Markers used for wrapping the table of contents
139 const TOC_START = '<mw:toc>';
140 const TOC_END = '</mw:toc>';
141
142 # Persistent:
143 public $mTagHooks = [];
144 public $mTransparentTagHooks = [];
145 public $mFunctionHooks = [];
146 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
147 public $mFunctionTagHooks = [];
148 public $mStripList = [];
149 public $mDefaultStripList = [];
150 public $mVarCache = [];
151 public $mImageParams = [];
152 public $mImageParamsMagicArray = [];
153 public $mMarkerIndex = 0;
154 public $mFirstCall = true;
155
156 # Initialised by initialiseVariables()
157
158 /**
159 * @var MagicWordArray
160 */
161 public $mVariables;
162
163 /**
164 * @var MagicWordArray
165 */
166 public $mSubstWords;
167 # Initialised in constructor
168 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
169
170 # Initialized in getPreprocessor()
171 /** @var Preprocessor */
172 public $mPreprocessor;
173
174 # Cleared with clearState():
175 /**
176 * @var ParserOutput
177 */
178 public $mOutput;
179 public $mAutonumber;
180
181 /**
182 * @var StripState
183 */
184 public $mStripState;
185
186 public $mIncludeCount;
187 /**
188 * @var LinkHolderArray
189 */
190 public $mLinkHolders;
191
192 public $mLinkID;
193 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
194 public $mDefaultSort;
195 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
196 public $mExpensiveFunctionCount; # number of expensive parser function calls
197 public $mShowToc, $mForceTocPosition;
198
199 /**
200 * @var User
201 */
202 public $mUser; # User object; only used when doing pre-save transform
203
204 # Temporary
205 # These are variables reset at least once per parse regardless of $clearState
206
207 /**
208 * @var ParserOptions
209 */
210 public $mOptions;
211
212 /**
213 * @var Title
214 */
215 public $mTitle; # Title context, used for self-link rendering and similar things
216 public $mOutputType; # Output type, one of the OT_xxx constants
217 public $ot; # Shortcut alias, see setOutputType()
218 public $mRevisionObject; # The revision object of the specified revision ID
219 public $mRevisionId; # ID to display in {{REVISIONID}} tags
220 public $mRevisionTimestamp; # The timestamp of the specified revision ID
221 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
222 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
223 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
224 public $mInputSize = false; # For {{PAGESIZE}} on current page.
225
226 /**
227 * @var string Deprecated accessor for the strip marker prefix.
228 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
229 */
230 public $mUniqPrefix = Parser::MARKER_PREFIX;
231
232 /**
233 * @var array Array with the language name of each language link (i.e. the
234 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
235 * duplicate language links to the ParserOutput.
236 */
237 public $mLangLinkLanguages;
238
239 /**
240 * @var MapCacheLRU|null
241 * @since 1.24
242 *
243 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
244 */
245 public $currentRevisionCache;
246
247 /**
248 * @var bool|string Recursive call protection.
249 * This variable should be treated as if it were private.
250 */
251 public $mInParse = false;
252
253 /** @var SectionProfiler */
254 protected $mProfiler;
255
256 /**
257 * @var LinkRenderer
258 */
259 protected $mLinkRenderer;
260
261 /**
262 * @param array $conf
263 */
264 public function __construct( $conf = [] ) {
265 $this->mConf = $conf;
266 $this->mUrlProtocols = wfUrlProtocols();
267 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
268 self::EXT_LINK_ADDR .
269 self::EXT_LINK_URL_CLASS . '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
270 if ( isset( $conf['preprocessorClass'] ) ) {
271 $this->mPreprocessorClass = $conf['preprocessorClass'];
272 } elseif ( defined( 'HPHP_VERSION' ) ) {
273 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
274 $this->mPreprocessorClass = 'Preprocessor_Hash';
275 } elseif ( extension_loaded( 'domxml' ) ) {
276 # PECL extension that conflicts with the core DOM extension (T15770)
277 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
278 $this->mPreprocessorClass = 'Preprocessor_Hash';
279 } elseif ( extension_loaded( 'dom' ) ) {
280 $this->mPreprocessorClass = 'Preprocessor_DOM';
281 } else {
282 $this->mPreprocessorClass = 'Preprocessor_Hash';
283 }
284 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
285 }
286
287 /**
288 * Reduce memory usage to reduce the impact of circular references
289 */
290 public function __destruct() {
291 if ( isset( $this->mLinkHolders ) ) {
292 unset( $this->mLinkHolders );
293 }
294 foreach ( $this as $name => $value ) {
295 unset( $this->$name );
296 }
297 }
298
299 /**
300 * Allow extensions to clean up when the parser is cloned
301 */
302 public function __clone() {
303 $this->mInParse = false;
304
305 // T58226: When you create a reference "to" an object field, that
306 // makes the object field itself be a reference too (until the other
307 // reference goes out of scope). When cloning, any field that's a
308 // reference is copied as a reference in the new object. Both of these
309 // are defined PHP5 behaviors, as inconvenient as it is for us when old
310 // hooks from PHP4 days are passing fields by reference.
311 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
312 // Make a non-reference copy of the field, then rebind the field to
313 // reference the new copy.
314 $tmp = $this->$k;
315 $this->$k =& $tmp;
316 unset( $tmp );
317 }
318
319 Hooks::run( 'ParserCloned', [ $this ] );
320 }
321
322 /**
323 * Do various kinds of initialisation on the first call of the parser
324 */
325 public function firstCallInit() {
326 if ( !$this->mFirstCall ) {
327 return;
328 }
329 $this->mFirstCall = false;
330
331 CoreParserFunctions::register( $this );
332 CoreTagHooks::register( $this );
333 $this->initialiseVariables();
334
335 // Avoid PHP 7.1 warning from passing $this by reference
336 $parser = $this;
337 Hooks::run( 'ParserFirstCallInit', [ &$parser ] );
338 }
339
340 /**
341 * Clear Parser state
342 *
343 * @private
344 */
345 public function clearState() {
346 if ( $this->mFirstCall ) {
347 $this->firstCallInit();
348 }
349 $this->mOutput = new ParserOutput;
350 $this->mOptions->registerWatcher( [ $this->mOutput, 'recordOption' ] );
351 $this->mAutonumber = 0;
352 $this->mIncludeCount = [];
353 $this->mLinkHolders = new LinkHolderArray( $this );
354 $this->mLinkID = 0;
355 $this->mRevisionObject = $this->mRevisionTimestamp =
356 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null;
357 $this->mVarCache = [];
358 $this->mUser = null;
359 $this->mLangLinkLanguages = [];
360 $this->currentRevisionCache = null;
361
362 $this->mStripState = new StripState;
363
364 # Clear these on every parse, T6549
365 $this->mTplRedirCache = $this->mTplDomCache = [];
366
367 $this->mShowToc = true;
368 $this->mForceTocPosition = false;
369 $this->mIncludeSizes = [
370 'post-expand' => 0,
371 'arg' => 0,
372 ];
373 $this->mPPNodeCount = 0;
374 $this->mGeneratedPPNodeCount = 0;
375 $this->mHighestExpansionDepth = 0;
376 $this->mDefaultSort = false;
377 $this->mHeadings = [];
378 $this->mDoubleUnderscores = [];
379 $this->mExpensiveFunctionCount = 0;
380
381 # Fix cloning
382 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
383 $this->mPreprocessor = null;
384 }
385
386 $this->mProfiler = new SectionProfiler();
387
388 // Avoid PHP 7.1 warning from passing $this by reference
389 $parser = $this;
390 Hooks::run( 'ParserClearState', [ &$parser ] );
391 }
392
393 /**
394 * Convert wikitext to HTML
395 * Do not call this function recursively.
396 *
397 * @param string $text Text we want to parse
398 * @param Title $title
399 * @param ParserOptions $options
400 * @param bool $linestart
401 * @param bool $clearState
402 * @param int $revid Number to pass in {{REVISIONID}}
403 * @return ParserOutput A ParserOutput
404 */
405 public function parse(
406 $text, Title $title, ParserOptions $options,
407 $linestart = true, $clearState = true, $revid = null
408 ) {
409 /**
410 * First pass--just handle <nowiki> sections, pass the rest off
411 * to internalParse() which does all the real work.
412 */
413
414 global $wgShowHostnames;
415
416 if ( $clearState ) {
417 // We use U+007F DELETE to construct strip markers, so we have to make
418 // sure that this character does not occur in the input text.
419 $text = strtr( $text, "\x7f", "?" );
420 $magicScopeVariable = $this->lock();
421 }
422 // Strip U+0000 NULL (T159174)
423 $text = str_replace( "\000", '', $text );
424
425 $this->startParse( $title, $options, self::OT_HTML, $clearState );
426
427 $this->currentRevisionCache = null;
428 $this->mInputSize = strlen( $text );
429 if ( $this->mOptions->getEnableLimitReport() ) {
430 $this->mOutput->resetParseStartTime();
431 }
432
433 $oldRevisionId = $this->mRevisionId;
434 $oldRevisionObject = $this->mRevisionObject;
435 $oldRevisionTimestamp = $this->mRevisionTimestamp;
436 $oldRevisionUser = $this->mRevisionUser;
437 $oldRevisionSize = $this->mRevisionSize;
438 if ( $revid !== null ) {
439 $this->mRevisionId = $revid;
440 $this->mRevisionObject = null;
441 $this->mRevisionTimestamp = null;
442 $this->mRevisionUser = null;
443 $this->mRevisionSize = null;
444 }
445
446 // Avoid PHP 7.1 warning from passing $this by reference
447 $parser = $this;
448 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
449 # No more strip!
450 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
451 $text = $this->internalParse( $text );
452 Hooks::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState ] );
453
454 $text = $this->internalParseHalfParsed( $text, true, $linestart );
455
456 /**
457 * A converted title will be provided in the output object if title and
458 * content conversion are enabled, the article text does not contain
459 * a conversion-suppressing double-underscore tag, and no
460 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
461 * automatic link conversion.
462 */
463 if ( !( $options->getDisableTitleConversion()
464 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
465 || isset( $this->mDoubleUnderscores['notitleconvert'] )
466 || $this->mOutput->getDisplayTitle() !== false )
467 ) {
468 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
469 if ( $convruletitle ) {
470 $this->mOutput->setTitleText( $convruletitle );
471 } else {
472 $titleText = $this->getConverterLanguage()->convertTitle( $title );
473 $this->mOutput->setTitleText( $titleText );
474 }
475 }
476
477 # Done parsing! Compute runtime adaptive expiry if set
478 $this->mOutput->finalizeAdaptiveCacheExpiry();
479
480 # Warn if too many heavyweight parser functions were used
481 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
482 $this->limitationWarn( 'expensive-parserfunction',
483 $this->mExpensiveFunctionCount,
484 $this->mOptions->getExpensiveParserFunctionLimit()
485 );
486 }
487
488 # Information on include size limits, for the benefit of users who try to skirt them
489 if ( $this->mOptions->getEnableLimitReport() ) {
490 $max = $this->mOptions->getMaxIncludeSize();
491
492 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' );
493 if ( $cpuTime !== null ) {
494 $this->mOutput->setLimitReportData( 'limitreport-cputime',
495 sprintf( "%.3f", $cpuTime )
496 );
497 }
498
499 $wallTime = $this->mOutput->getTimeSinceStart( 'wall' );
500 $this->mOutput->setLimitReportData( 'limitreport-walltime',
501 sprintf( "%.3f", $wallTime )
502 );
503
504 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes',
505 [ $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() ]
506 );
507 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes',
508 [ $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() ]
509 );
510 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize',
511 [ $this->mIncludeSizes['post-expand'], $max ]
512 );
513 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize',
514 [ $this->mIncludeSizes['arg'], $max ]
515 );
516 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth',
517 [ $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() ]
518 );
519 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount',
520 [ $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() ]
521 );
522 Hooks::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput ] );
523
524 $limitReport = "NewPP limit report\n";
525 if ( $wgShowHostnames ) {
526 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
527 }
528 $limitReport .= 'Cached time: ' . $this->mOutput->getCacheTime() . "\n";
529 $limitReport .= 'Cache expiry: ' . $this->mOutput->getCacheExpiry() . "\n";
530 $limitReport .= 'Dynamic content: ' .
531 ( $this->mOutput->hasDynamicContent() ? 'true' : 'false' ) .
532 "\n";
533
534 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
535 if ( Hooks::run( 'ParserLimitReportFormat',
536 [ $key, &$value, &$limitReport, false, false ]
537 ) ) {
538 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
539 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
540 ->inLanguage( 'en' )->useDatabase( false );
541 if ( !$valueMsg->exists() ) {
542 $valueMsg = new RawMessage( '$1' );
543 }
544 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
545 $valueMsg->params( $value );
546 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
547 }
548 }
549 }
550 // Since we're not really outputting HTML, decode the entities and
551 // then re-encode the things that need hiding inside HTML comments.
552 $limitReport = htmlspecialchars_decode( $limitReport );
553 Hooks::run( 'ParserLimitReport', [ $this, &$limitReport ] );
554
555 // Sanitize for comment. Note '‐' in the replacement is U+2010,
556 // which looks much like the problematic '-'.
557 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&amp;' ], $limitReport );
558 $text .= "\n<!-- \n$limitReport-->\n";
559
560 // Add on template profiling data in human/machine readable way
561 $dataByFunc = $this->mProfiler->getFunctionStats();
562 uasort( $dataByFunc, function ( $a, $b ) {
563 return $a['real'] < $b['real']; // descending order
564 } );
565 $profileReport = [];
566 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
567 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
568 $item['%real'], $item['real'], $item['calls'],
569 htmlspecialchars( $item['name'] ) );
570 }
571 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
572 $text .= implode( "\n", $profileReport ) . "\n-->\n";
573
574 $this->mOutput->setLimitReportData( 'limitreport-timingprofile', $profileReport );
575
576 // Add other cache related metadata
577 if ( $wgShowHostnames ) {
578 $this->mOutput->setLimitReportData( 'cachereport-origin', wfHostname() );
579 }
580 $this->mOutput->setLimitReportData( 'cachereport-timestamp',
581 $this->mOutput->getCacheTime() );
582 $this->mOutput->setLimitReportData( 'cachereport-ttl',
583 $this->mOutput->getCacheExpiry() );
584 $this->mOutput->setLimitReportData( 'cachereport-transientcontent',
585 $this->mOutput->hasDynamicContent() );
586
587 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
588 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
589 $this->mTitle->getPrefixedDBkey() );
590 }
591 }
592
593 # Wrap non-interface parser output in a <div> so it can be targeted
594 # with CSS (T37247)
595 $class = $this->mOptions->getWrapOutputClass();
596 if ( $class !== false && !$this->mOptions->getInterfaceMessage() ) {
597 $text = Html::rawElement( 'div', [ 'class' => $class ], $text );
598 }
599
600 $this->mOutput->setText( $text );
601
602 $this->mRevisionId = $oldRevisionId;
603 $this->mRevisionObject = $oldRevisionObject;
604 $this->mRevisionTimestamp = $oldRevisionTimestamp;
605 $this->mRevisionUser = $oldRevisionUser;
606 $this->mRevisionSize = $oldRevisionSize;
607 $this->mInputSize = false;
608 $this->currentRevisionCache = null;
609
610 return $this->mOutput;
611 }
612
613 /**
614 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
615 * can be called from an extension tag hook.
616 *
617 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
618 * instead, which means that lists and links have not been fully parsed yet,
619 * and strip markers are still present.
620 *
621 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
622 *
623 * Use this function if you're a parser tag hook and you want to parse
624 * wikitext before or after applying additional transformations, and you
625 * intend to *return the result as hook output*, which will cause it to go
626 * through the rest of parsing process automatically.
627 *
628 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
629 * $text are not expanded
630 *
631 * @param string $text Text extension wants to have parsed
632 * @param bool|PPFrame $frame The frame to use for expanding any template variables
633 * @return string UNSAFE half-parsed HTML
634 */
635 public function recursiveTagParse( $text, $frame = false ) {
636 // Avoid PHP 7.1 warning from passing $this by reference
637 $parser = $this;
638 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
639 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
640 $text = $this->internalParse( $text, false, $frame );
641 return $text;
642 }
643
644 /**
645 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
646 * point can be called from an extension tag hook.
647 *
648 * The output of this function is fully-parsed HTML that is safe for output.
649 * If you're a parser tag hook, you might want to use recursiveTagParse()
650 * instead.
651 *
652 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
653 * $text are not expanded
654 *
655 * @since 1.25
656 *
657 * @param string $text Text extension wants to have parsed
658 * @param bool|PPFrame $frame The frame to use for expanding any template variables
659 * @return string Fully parsed HTML
660 */
661 public function recursiveTagParseFully( $text, $frame = false ) {
662 $text = $this->recursiveTagParse( $text, $frame );
663 $text = $this->internalParseHalfParsed( $text, false );
664 return $text;
665 }
666
667 /**
668 * Expand templates and variables in the text, producing valid, static wikitext.
669 * Also removes comments.
670 * Do not call this function recursively.
671 * @param string $text
672 * @param Title $title
673 * @param ParserOptions $options
674 * @param int|null $revid
675 * @param bool|PPFrame $frame
676 * @return mixed|string
677 */
678 public function preprocess( $text, Title $title = null,
679 ParserOptions $options, $revid = null, $frame = false
680 ) {
681 $magicScopeVariable = $this->lock();
682 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
683 if ( $revid !== null ) {
684 $this->mRevisionId = $revid;
685 }
686 // Avoid PHP 7.1 warning from passing $this by reference
687 $parser = $this;
688 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
689 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
690 $text = $this->replaceVariables( $text, $frame );
691 $text = $this->mStripState->unstripBoth( $text );
692 return $text;
693 }
694
695 /**
696 * Recursive parser entry point that can be called from an extension tag
697 * hook.
698 *
699 * @param string $text Text to be expanded
700 * @param bool|PPFrame $frame The frame to use for expanding any template variables
701 * @return string
702 * @since 1.19
703 */
704 public function recursivePreprocess( $text, $frame = false ) {
705 $text = $this->replaceVariables( $text, $frame );
706 $text = $this->mStripState->unstripBoth( $text );
707 return $text;
708 }
709
710 /**
711 * Process the wikitext for the "?preload=" feature. (T7210)
712 *
713 * "<noinclude>", "<includeonly>" etc. are parsed as for template
714 * transclusion, comments, templates, arguments, tags hooks and parser
715 * functions are untouched.
716 *
717 * @param string $text
718 * @param Title $title
719 * @param ParserOptions $options
720 * @param array $params
721 * @return string
722 */
723 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = [] ) {
724 $msg = new RawMessage( $text );
725 $text = $msg->params( $params )->plain();
726
727 # Parser (re)initialisation
728 $magicScopeVariable = $this->lock();
729 $this->startParse( $title, $options, self::OT_PLAIN, true );
730
731 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
732 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
733 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
734 $text = $this->mStripState->unstripBoth( $text );
735 return $text;
736 }
737
738 /**
739 * Get a random string
740 *
741 * @return string
742 * @deprecated since 1.26; use wfRandomString() instead.
743 */
744 public static function getRandomString() {
745 wfDeprecated( __METHOD__, '1.26' );
746 return wfRandomString( 16 );
747 }
748
749 /**
750 * Set the current user.
751 * Should only be used when doing pre-save transform.
752 *
753 * @param User|null $user User object or null (to reset)
754 */
755 public function setUser( $user ) {
756 $this->mUser = $user;
757 }
758
759 /**
760 * Accessor for mUniqPrefix.
761 *
762 * @return string
763 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
764 */
765 public function uniqPrefix() {
766 wfDeprecated( __METHOD__, '1.26' );
767 return self::MARKER_PREFIX;
768 }
769
770 /**
771 * Set the context title
772 *
773 * @param Title $t
774 */
775 public function setTitle( $t ) {
776 if ( !$t ) {
777 $t = Title::newFromText( 'NO TITLE' );
778 }
779
780 if ( $t->hasFragment() ) {
781 # Strip the fragment to avoid various odd effects
782 $this->mTitle = $t->createFragmentTarget( '' );
783 } else {
784 $this->mTitle = $t;
785 }
786 }
787
788 /**
789 * Accessor for the Title object
790 *
791 * @return Title
792 */
793 public function getTitle() {
794 return $this->mTitle;
795 }
796
797 /**
798 * Accessor/mutator for the Title object
799 *
800 * @param Title $x Title object or null to just get the current one
801 * @return Title
802 */
803 public function Title( $x = null ) {
804 return wfSetVar( $this->mTitle, $x );
805 }
806
807 /**
808 * Set the output type
809 *
810 * @param int $ot New value
811 */
812 public function setOutputType( $ot ) {
813 $this->mOutputType = $ot;
814 # Shortcut alias
815 $this->ot = [
816 'html' => $ot == self::OT_HTML,
817 'wiki' => $ot == self::OT_WIKI,
818 'pre' => $ot == self::OT_PREPROCESS,
819 'plain' => $ot == self::OT_PLAIN,
820 ];
821 }
822
823 /**
824 * Accessor/mutator for the output type
825 *
826 * @param int|null $x New value or null to just get the current one
827 * @return int
828 */
829 public function OutputType( $x = null ) {
830 return wfSetVar( $this->mOutputType, $x );
831 }
832
833 /**
834 * Get the ParserOutput object
835 *
836 * @return ParserOutput
837 */
838 public function getOutput() {
839 return $this->mOutput;
840 }
841
842 /**
843 * Get the ParserOptions object
844 *
845 * @return ParserOptions
846 */
847 public function getOptions() {
848 return $this->mOptions;
849 }
850
851 /**
852 * Accessor/mutator for the ParserOptions object
853 *
854 * @param ParserOptions $x New value or null to just get the current one
855 * @return ParserOptions Current ParserOptions object
856 */
857 public function Options( $x = null ) {
858 return wfSetVar( $this->mOptions, $x );
859 }
860
861 /**
862 * @return int
863 */
864 public function nextLinkID() {
865 return $this->mLinkID++;
866 }
867
868 /**
869 * @param int $id
870 */
871 public function setLinkID( $id ) {
872 $this->mLinkID = $id;
873 }
874
875 /**
876 * Get a language object for use in parser functions such as {{FORMATNUM:}}
877 * @return Language
878 */
879 public function getFunctionLang() {
880 return $this->getTargetLanguage();
881 }
882
883 /**
884 * Get the target language for the content being parsed. This is usually the
885 * language that the content is in.
886 *
887 * @since 1.19
888 *
889 * @throws MWException
890 * @return Language
891 */
892 public function getTargetLanguage() {
893 $target = $this->mOptions->getTargetLanguage();
894
895 if ( $target !== null ) {
896 return $target;
897 } elseif ( $this->mOptions->getInterfaceMessage() ) {
898 return $this->mOptions->getUserLangObj();
899 } elseif ( is_null( $this->mTitle ) ) {
900 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
901 }
902
903 return $this->mTitle->getPageLanguage();
904 }
905
906 /**
907 * Get the language object for language conversion
908 * @return Language|null
909 */
910 public function getConverterLanguage() {
911 return $this->getTargetLanguage();
912 }
913
914 /**
915 * Get a User object either from $this->mUser, if set, or from the
916 * ParserOptions object otherwise
917 *
918 * @return User
919 */
920 public function getUser() {
921 if ( !is_null( $this->mUser ) ) {
922 return $this->mUser;
923 }
924 return $this->mOptions->getUser();
925 }
926
927 /**
928 * Get a preprocessor object
929 *
930 * @return Preprocessor
931 */
932 public function getPreprocessor() {
933 if ( !isset( $this->mPreprocessor ) ) {
934 $class = $this->mPreprocessorClass;
935 $this->mPreprocessor = new $class( $this );
936 }
937 return $this->mPreprocessor;
938 }
939
940 /**
941 * Get a LinkRenderer instance to make links with
942 *
943 * @since 1.28
944 * @return LinkRenderer
945 */
946 public function getLinkRenderer() {
947 if ( !$this->mLinkRenderer ) {
948 $this->mLinkRenderer = MediaWikiServices::getInstance()
949 ->getLinkRendererFactory()->create();
950 $this->mLinkRenderer->setStubThreshold(
951 $this->getOptions()->getStubThreshold()
952 );
953 }
954
955 return $this->mLinkRenderer;
956 }
957
958 /**
959 * Replaces all occurrences of HTML-style comments and the given tags
960 * in the text with a random marker and returns the next text. The output
961 * parameter $matches will be an associative array filled with data in
962 * the form:
963 *
964 * @code
965 * 'UNIQ-xxxxx' => [
966 * 'element',
967 * 'tag content',
968 * [ 'param' => 'x' ],
969 * '<element param="x">tag content</element>' ]
970 * @endcode
971 *
972 * @param array $elements List of element names. Comments are always extracted.
973 * @param string $text Source text string.
974 * @param array $matches Out parameter, Array: extracted tags
975 * @param string|null $uniq_prefix
976 * @return string Stripped text
977 * @since 1.26 The uniq_prefix argument is deprecated.
978 */
979 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
980 if ( $uniq_prefix !== null ) {
981 wfDeprecated( __METHOD__ . ' called with $prefix argument', '1.26' );
982 }
983 static $n = 1;
984 $stripped = '';
985 $matches = [];
986
987 $taglist = implode( '|', $elements );
988 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
989
990 while ( $text != '' ) {
991 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
992 $stripped .= $p[0];
993 if ( count( $p ) < 5 ) {
994 break;
995 }
996 if ( count( $p ) > 5 ) {
997 # comment
998 $element = $p[4];
999 $attributes = '';
1000 $close = '';
1001 $inside = $p[5];
1002 } else {
1003 # tag
1004 $element = $p[1];
1005 $attributes = $p[2];
1006 $close = $p[3];
1007 $inside = $p[4];
1008 }
1009
1010 $marker = self::MARKER_PREFIX . "-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
1011 $stripped .= $marker;
1012
1013 if ( $close === '/>' ) {
1014 # Empty element tag, <tag />
1015 $content = null;
1016 $text = $inside;
1017 $tail = null;
1018 } else {
1019 if ( $element === '!--' ) {
1020 $end = '/(-->)/';
1021 } else {
1022 $end = "/(<\\/$element\\s*>)/i";
1023 }
1024 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
1025 $content = $q[0];
1026 if ( count( $q ) < 3 ) {
1027 # No end tag -- let it run out to the end of the text.
1028 $tail = '';
1029 $text = '';
1030 } else {
1031 $tail = $q[1];
1032 $text = $q[2];
1033 }
1034 }
1035
1036 $matches[$marker] = [ $element,
1037 $content,
1038 Sanitizer::decodeTagAttributes( $attributes ),
1039 "<$element$attributes$close$content$tail" ];
1040 }
1041 return $stripped;
1042 }
1043
1044 /**
1045 * Get a list of strippable XML-like elements
1046 *
1047 * @return array
1048 */
1049 public function getStripList() {
1050 return $this->mStripList;
1051 }
1052
1053 /**
1054 * Add an item to the strip state
1055 * Returns the unique tag which must be inserted into the stripped text
1056 * The tag will be replaced with the original text in unstrip()
1057 *
1058 * @param string $text
1059 *
1060 * @return string
1061 */
1062 public function insertStripItem( $text ) {
1063 $marker = self::MARKER_PREFIX . "-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
1064 $this->mMarkerIndex++;
1065 $this->mStripState->addGeneral( $marker, $text );
1066 return $marker;
1067 }
1068
1069 /**
1070 * parse the wiki syntax used to render tables
1071 *
1072 * @private
1073 * @param string $text
1074 * @return string
1075 */
1076 public function doTableStuff( $text ) {
1077
1078 $lines = StringUtils::explode( "\n", $text );
1079 $out = '';
1080 $td_history = []; # Is currently a td tag open?
1081 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1082 $tr_history = []; # Is currently a tr tag open?
1083 $tr_attributes = []; # history of tr attributes
1084 $has_opened_tr = []; # Did this table open a <tr> element?
1085 $indent_level = 0; # indent level of the table
1086
1087 foreach ( $lines as $outLine ) {
1088 $line = trim( $outLine );
1089
1090 if ( $line === '' ) { # empty line, go to next line
1091 $out .= $outLine . "\n";
1092 continue;
1093 }
1094
1095 $first_character = $line[0];
1096 $first_two = substr( $line, 0, 2 );
1097 $matches = [];
1098
1099 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1100 # First check if we are starting a new table
1101 $indent_level = strlen( $matches[1] );
1102
1103 $attributes = $this->mStripState->unstripBoth( $matches[2] );
1104 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
1105
1106 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1107 array_push( $td_history, false );
1108 array_push( $last_tag_history, '' );
1109 array_push( $tr_history, false );
1110 array_push( $tr_attributes, '' );
1111 array_push( $has_opened_tr, false );
1112 } elseif ( count( $td_history ) == 0 ) {
1113 # Don't do any of the following
1114 $out .= $outLine . "\n";
1115 continue;
1116 } elseif ( $first_two === '|}' ) {
1117 # We are ending a table
1118 $line = '</table>' . substr( $line, 2 );
1119 $last_tag = array_pop( $last_tag_history );
1120
1121 if ( !array_pop( $has_opened_tr ) ) {
1122 $line = "<tr><td></td></tr>{$line}";
1123 }
1124
1125 if ( array_pop( $tr_history ) ) {
1126 $line = "</tr>{$line}";
1127 }
1128
1129 if ( array_pop( $td_history ) ) {
1130 $line = "</{$last_tag}>{$line}";
1131 }
1132 array_pop( $tr_attributes );
1133 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1134 } elseif ( $first_two === '|-' ) {
1135 # Now we have a table row
1136 $line = preg_replace( '#^\|-+#', '', $line );
1137
1138 # Whats after the tag is now only attributes
1139 $attributes = $this->mStripState->unstripBoth( $line );
1140 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
1141 array_pop( $tr_attributes );
1142 array_push( $tr_attributes, $attributes );
1143
1144 $line = '';
1145 $last_tag = array_pop( $last_tag_history );
1146 array_pop( $has_opened_tr );
1147 array_push( $has_opened_tr, true );
1148
1149 if ( array_pop( $tr_history ) ) {
1150 $line = '</tr>';
1151 }
1152
1153 if ( array_pop( $td_history ) ) {
1154 $line = "</{$last_tag}>{$line}";
1155 }
1156
1157 $outLine = $line;
1158 array_push( $tr_history, false );
1159 array_push( $td_history, false );
1160 array_push( $last_tag_history, '' );
1161 } elseif ( $first_character === '|'
1162 || $first_character === '!'
1163 || $first_two === '|+'
1164 ) {
1165 # This might be cell elements, td, th or captions
1166 if ( $first_two === '|+' ) {
1167 $first_character = '+';
1168 $line = substr( $line, 2 );
1169 } else {
1170 $line = substr( $line, 1 );
1171 }
1172
1173 // Implies both are valid for table headings.
1174 if ( $first_character === '!' ) {
1175 $line = StringUtils::replaceMarkup( '!!', '||', $line );
1176 }
1177
1178 # Split up multiple cells on the same line.
1179 # FIXME : This can result in improper nesting of tags processed
1180 # by earlier parser steps.
1181 $cells = explode( '||', $line );
1182
1183 $outLine = '';
1184
1185 # Loop through each table cell
1186 foreach ( $cells as $cell ) {
1187 $previous = '';
1188 if ( $first_character !== '+' ) {
1189 $tr_after = array_pop( $tr_attributes );
1190 if ( !array_pop( $tr_history ) ) {
1191 $previous = "<tr{$tr_after}>\n";
1192 }
1193 array_push( $tr_history, true );
1194 array_push( $tr_attributes, '' );
1195 array_pop( $has_opened_tr );
1196 array_push( $has_opened_tr, true );
1197 }
1198
1199 $last_tag = array_pop( $last_tag_history );
1200
1201 if ( array_pop( $td_history ) ) {
1202 $previous = "</{$last_tag}>\n{$previous}";
1203 }
1204
1205 if ( $first_character === '|' ) {
1206 $last_tag = 'td';
1207 } elseif ( $first_character === '!' ) {
1208 $last_tag = 'th';
1209 } elseif ( $first_character === '+' ) {
1210 $last_tag = 'caption';
1211 } else {
1212 $last_tag = '';
1213 }
1214
1215 array_push( $last_tag_history, $last_tag );
1216
1217 # A cell could contain both parameters and data
1218 $cell_data = explode( '|', $cell, 2 );
1219
1220 # T2553: Note that a '|' inside an invalid link should not
1221 # be mistaken as delimiting cell parameters
1222 # Bug T153140: Neither should language converter markup.
1223 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1224 $cell = "{$previous}<{$last_tag}>{$cell}";
1225 } elseif ( count( $cell_data ) == 1 ) {
1226 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1227 } else {
1228 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1229 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1230 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1231 }
1232
1233 $outLine .= $cell;
1234 array_push( $td_history, true );
1235 }
1236 }
1237 $out .= $outLine . "\n";
1238 }
1239
1240 # Closing open td, tr && table
1241 while ( count( $td_history ) > 0 ) {
1242 if ( array_pop( $td_history ) ) {
1243 $out .= "</td>\n";
1244 }
1245 if ( array_pop( $tr_history ) ) {
1246 $out .= "</tr>\n";
1247 }
1248 if ( !array_pop( $has_opened_tr ) ) {
1249 $out .= "<tr><td></td></tr>\n";
1250 }
1251
1252 $out .= "</table>\n";
1253 }
1254
1255 # Remove trailing line-ending (b/c)
1256 if ( substr( $out, -1 ) === "\n" ) {
1257 $out = substr( $out, 0, -1 );
1258 }
1259
1260 # special case: don't return empty table
1261 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1262 $out = '';
1263 }
1264
1265 return $out;
1266 }
1267
1268 /**
1269 * Helper function for parse() that transforms wiki markup into half-parsed
1270 * HTML. Only called for $mOutputType == self::OT_HTML.
1271 *
1272 * @private
1273 *
1274 * @param string $text The text to parse
1275 * @param bool $isMain Whether this is being called from the main parse() function
1276 * @param PPFrame|bool $frame A pre-processor frame
1277 *
1278 * @return string
1279 */
1280 public function internalParse( $text, $isMain = true, $frame = false ) {
1281
1282 $origText = $text;
1283
1284 // Avoid PHP 7.1 warning from passing $this by reference
1285 $parser = $this;
1286
1287 # Hook to suspend the parser in this state
1288 if ( !Hooks::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState ] ) ) {
1289 return $text;
1290 }
1291
1292 # if $frame is provided, then use $frame for replacing any variables
1293 if ( $frame ) {
1294 # use frame depth to infer how include/noinclude tags should be handled
1295 # depth=0 means this is the top-level document; otherwise it's an included document
1296 if ( !$frame->depth ) {
1297 $flag = 0;
1298 } else {
1299 $flag = Parser::PTD_FOR_INCLUSION;
1300 }
1301 $dom = $this->preprocessToDom( $text, $flag );
1302 $text = $frame->expand( $dom );
1303 } else {
1304 # if $frame is not provided, then use old-style replaceVariables
1305 $text = $this->replaceVariables( $text );
1306 }
1307
1308 Hooks::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState ] );
1309 $text = Sanitizer::removeHTMLtags(
1310 $text,
1311 [ $this, 'attributeStripCallback' ],
1312 false,
1313 array_keys( $this->mTransparentTagHooks ),
1314 [],
1315 [ $this, 'addTrackingCategory' ]
1316 );
1317 Hooks::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState ] );
1318
1319 # Tables need to come after variable replacement for things to work
1320 # properly; putting them before other transformations should keep
1321 # exciting things like link expansions from showing up in surprising
1322 # places.
1323 $text = $this->doTableStuff( $text );
1324
1325 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1326
1327 $text = $this->doDoubleUnderscore( $text );
1328
1329 $text = $this->doHeadings( $text );
1330 $text = $this->replaceInternalLinks( $text );
1331 $text = $this->doAllQuotes( $text );
1332 $text = $this->replaceExternalLinks( $text );
1333
1334 # replaceInternalLinks may sometimes leave behind
1335 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1336 $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text );
1337
1338 $text = $this->doMagicLinks( $text );
1339 $text = $this->formatHeadings( $text, $origText, $isMain );
1340
1341 return $text;
1342 }
1343
1344 /**
1345 * Helper function for parse() that transforms half-parsed HTML into fully
1346 * parsed HTML.
1347 *
1348 * @param string $text
1349 * @param bool $isMain
1350 * @param bool $linestart
1351 * @return string
1352 */
1353 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1354 $text = $this->mStripState->unstripGeneral( $text );
1355
1356 // Avoid PHP 7.1 warning from passing $this by reference
1357 $parser = $this;
1358
1359 if ( $isMain ) {
1360 Hooks::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1361 }
1362
1363 # Clean up special characters, only run once, next-to-last before doBlockLevels
1364 $fixtags = [
1365 # French spaces, last one Guillemet-left
1366 # only if there is something before the space
1367 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
1368 # french spaces, Guillemet-right
1369 '/(\\302\\253) /' => '\\1&#160;',
1370 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1371 ];
1372 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1373
1374 $text = $this->doBlockLevels( $text, $linestart );
1375
1376 $this->replaceLinkHolders( $text );
1377
1378 /**
1379 * The input doesn't get language converted if
1380 * a) It's disabled
1381 * b) Content isn't converted
1382 * c) It's a conversion table
1383 * d) it is an interface message (which is in the user language)
1384 */
1385 if ( !( $this->mOptions->getDisableContentConversion()
1386 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
1387 ) {
1388 if ( !$this->mOptions->getInterfaceMessage() ) {
1389 # The position of the convert() call should not be changed. it
1390 # assumes that the links are all replaced and the only thing left
1391 # is the <nowiki> mark.
1392 $text = $this->getConverterLanguage()->convert( $text );
1393 }
1394 }
1395
1396 $text = $this->mStripState->unstripNoWiki( $text );
1397
1398 if ( $isMain ) {
1399 Hooks::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1400 }
1401
1402 $text = $this->replaceTransparentTags( $text );
1403 $text = $this->mStripState->unstripGeneral( $text );
1404
1405 $text = Sanitizer::normalizeCharReferences( $text );
1406
1407 if ( MWTidy::isEnabled() ) {
1408 if ( $this->mOptions->getTidy() ) {
1409 $text = MWTidy::tidy( $text );
1410 }
1411 } else {
1412 # attempt to sanitize at least some nesting problems
1413 # (T4702 and quite a few others)
1414 $tidyregs = [
1415 # ''Something [http://www.cool.com cool''] -->
1416 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1417 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1418 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1419 # fix up an anchor inside another anchor, only
1420 # at least for a single single nested link (T5695)
1421 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1422 '\\1\\2</a>\\3</a>\\1\\4</a>',
1423 # fix div inside inline elements- doBlockLevels won't wrap a line which
1424 # contains a div, so fix it up here; replace
1425 # div with escaped text
1426 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1427 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
1428 # remove empty italic or bold tag pairs, some
1429 # introduced by rules above
1430 '/<([bi])><\/\\1>/' => '',
1431 ];
1432
1433 $text = preg_replace(
1434 array_keys( $tidyregs ),
1435 array_values( $tidyregs ),
1436 $text );
1437 }
1438
1439 if ( $isMain ) {
1440 Hooks::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1441 }
1442
1443 return $text;
1444 }
1445
1446 /**
1447 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1448 * magic external links.
1449 *
1450 * DML
1451 * @private
1452 *
1453 * @param string $text
1454 *
1455 * @return string
1456 */
1457 public function doMagicLinks( $text ) {
1458 $prots = wfUrlProtocolsWithoutProtRel();
1459 $urlChar = self::EXT_LINK_URL_CLASS;
1460 $addr = self::EXT_LINK_ADDR;
1461 $space = self::SPACE_NOT_NL; # non-newline space
1462 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1463 $spaces = "$space++"; # possessive match of 1 or more spaces
1464 $text = preg_replace_callback(
1465 '!(?: # Start cases
1466 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1467 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1468 (\b # m[3]: Free external links
1469 (?i:$prots)
1470 ($addr$urlChar*) # m[4]: Post-protocol path
1471 ) |
1472 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1473 ([0-9]+)\b |
1474 \bISBN $spaces ( # m[6]: ISBN, capture number
1475 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1476 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1477 [0-9Xx] # check digit
1478 )\b
1479 )!xu", [ $this, 'magicLinkCallback' ], $text );
1480 return $text;
1481 }
1482
1483 /**
1484 * @throws MWException
1485 * @param array $m
1486 * @return HTML|string
1487 */
1488 public function magicLinkCallback( $m ) {
1489 if ( isset( $m[1] ) && $m[1] !== '' ) {
1490 # Skip anchor
1491 return $m[0];
1492 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1493 # Skip HTML element
1494 return $m[0];
1495 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1496 # Free external link
1497 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1498 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1499 # RFC or PMID
1500 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1501 if ( !$this->mOptions->getMagicRFCLinks() ) {
1502 return $m[0];
1503 }
1504 $keyword = 'RFC';
1505 $urlmsg = 'rfcurl';
1506 $cssClass = 'mw-magiclink-rfc';
1507 $trackingCat = 'magiclink-tracking-rfc';
1508 $id = $m[5];
1509 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1510 if ( !$this->mOptions->getMagicPMIDLinks() ) {
1511 return $m[0];
1512 }
1513 $keyword = 'PMID';
1514 $urlmsg = 'pubmedurl';
1515 $cssClass = 'mw-magiclink-pmid';
1516 $trackingCat = 'magiclink-tracking-pmid';
1517 $id = $m[5];
1518 } else {
1519 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1520 substr( $m[0], 0, 20 ) . '"' );
1521 }
1522 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1523 $this->addTrackingCategory( $trackingCat );
1524 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle );
1525 } elseif ( isset( $m[6] ) && $m[6] !== ''
1526 && $this->mOptions->getMagicISBNLinks()
1527 ) {
1528 # ISBN
1529 $isbn = $m[6];
1530 $space = self::SPACE_NOT_NL; # non-newline space
1531 $isbn = preg_replace( "/$space/", ' ', $isbn );
1532 $num = strtr( $isbn, [
1533 '-' => '',
1534 ' ' => '',
1535 'x' => 'X',
1536 ] );
1537 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1538 return $this->getLinkRenderer()->makeKnownLink(
1539 SpecialPage::getTitleFor( 'Booksources', $num ),
1540 "ISBN $isbn",
1541 [
1542 'class' => 'internal mw-magiclink-isbn',
1543 'title' => false // suppress title attribute
1544 ]
1545 );
1546 } else {
1547 return $m[0];
1548 }
1549 }
1550
1551 /**
1552 * Make a free external link, given a user-supplied URL
1553 *
1554 * @param string $url
1555 * @param int $numPostProto
1556 * The number of characters after the protocol.
1557 * @return string HTML
1558 * @private
1559 */
1560 public function makeFreeExternalLink( $url, $numPostProto ) {
1561 $trail = '';
1562
1563 # The characters '<' and '>' (which were escaped by
1564 # removeHTMLtags()) should not be included in
1565 # URLs, per RFC 2396.
1566 # Make &nbsp; terminate a URL as well (bug T84937)
1567 $m2 = [];
1568 if ( preg_match(
1569 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1570 $url,
1571 $m2,
1572 PREG_OFFSET_CAPTURE
1573 ) ) {
1574 $trail = substr( $url, $m2[0][1] ) . $trail;
1575 $url = substr( $url, 0, $m2[0][1] );
1576 }
1577
1578 # Move trailing punctuation to $trail
1579 $sep = ',;\.:!?';
1580 # If there is no left bracket, then consider right brackets fair game too
1581 if ( strpos( $url, '(' ) === false ) {
1582 $sep .= ')';
1583 }
1584
1585 $urlRev = strrev( $url );
1586 $numSepChars = strspn( $urlRev, $sep );
1587 # Don't break a trailing HTML entity by moving the ; into $trail
1588 # This is in hot code, so use substr_compare to avoid having to
1589 # create a new string object for the comparison
1590 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1591 # more optimization: instead of running preg_match with a $
1592 # anchor, which can be slow, do the match on the reversed
1593 # string starting at the desired offset.
1594 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1595 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1596 $numSepChars--;
1597 }
1598 }
1599 if ( $numSepChars ) {
1600 $trail = substr( $url, -$numSepChars ) . $trail;
1601 $url = substr( $url, 0, -$numSepChars );
1602 }
1603
1604 # Verify that we still have a real URL after trail removal, and
1605 # not just lone protocol
1606 if ( strlen( $trail ) >= $numPostProto ) {
1607 return $url . $trail;
1608 }
1609
1610 $url = Sanitizer::cleanUrl( $url );
1611
1612 # Is this an external image?
1613 $text = $this->maybeMakeExternalImage( $url );
1614 if ( $text === false ) {
1615 # Not an image, make a link
1616 $text = Linker::makeExternalLink( $url,
1617 $this->getConverterLanguage()->markNoConversion( $url, true ),
1618 true, 'free',
1619 $this->getExternalLinkAttribs( $url ), $this->mTitle );
1620 # Register it in the output object...
1621 $this->mOutput->addExternalLink( $url );
1622 }
1623 return $text . $trail;
1624 }
1625
1626 /**
1627 * Parse headers and return html
1628 *
1629 * @private
1630 *
1631 * @param string $text
1632 *
1633 * @return string
1634 */
1635 public function doHeadings( $text ) {
1636 for ( $i = 6; $i >= 1; --$i ) {
1637 $h = str_repeat( '=', $i );
1638 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1639 }
1640 return $text;
1641 }
1642
1643 /**
1644 * Replace single quotes with HTML markup
1645 * @private
1646 *
1647 * @param string $text
1648 *
1649 * @return string The altered text
1650 */
1651 public function doAllQuotes( $text ) {
1652 $outtext = '';
1653 $lines = StringUtils::explode( "\n", $text );
1654 foreach ( $lines as $line ) {
1655 $outtext .= $this->doQuotes( $line ) . "\n";
1656 }
1657 $outtext = substr( $outtext, 0, -1 );
1658 return $outtext;
1659 }
1660
1661 /**
1662 * Helper function for doAllQuotes()
1663 *
1664 * @param string $text
1665 *
1666 * @return string
1667 */
1668 public function doQuotes( $text ) {
1669 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1670 $countarr = count( $arr );
1671 if ( $countarr == 1 ) {
1672 return $text;
1673 }
1674
1675 // First, do some preliminary work. This may shift some apostrophes from
1676 // being mark-up to being text. It also counts the number of occurrences
1677 // of bold and italics mark-ups.
1678 $numbold = 0;
1679 $numitalics = 0;
1680 for ( $i = 1; $i < $countarr; $i += 2 ) {
1681 $thislen = strlen( $arr[$i] );
1682 // If there are ever four apostrophes, assume the first is supposed to
1683 // be text, and the remaining three constitute mark-up for bold text.
1684 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1685 if ( $thislen == 4 ) {
1686 $arr[$i - 1] .= "'";
1687 $arr[$i] = "'''";
1688 $thislen = 3;
1689 } elseif ( $thislen > 5 ) {
1690 // If there are more than 5 apostrophes in a row, assume they're all
1691 // text except for the last 5.
1692 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1693 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1694 $arr[$i] = "'''''";
1695 $thislen = 5;
1696 }
1697 // Count the number of occurrences of bold and italics mark-ups.
1698 if ( $thislen == 2 ) {
1699 $numitalics++;
1700 } elseif ( $thislen == 3 ) {
1701 $numbold++;
1702 } elseif ( $thislen == 5 ) {
1703 $numitalics++;
1704 $numbold++;
1705 }
1706 }
1707
1708 // If there is an odd number of both bold and italics, it is likely
1709 // that one of the bold ones was meant to be an apostrophe followed
1710 // by italics. Which one we cannot know for certain, but it is more
1711 // likely to be one that has a single-letter word before it.
1712 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1713 $firstsingleletterword = -1;
1714 $firstmultiletterword = -1;
1715 $firstspace = -1;
1716 for ( $i = 1; $i < $countarr; $i += 2 ) {
1717 if ( strlen( $arr[$i] ) == 3 ) {
1718 $x1 = substr( $arr[$i - 1], -1 );
1719 $x2 = substr( $arr[$i - 1], -2, 1 );
1720 if ( $x1 === ' ' ) {
1721 if ( $firstspace == -1 ) {
1722 $firstspace = $i;
1723 }
1724 } elseif ( $x2 === ' ' ) {
1725 $firstsingleletterword = $i;
1726 // if $firstsingleletterword is set, we don't
1727 // look at the other options, so we can bail early.
1728 break;
1729 } else {
1730 if ( $firstmultiletterword == -1 ) {
1731 $firstmultiletterword = $i;
1732 }
1733 }
1734 }
1735 }
1736
1737 // If there is a single-letter word, use it!
1738 if ( $firstsingleletterword > -1 ) {
1739 $arr[$firstsingleletterword] = "''";
1740 $arr[$firstsingleletterword - 1] .= "'";
1741 } elseif ( $firstmultiletterword > -1 ) {
1742 // If not, but there's a multi-letter word, use that one.
1743 $arr[$firstmultiletterword] = "''";
1744 $arr[$firstmultiletterword - 1] .= "'";
1745 } elseif ( $firstspace > -1 ) {
1746 // ... otherwise use the first one that has neither.
1747 // (notice that it is possible for all three to be -1 if, for example,
1748 // there is only one pentuple-apostrophe in the line)
1749 $arr[$firstspace] = "''";
1750 $arr[$firstspace - 1] .= "'";
1751 }
1752 }
1753
1754 // Now let's actually convert our apostrophic mush to HTML!
1755 $output = '';
1756 $buffer = '';
1757 $state = '';
1758 $i = 0;
1759 foreach ( $arr as $r ) {
1760 if ( ( $i % 2 ) == 0 ) {
1761 if ( $state === 'both' ) {
1762 $buffer .= $r;
1763 } else {
1764 $output .= $r;
1765 }
1766 } else {
1767 $thislen = strlen( $r );
1768 if ( $thislen == 2 ) {
1769 if ( $state === 'i' ) {
1770 $output .= '</i>';
1771 $state = '';
1772 } elseif ( $state === 'bi' ) {
1773 $output .= '</i>';
1774 $state = 'b';
1775 } elseif ( $state === 'ib' ) {
1776 $output .= '</b></i><b>';
1777 $state = 'b';
1778 } elseif ( $state === 'both' ) {
1779 $output .= '<b><i>' . $buffer . '</i>';
1780 $state = 'b';
1781 } else { // $state can be 'b' or ''
1782 $output .= '<i>';
1783 $state .= 'i';
1784 }
1785 } elseif ( $thislen == 3 ) {
1786 if ( $state === 'b' ) {
1787 $output .= '</b>';
1788 $state = '';
1789 } elseif ( $state === 'bi' ) {
1790 $output .= '</i></b><i>';
1791 $state = 'i';
1792 } elseif ( $state === 'ib' ) {
1793 $output .= '</b>';
1794 $state = 'i';
1795 } elseif ( $state === 'both' ) {
1796 $output .= '<i><b>' . $buffer . '</b>';
1797 $state = 'i';
1798 } else { // $state can be 'i' or ''
1799 $output .= '<b>';
1800 $state .= 'b';
1801 }
1802 } elseif ( $thislen == 5 ) {
1803 if ( $state === 'b' ) {
1804 $output .= '</b><i>';
1805 $state = 'i';
1806 } elseif ( $state === 'i' ) {
1807 $output .= '</i><b>';
1808 $state = 'b';
1809 } elseif ( $state === 'bi' ) {
1810 $output .= '</i></b>';
1811 $state = '';
1812 } elseif ( $state === 'ib' ) {
1813 $output .= '</b></i>';
1814 $state = '';
1815 } elseif ( $state === 'both' ) {
1816 $output .= '<i><b>' . $buffer . '</b></i>';
1817 $state = '';
1818 } else { // ($state == '')
1819 $buffer = '';
1820 $state = 'both';
1821 }
1822 }
1823 }
1824 $i++;
1825 }
1826 // Now close all remaining tags. Notice that the order is important.
1827 if ( $state === 'b' || $state === 'ib' ) {
1828 $output .= '</b>';
1829 }
1830 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1831 $output .= '</i>';
1832 }
1833 if ( $state === 'bi' ) {
1834 $output .= '</b>';
1835 }
1836 // There might be lonely ''''', so make sure we have a buffer
1837 if ( $state === 'both' && $buffer ) {
1838 $output .= '<b><i>' . $buffer . '</i></b>';
1839 }
1840 return $output;
1841 }
1842
1843 /**
1844 * Replace external links (REL)
1845 *
1846 * Note: this is all very hackish and the order of execution matters a lot.
1847 * Make sure to run tests/parser/parserTests.php if you change this code.
1848 *
1849 * @private
1850 *
1851 * @param string $text
1852 *
1853 * @throws MWException
1854 * @return string
1855 */
1856 public function replaceExternalLinks( $text ) {
1857
1858 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1859 if ( $bits === false ) {
1860 throw new MWException( "PCRE needs to be compiled with "
1861 . "--enable-unicode-properties in order for MediaWiki to function" );
1862 }
1863 $s = array_shift( $bits );
1864
1865 $i = 0;
1866 while ( $i < count( $bits ) ) {
1867 $url = $bits[$i++];
1868 $i++; // protocol
1869 $text = $bits[$i++];
1870 $trail = $bits[$i++];
1871
1872 # The characters '<' and '>' (which were escaped by
1873 # removeHTMLtags()) should not be included in
1874 # URLs, per RFC 2396.
1875 $m2 = [];
1876 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1877 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1878 $url = substr( $url, 0, $m2[0][1] );
1879 }
1880
1881 # If the link text is an image URL, replace it with an <img> tag
1882 # This happened by accident in the original parser, but some people used it extensively
1883 $img = $this->maybeMakeExternalImage( $text );
1884 if ( $img !== false ) {
1885 $text = $img;
1886 }
1887
1888 $dtrail = '';
1889
1890 # Set linktype for CSS - if URL==text, link is essentially free
1891 $linktype = ( $text === $url ) ? 'free' : 'text';
1892
1893 # No link text, e.g. [http://domain.tld/some.link]
1894 if ( $text == '' ) {
1895 # Autonumber
1896 $langObj = $this->getTargetLanguage();
1897 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1898 $linktype = 'autonumber';
1899 } else {
1900 # Have link text, e.g. [http://domain.tld/some.link text]s
1901 # Check for trail
1902 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1903 }
1904
1905 $text = $this->getConverterLanguage()->markNoConversion( $text );
1906
1907 $url = Sanitizer::cleanUrl( $url );
1908
1909 # Use the encoded URL
1910 # This means that users can paste URLs directly into the text
1911 # Funny characters like ö aren't valid in URLs anyway
1912 # This was changed in August 2004
1913 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1914 $this->getExternalLinkAttribs( $url ), $this->mTitle ) . $dtrail . $trail;
1915
1916 # Register link in the output object.
1917 $this->mOutput->addExternalLink( $url );
1918 }
1919
1920 return $s;
1921 }
1922
1923 /**
1924 * Get the rel attribute for a particular external link.
1925 *
1926 * @since 1.21
1927 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1928 * nofollow if appropriate
1929 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1930 * @return string|null Rel attribute for $url
1931 */
1932 public static function getExternalLinkRel( $url = false, $title = null ) {
1933 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1934 $ns = $title ? $title->getNamespace() : false;
1935 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1936 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1937 ) {
1938 return 'nofollow';
1939 }
1940 return null;
1941 }
1942
1943 /**
1944 * Get an associative array of additional HTML attributes appropriate for a
1945 * particular external link. This currently may include rel => nofollow
1946 * (depending on configuration, namespace, and the URL's domain) and/or a
1947 * target attribute (depending on configuration).
1948 *
1949 * @param string $url URL to extract the domain from for rel =>
1950 * nofollow if appropriate
1951 * @return array Associative array of HTML attributes
1952 */
1953 public function getExternalLinkAttribs( $url ) {
1954 $attribs = [];
1955 $rel = self::getExternalLinkRel( $url, $this->mTitle );
1956
1957 $target = $this->mOptions->getExternalLinkTarget();
1958 if ( $target ) {
1959 $attribs['target'] = $target;
1960 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1961 // T133507. New windows can navigate parent cross-origin.
1962 // Including noreferrer due to lacking browser
1963 // support of noopener. Eventually noreferrer should be removed.
1964 if ( $rel !== '' ) {
1965 $rel .= ' ';
1966 }
1967 $rel .= 'noreferrer noopener';
1968 }
1969 }
1970 $attribs['rel'] = $rel;
1971 return $attribs;
1972 }
1973
1974 /**
1975 * Replace unusual escape codes in a URL with their equivalent characters
1976 *
1977 * This generally follows the syntax defined in RFC 3986, with special
1978 * consideration for HTTP query strings.
1979 *
1980 * @param string $url
1981 * @return string
1982 */
1983 public static function normalizeLinkUrl( $url ) {
1984 # First, make sure unsafe characters are encoded
1985 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1986 function ( $m ) {
1987 return rawurlencode( $m[0] );
1988 },
1989 $url
1990 );
1991
1992 $ret = '';
1993 $end = strlen( $url );
1994
1995 # Fragment part - 'fragment'
1996 $start = strpos( $url, '#' );
1997 if ( $start !== false && $start < $end ) {
1998 $ret = self::normalizeUrlComponent(
1999 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2000 $end = $start;
2001 }
2002
2003 # Query part - 'query' minus &=+;
2004 $start = strpos( $url, '?' );
2005 if ( $start !== false && $start < $end ) {
2006 $ret = self::normalizeUrlComponent(
2007 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2008 $end = $start;
2009 }
2010
2011 # Scheme and path part - 'pchar'
2012 # (we assume no userinfo or encoded colons in the host)
2013 $ret = self::normalizeUrlComponent(
2014 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2015
2016 return $ret;
2017 }
2018
2019 private static function normalizeUrlComponent( $component, $unsafe ) {
2020 $callback = function ( $matches ) use ( $unsafe ) {
2021 $char = urldecode( $matches[0] );
2022 $ord = ord( $char );
2023 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2024 # Unescape it
2025 return $char;
2026 } else {
2027 # Leave it escaped, but use uppercase for a-f
2028 return strtoupper( $matches[0] );
2029 }
2030 };
2031 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2032 }
2033
2034 /**
2035 * make an image if it's allowed, either through the global
2036 * option, through the exception, or through the on-wiki whitelist
2037 *
2038 * @param string $url
2039 *
2040 * @return string
2041 */
2042 private function maybeMakeExternalImage( $url ) {
2043 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
2044 $imagesexception = !empty( $imagesfrom );
2045 $text = false;
2046 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2047 if ( $imagesexception && is_array( $imagesfrom ) ) {
2048 $imagematch = false;
2049 foreach ( $imagesfrom as $match ) {
2050 if ( strpos( $url, $match ) === 0 ) {
2051 $imagematch = true;
2052 break;
2053 }
2054 }
2055 } elseif ( $imagesexception ) {
2056 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2057 } else {
2058 $imagematch = false;
2059 }
2060
2061 if ( $this->mOptions->getAllowExternalImages()
2062 || ( $imagesexception && $imagematch )
2063 ) {
2064 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
2065 # Image found
2066 $text = Linker::makeExternalImage( $url );
2067 }
2068 }
2069 if ( !$text && $this->mOptions->getEnableImageWhitelist()
2070 && preg_match( self::EXT_IMAGE_REGEX, $url )
2071 ) {
2072 $whitelist = explode(
2073 "\n",
2074 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2075 );
2076
2077 foreach ( $whitelist as $entry ) {
2078 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2079 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
2080 continue;
2081 }
2082 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2083 # Image matches a whitelist entry
2084 $text = Linker::makeExternalImage( $url );
2085 break;
2086 }
2087 }
2088 }
2089 return $text;
2090 }
2091
2092 /**
2093 * Process [[ ]] wikilinks
2094 *
2095 * @param string $s
2096 *
2097 * @return string Processed text
2098 *
2099 * @private
2100 */
2101 public function replaceInternalLinks( $s ) {
2102 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
2103 return $s;
2104 }
2105
2106 /**
2107 * Process [[ ]] wikilinks (RIL)
2108 * @param string $s
2109 * @throws MWException
2110 * @return LinkHolderArray
2111 *
2112 * @private
2113 */
2114 public function replaceInternalLinks2( &$s ) {
2115 global $wgExtraInterlanguageLinkPrefixes;
2116
2117 static $tc = false, $e1, $e1_img;
2118 # the % is needed to support urlencoded titles as well
2119 if ( !$tc ) {
2120 $tc = Title::legalChars() . '#%';
2121 # Match a link having the form [[namespace:link|alternate]]trail
2122 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2123 # Match cases where there is no "]]", which might still be images
2124 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2125 }
2126
2127 $holders = new LinkHolderArray( $this );
2128
2129 # split the entire text string on occurrences of [[
2130 $a = StringUtils::explode( '[[', ' ' . $s );
2131 # get the first element (all text up to first [[), and remove the space we added
2132 $s = $a->current();
2133 $a->next();
2134 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2135 $s = substr( $s, 1 );
2136
2137 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2138 $e2 = null;
2139 if ( $useLinkPrefixExtension ) {
2140 # Match the end of a line for a word that's not followed by whitespace,
2141 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2142 global $wgContLang;
2143 $charset = $wgContLang->linkPrefixCharset();
2144 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2145 }
2146
2147 if ( is_null( $this->mTitle ) ) {
2148 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2149 }
2150 $nottalk = !$this->mTitle->isTalkPage();
2151
2152 if ( $useLinkPrefixExtension ) {
2153 $m = [];
2154 if ( preg_match( $e2, $s, $m ) ) {
2155 $first_prefix = $m[2];
2156 } else {
2157 $first_prefix = false;
2158 }
2159 } else {
2160 $prefix = '';
2161 }
2162
2163 $useSubpages = $this->areSubpagesAllowed();
2164
2165 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2166 # Loop for each link
2167 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2168 // @codingStandardsIgnoreEnd
2169
2170 # Check for excessive memory usage
2171 if ( $holders->isBig() ) {
2172 # Too big
2173 # Do the existence check, replace the link holders and clear the array
2174 $holders->replace( $s );
2175 $holders->clear();
2176 }
2177
2178 if ( $useLinkPrefixExtension ) {
2179 if ( preg_match( $e2, $s, $m ) ) {
2180 $prefix = $m[2];
2181 $s = $m[1];
2182 } else {
2183 $prefix = '';
2184 }
2185 # first link
2186 if ( $first_prefix ) {
2187 $prefix = $first_prefix;
2188 $first_prefix = false;
2189 }
2190 }
2191
2192 $might_be_img = false;
2193
2194 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2195 $text = $m[2];
2196 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2197 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2198 # the real problem is with the $e1 regex
2199 # See T1500.
2200 # Still some problems for cases where the ] is meant to be outside punctuation,
2201 # and no image is in sight. See T4095.
2202 if ( $text !== ''
2203 && substr( $m[3], 0, 1 ) === ']'
2204 && strpos( $text, '[' ) !== false
2205 ) {
2206 $text .= ']'; # so that replaceExternalLinks($text) works later
2207 $m[3] = substr( $m[3], 1 );
2208 }
2209 # fix up urlencoded title texts
2210 if ( strpos( $m[1], '%' ) !== false ) {
2211 # Should anchors '#' also be rejected?
2212 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2213 }
2214 $trail = $m[3];
2215 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2216 # Invalid, but might be an image with a link in its caption
2217 $might_be_img = true;
2218 $text = $m[2];
2219 if ( strpos( $m[1], '%' ) !== false ) {
2220 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2221 }
2222 $trail = "";
2223 } else { # Invalid form; output directly
2224 $s .= $prefix . '[[' . $line;
2225 continue;
2226 }
2227
2228 $origLink = ltrim( $m[1], ' ' );
2229
2230 # Don't allow internal links to pages containing
2231 # PROTO: where PROTO is a valid URL protocol; these
2232 # should be external links.
2233 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) {
2234 $s .= $prefix . '[[' . $line;
2235 continue;
2236 }
2237
2238 # Make subpage if necessary
2239 if ( $useSubpages ) {
2240 $link = $this->maybeDoSubpageLink( $origLink, $text );
2241 } else {
2242 $link = $origLink;
2243 }
2244
2245 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2246 if ( !$noforce ) {
2247 # Strip off leading ':'
2248 $link = substr( $link, 1 );
2249 }
2250
2251 $unstrip = $this->mStripState->unstripNoWiki( $link );
2252 $nt = is_string( $unstrip ) ? Title::newFromText( $unstrip ) : null;
2253 if ( $nt === null ) {
2254 $s .= $prefix . '[[' . $line;
2255 continue;
2256 }
2257
2258 $ns = $nt->getNamespace();
2259 $iw = $nt->getInterwiki();
2260
2261 if ( $might_be_img ) { # if this is actually an invalid link
2262 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2263 $found = false;
2264 while ( true ) {
2265 # look at the next 'line' to see if we can close it there
2266 $a->next();
2267 $next_line = $a->current();
2268 if ( $next_line === false || $next_line === null ) {
2269 break;
2270 }
2271 $m = explode( ']]', $next_line, 3 );
2272 if ( count( $m ) == 3 ) {
2273 # the first ]] closes the inner link, the second the image
2274 $found = true;
2275 $text .= "[[{$m[0]}]]{$m[1]}";
2276 $trail = $m[2];
2277 break;
2278 } elseif ( count( $m ) == 2 ) {
2279 # if there's exactly one ]] that's fine, we'll keep looking
2280 $text .= "[[{$m[0]}]]{$m[1]}";
2281 } else {
2282 # if $next_line is invalid too, we need look no further
2283 $text .= '[[' . $next_line;
2284 break;
2285 }
2286 }
2287 if ( !$found ) {
2288 # we couldn't find the end of this imageLink, so output it raw
2289 # but don't ignore what might be perfectly normal links in the text we've examined
2290 $holders->merge( $this->replaceInternalLinks2( $text ) );
2291 $s .= "{$prefix}[[$link|$text";
2292 # note: no $trail, because without an end, there *is* no trail
2293 continue;
2294 }
2295 } else { # it's not an image, so output it raw
2296 $s .= "{$prefix}[[$link|$text";
2297 # note: no $trail, because without an end, there *is* no trail
2298 continue;
2299 }
2300 }
2301
2302 $wasblank = ( $text == '' );
2303 if ( $wasblank ) {
2304 $text = $link;
2305 } else {
2306 # T6598 madness. Handle the quotes only if they come from the alternate part
2307 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2308 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2309 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2310 $text = $this->doQuotes( $text );
2311 }
2312
2313 # Link not escaped by : , create the various objects
2314 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2315 # Interwikis
2316 if (
2317 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2318 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2319 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2320 )
2321 ) {
2322 # T26502: filter duplicates
2323 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2324 $this->mLangLinkLanguages[$iw] = true;
2325 $this->mOutput->addLanguageLink( $nt->getFullText() );
2326 }
2327
2328 $s = rtrim( $s . $prefix );
2329 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2330 continue;
2331 }
2332
2333 if ( $ns == NS_FILE ) {
2334 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2335 if ( $wasblank ) {
2336 # if no parameters were passed, $text
2337 # becomes something like "File:Foo.png",
2338 # which we don't want to pass on to the
2339 # image generator
2340 $text = '';
2341 } else {
2342 # recursively parse links inside the image caption
2343 # actually, this will parse them in any other parameters, too,
2344 # but it might be hard to fix that, and it doesn't matter ATM
2345 $text = $this->replaceExternalLinks( $text );
2346 $holders->merge( $this->replaceInternalLinks2( $text ) );
2347 }
2348 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2349 $s .= $prefix . $this->armorLinks(
2350 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2351 continue;
2352 }
2353 } elseif ( $ns == NS_CATEGORY ) {
2354 $s = rtrim( $s . "\n" ); # T2087
2355
2356 if ( $wasblank ) {
2357 $sortkey = $this->getDefaultSort();
2358 } else {
2359 $sortkey = $text;
2360 }
2361 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2362 $sortkey = str_replace( "\n", '', $sortkey );
2363 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2364 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2365
2366 /**
2367 * Strip the whitespace Category links produce, see T2087
2368 */
2369 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2370
2371 continue;
2372 }
2373 }
2374
2375 # Self-link checking. For some languages, variants of the title are checked in
2376 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2377 # for linking to a different variant.
2378 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2379 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2380 continue;
2381 }
2382
2383 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2384 # @todo FIXME: Should do batch file existence checks, see comment below
2385 if ( $ns == NS_MEDIA ) {
2386 # Give extensions a chance to select the file revision for us
2387 $options = [];
2388 $descQuery = false;
2389 Hooks::run( 'BeforeParserFetchFileAndTitle',
2390 [ $this, $nt, &$options, &$descQuery ] );
2391 # Fetch and register the file (file title may be different via hooks)
2392 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2393 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2394 $s .= $prefix . $this->armorLinks(
2395 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2396 continue;
2397 }
2398
2399 # Some titles, such as valid special pages or files in foreign repos, should
2400 # be shown as bluelinks even though they're not included in the page table
2401 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2402 # batch file existence checks for NS_FILE and NS_MEDIA
2403 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2404 $this->mOutput->addLink( $nt );
2405 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2406 } else {
2407 # Links will be added to the output link list after checking
2408 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2409 }
2410 }
2411 return $holders;
2412 }
2413
2414 /**
2415 * Render a forced-blue link inline; protect against double expansion of
2416 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2417 * Since this little disaster has to split off the trail text to avoid
2418 * breaking URLs in the following text without breaking trails on the
2419 * wiki links, it's been made into a horrible function.
2420 *
2421 * @param Title $nt
2422 * @param string $text
2423 * @param string $trail
2424 * @param string $prefix
2425 * @return string HTML-wikitext mix oh yuck
2426 */
2427 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2428 list( $inside, $trail ) = Linker::splitTrail( $trail );
2429
2430 if ( $text == '' ) {
2431 $text = htmlspecialchars( $nt->getPrefixedText() );
2432 }
2433
2434 $link = $this->getLinkRenderer()->makeKnownLink(
2435 $nt, new HtmlArmor( "$prefix$text$inside" )
2436 );
2437
2438 return $this->armorLinks( $link ) . $trail;
2439 }
2440
2441 /**
2442 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2443 * going to go through further parsing steps before inline URL expansion.
2444 *
2445 * Not needed quite as much as it used to be since free links are a bit
2446 * more sensible these days. But bracketed links are still an issue.
2447 *
2448 * @param string $text More-or-less HTML
2449 * @return string Less-or-more HTML with NOPARSE bits
2450 */
2451 public function armorLinks( $text ) {
2452 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2453 self::MARKER_PREFIX . "NOPARSE$1", $text );
2454 }
2455
2456 /**
2457 * Return true if subpage links should be expanded on this page.
2458 * @return bool
2459 */
2460 public function areSubpagesAllowed() {
2461 # Some namespaces don't allow subpages
2462 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2463 }
2464
2465 /**
2466 * Handle link to subpage if necessary
2467 *
2468 * @param string $target The source of the link
2469 * @param string &$text The link text, modified as necessary
2470 * @return string The full name of the link
2471 * @private
2472 */
2473 public function maybeDoSubpageLink( $target, &$text ) {
2474 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2475 }
2476
2477 /**
2478 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2479 *
2480 * @param string $text
2481 * @param bool $linestart Whether or not this is at the start of a line.
2482 * @private
2483 * @return string The lists rendered as HTML
2484 */
2485 public function doBlockLevels( $text, $linestart ) {
2486 return BlockLevelPass::doBlockLevels( $text, $linestart );
2487 }
2488
2489 /**
2490 * Return value of a magic variable (like PAGENAME)
2491 *
2492 * @private
2493 *
2494 * @param string $index Magic variable identifier as mapped in MagicWord::$mVariableIDs
2495 * @param bool|PPFrame $frame
2496 *
2497 * @throws MWException
2498 * @return string
2499 */
2500 public function getVariableValue( $index, $frame = false ) {
2501 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2502 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2503
2504 if ( is_null( $this->mTitle ) ) {
2505 // If no title set, bad things are going to happen
2506 // later. Title should always be set since this
2507 // should only be called in the middle of a parse
2508 // operation (but the unit-tests do funky stuff)
2509 throw new MWException( __METHOD__ . ' Should only be '
2510 . ' called while parsing (no title set)' );
2511 }
2512
2513 // Avoid PHP 7.1 warning from passing $this by reference
2514 $parser = $this;
2515
2516 /**
2517 * Some of these require message or data lookups and can be
2518 * expensive to check many times.
2519 */
2520 if ( Hooks::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache ] ) ) {
2521 if ( isset( $this->mVarCache[$index] ) ) {
2522 return $this->mVarCache[$index];
2523 }
2524 }
2525
2526 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2527 Hooks::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2528
2529 $pageLang = $this->getFunctionLang();
2530
2531 switch ( $index ) {
2532 case '!':
2533 $value = '|';
2534 break;
2535 case 'currentmonth':
2536 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) );
2537 break;
2538 case 'currentmonth1':
2539 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2540 break;
2541 case 'currentmonthname':
2542 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2543 break;
2544 case 'currentmonthnamegen':
2545 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2546 break;
2547 case 'currentmonthabbrev':
2548 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2549 break;
2550 case 'currentday':
2551 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) );
2552 break;
2553 case 'currentday2':
2554 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) );
2555 break;
2556 case 'localmonth':
2557 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) );
2558 break;
2559 case 'localmonth1':
2560 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2561 break;
2562 case 'localmonthname':
2563 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2564 break;
2565 case 'localmonthnamegen':
2566 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2567 break;
2568 case 'localmonthabbrev':
2569 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2570 break;
2571 case 'localday':
2572 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) );
2573 break;
2574 case 'localday2':
2575 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) );
2576 break;
2577 case 'pagename':
2578 $value = wfEscapeWikiText( $this->mTitle->getText() );
2579 break;
2580 case 'pagenamee':
2581 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2582 break;
2583 case 'fullpagename':
2584 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2585 break;
2586 case 'fullpagenamee':
2587 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2588 break;
2589 case 'subpagename':
2590 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2591 break;
2592 case 'subpagenamee':
2593 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2594 break;
2595 case 'rootpagename':
2596 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2597 break;
2598 case 'rootpagenamee':
2599 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2600 ' ',
2601 '_',
2602 $this->mTitle->getRootText()
2603 ) ) );
2604 break;
2605 case 'basepagename':
2606 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2607 break;
2608 case 'basepagenamee':
2609 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2610 ' ',
2611 '_',
2612 $this->mTitle->getBaseText()
2613 ) ) );
2614 break;
2615 case 'talkpagename':
2616 if ( $this->mTitle->canTalk() ) {
2617 $talkPage = $this->mTitle->getTalkPage();
2618 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2619 } else {
2620 $value = '';
2621 }
2622 break;
2623 case 'talkpagenamee':
2624 if ( $this->mTitle->canTalk() ) {
2625 $talkPage = $this->mTitle->getTalkPage();
2626 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2627 } else {
2628 $value = '';
2629 }
2630 break;
2631 case 'subjectpagename':
2632 $subjPage = $this->mTitle->getSubjectPage();
2633 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2634 break;
2635 case 'subjectpagenamee':
2636 $subjPage = $this->mTitle->getSubjectPage();
2637 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2638 break;
2639 case 'pageid': // requested in T25427
2640 $pageid = $this->getTitle()->getArticleID();
2641 if ( $pageid == 0 ) {
2642 # 0 means the page doesn't exist in the database,
2643 # which means the user is previewing a new page.
2644 # The vary-revision flag must be set, because the magic word
2645 # will have a different value once the page is saved.
2646 $this->mOutput->setFlag( 'vary-revision' );
2647 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2648 }
2649 $value = $pageid ? $pageid : null;
2650 break;
2651 case 'revisionid':
2652 # Let the edit saving system know we should parse the page
2653 # *after* a revision ID has been assigned.
2654 $this->mOutput->setFlag( 'vary-revision-id' );
2655 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2656 $value = $this->mRevisionId;
2657 if ( !$value && $this->mOptions->getSpeculativeRevIdCallback() ) {
2658 $value = call_user_func( $this->mOptions->getSpeculativeRevIdCallback() );
2659 $this->mOutput->setSpeculativeRevIdUsed( $value );
2660 }
2661 break;
2662 case 'revisionday':
2663 # Let the edit saving system know we should parse the page
2664 # *after* a revision ID has been assigned. This is for null edits.
2665 $this->mOutput->setFlag( 'vary-revision' );
2666 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2667 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2668 break;
2669 case 'revisionday2':
2670 # Let the edit saving system know we should parse the page
2671 # *after* a revision ID has been assigned. This is for null edits.
2672 $this->mOutput->setFlag( 'vary-revision' );
2673 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2674 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2675 break;
2676 case 'revisionmonth':
2677 # Let the edit saving system know we should parse the page
2678 # *after* a revision ID has been assigned. This is for null edits.
2679 $this->mOutput->setFlag( 'vary-revision' );
2680 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2681 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2682 break;
2683 case 'revisionmonth1':
2684 # Let the edit saving system know we should parse the page
2685 # *after* a revision ID has been assigned. This is for null edits.
2686 $this->mOutput->setFlag( 'vary-revision' );
2687 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2688 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2689 break;
2690 case 'revisionyear':
2691 # Let the edit saving system know we should parse the page
2692 # *after* a revision ID has been assigned. This is for null edits.
2693 $this->mOutput->setFlag( 'vary-revision' );
2694 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2695 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2696 break;
2697 case 'revisiontimestamp':
2698 # Let the edit saving system know we should parse the page
2699 # *after* a revision ID has been assigned. This is for null edits.
2700 $this->mOutput->setFlag( 'vary-revision' );
2701 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2702 $value = $this->getRevisionTimestamp();
2703 break;
2704 case 'revisionuser':
2705 # Let the edit saving system know we should parse the page
2706 # *after* a revision ID has been assigned for null edits.
2707 $this->mOutput->setFlag( 'vary-user' );
2708 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-user...\n" );
2709 $value = $this->getRevisionUser();
2710 break;
2711 case 'revisionsize':
2712 $value = $this->getRevisionSize();
2713 break;
2714 case 'namespace':
2715 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2716 break;
2717 case 'namespacee':
2718 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2719 break;
2720 case 'namespacenumber':
2721 $value = $this->mTitle->getNamespace();
2722 break;
2723 case 'talkspace':
2724 $value = $this->mTitle->canTalk()
2725 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
2726 : '';
2727 break;
2728 case 'talkspacee':
2729 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2730 break;
2731 case 'subjectspace':
2732 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
2733 break;
2734 case 'subjectspacee':
2735 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2736 break;
2737 case 'currentdayname':
2738 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
2739 break;
2740 case 'currentyear':
2741 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
2742 break;
2743 case 'currenttime':
2744 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2745 break;
2746 case 'currenthour':
2747 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
2748 break;
2749 case 'currentweek':
2750 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2751 # int to remove the padding
2752 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
2753 break;
2754 case 'currentdow':
2755 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
2756 break;
2757 case 'localdayname':
2758 $value = $pageLang->getWeekdayName(
2759 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
2760 );
2761 break;
2762 case 'localyear':
2763 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
2764 break;
2765 case 'localtime':
2766 $value = $pageLang->time(
2767 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
2768 false,
2769 false
2770 );
2771 break;
2772 case 'localhour':
2773 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
2774 break;
2775 case 'localweek':
2776 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2777 # int to remove the padding
2778 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
2779 break;
2780 case 'localdow':
2781 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
2782 break;
2783 case 'numberofarticles':
2784 $value = $pageLang->formatNum( SiteStats::articles() );
2785 break;
2786 case 'numberoffiles':
2787 $value = $pageLang->formatNum( SiteStats::images() );
2788 break;
2789 case 'numberofusers':
2790 $value = $pageLang->formatNum( SiteStats::users() );
2791 break;
2792 case 'numberofactiveusers':
2793 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2794 break;
2795 case 'numberofpages':
2796 $value = $pageLang->formatNum( SiteStats::pages() );
2797 break;
2798 case 'numberofadmins':
2799 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2800 break;
2801 case 'numberofedits':
2802 $value = $pageLang->formatNum( SiteStats::edits() );
2803 break;
2804 case 'currenttimestamp':
2805 $value = wfTimestamp( TS_MW, $ts );
2806 break;
2807 case 'localtimestamp':
2808 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
2809 break;
2810 case 'currentversion':
2811 $value = SpecialVersion::getVersion();
2812 break;
2813 case 'articlepath':
2814 return $wgArticlePath;
2815 case 'sitename':
2816 return $wgSitename;
2817 case 'server':
2818 return $wgServer;
2819 case 'servername':
2820 return $wgServerName;
2821 case 'scriptpath':
2822 return $wgScriptPath;
2823 case 'stylepath':
2824 return $wgStylePath;
2825 case 'directionmark':
2826 return $pageLang->getDirMark();
2827 case 'contentlanguage':
2828 global $wgLanguageCode;
2829 return $wgLanguageCode;
2830 case 'pagelanguage':
2831 $value = $pageLang->getCode();
2832 break;
2833 case 'cascadingsources':
2834 $value = CoreParserFunctions::cascadingsources( $this );
2835 break;
2836 default:
2837 $ret = null;
2838 Hooks::run(
2839 'ParserGetVariableValueSwitch',
2840 [ &$parser, &$this->mVarCache, &$index, &$ret, &$frame ]
2841 );
2842
2843 return $ret;
2844 }
2845
2846 if ( $index ) {
2847 $this->mVarCache[$index] = $value;
2848 }
2849
2850 return $value;
2851 }
2852
2853 /**
2854 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2855 *
2856 * @private
2857 */
2858 public function initialiseVariables() {
2859 $variableIDs = MagicWord::getVariableIDs();
2860 $substIDs = MagicWord::getSubstIDs();
2861
2862 $this->mVariables = new MagicWordArray( $variableIDs );
2863 $this->mSubstWords = new MagicWordArray( $substIDs );
2864 }
2865
2866 /**
2867 * Preprocess some wikitext and return the document tree.
2868 * This is the ghost of replace_variables().
2869 *
2870 * @param string $text The text to parse
2871 * @param int $flags Bitwise combination of:
2872 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2873 * included. Default is to assume a direct page view.
2874 *
2875 * The generated DOM tree must depend only on the input text and the flags.
2876 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2877 *
2878 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2879 * change in the DOM tree for a given text, must be passed through the section identifier
2880 * in the section edit link and thus back to extractSections().
2881 *
2882 * The output of this function is currently only cached in process memory, but a persistent
2883 * cache may be implemented at a later date which takes further advantage of these strict
2884 * dependency requirements.
2885 *
2886 * @return PPNode
2887 */
2888 public function preprocessToDom( $text, $flags = 0 ) {
2889 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2890 return $dom;
2891 }
2892
2893 /**
2894 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2895 *
2896 * @param string $s
2897 *
2898 * @return array
2899 */
2900 public static function splitWhitespace( $s ) {
2901 $ltrimmed = ltrim( $s );
2902 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2903 $trimmed = rtrim( $ltrimmed );
2904 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2905 if ( $diff > 0 ) {
2906 $w2 = substr( $ltrimmed, -$diff );
2907 } else {
2908 $w2 = '';
2909 }
2910 return [ $w1, $trimmed, $w2 ];
2911 }
2912
2913 /**
2914 * Replace magic variables, templates, and template arguments
2915 * with the appropriate text. Templates are substituted recursively,
2916 * taking care to avoid infinite loops.
2917 *
2918 * Note that the substitution depends on value of $mOutputType:
2919 * self::OT_WIKI: only {{subst:}} templates
2920 * self::OT_PREPROCESS: templates but not extension tags
2921 * self::OT_HTML: all templates and extension tags
2922 *
2923 * @param string $text The text to transform
2924 * @param bool|PPFrame $frame Object describing the arguments passed to the
2925 * template. Arguments may also be provided as an associative array, as
2926 * was the usual case before MW1.12. Providing arguments this way may be
2927 * useful for extensions wishing to perform variable replacement
2928 * explicitly.
2929 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2930 * double-brace expansion.
2931 * @return string
2932 */
2933 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2934 # Is there any text? Also, Prevent too big inclusions!
2935 $textSize = strlen( $text );
2936 if ( $textSize < 1 || $textSize > $this->mOptions->getMaxIncludeSize() ) {
2937 return $text;
2938 }
2939
2940 if ( $frame === false ) {
2941 $frame = $this->getPreprocessor()->newFrame();
2942 } elseif ( !( $frame instanceof PPFrame ) ) {
2943 wfDebug( __METHOD__ . " called using plain parameters instead of "
2944 . "a PPFrame instance. Creating custom frame.\n" );
2945 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2946 }
2947
2948 $dom = $this->preprocessToDom( $text );
2949 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2950 $text = $frame->expand( $dom, $flags );
2951
2952 return $text;
2953 }
2954
2955 /**
2956 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2957 *
2958 * @param array $args
2959 *
2960 * @return array
2961 */
2962 public static function createAssocArgs( $args ) {
2963 $assocArgs = [];
2964 $index = 1;
2965 foreach ( $args as $arg ) {
2966 $eqpos = strpos( $arg, '=' );
2967 if ( $eqpos === false ) {
2968 $assocArgs[$index++] = $arg;
2969 } else {
2970 $name = trim( substr( $arg, 0, $eqpos ) );
2971 $value = trim( substr( $arg, $eqpos + 1 ) );
2972 if ( $value === false ) {
2973 $value = '';
2974 }
2975 if ( $name !== false ) {
2976 $assocArgs[$name] = $value;
2977 }
2978 }
2979 }
2980
2981 return $assocArgs;
2982 }
2983
2984 /**
2985 * Warn the user when a parser limitation is reached
2986 * Will warn at most once the user per limitation type
2987 *
2988 * The results are shown during preview and run through the Parser (See EditPage.php)
2989 *
2990 * @param string $limitationType Should be one of:
2991 * 'expensive-parserfunction' (corresponding messages:
2992 * 'expensive-parserfunction-warning',
2993 * 'expensive-parserfunction-category')
2994 * 'post-expand-template-argument' (corresponding messages:
2995 * 'post-expand-template-argument-warning',
2996 * 'post-expand-template-argument-category')
2997 * 'post-expand-template-inclusion' (corresponding messages:
2998 * 'post-expand-template-inclusion-warning',
2999 * 'post-expand-template-inclusion-category')
3000 * 'node-count-exceeded' (corresponding messages:
3001 * 'node-count-exceeded-warning',
3002 * 'node-count-exceeded-category')
3003 * 'expansion-depth-exceeded' (corresponding messages:
3004 * 'expansion-depth-exceeded-warning',
3005 * 'expansion-depth-exceeded-category')
3006 * @param string|int|null $current Current value
3007 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3008 * exceeded, provide the values (optional)
3009 */
3010 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3011 # does no harm if $current and $max are present but are unnecessary for the message
3012 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3013 # only during preview, and that would split the parser cache unnecessarily.
3014 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3015 ->text();
3016 $this->mOutput->addWarning( $warning );
3017 $this->addTrackingCategory( "$limitationType-category" );
3018 }
3019
3020 /**
3021 * Return the text of a template, after recursively
3022 * replacing any variables or templates within the template.
3023 *
3024 * @param array $piece The parts of the template
3025 * $piece['title']: the title, i.e. the part before the |
3026 * $piece['parts']: the parameter array
3027 * $piece['lineStart']: whether the brace was at the start of a line
3028 * @param PPFrame $frame The current frame, contains template arguments
3029 * @throws Exception
3030 * @return string The text of the template
3031 */
3032 public function braceSubstitution( $piece, $frame ) {
3033
3034 // Flags
3035
3036 // $text has been filled
3037 $found = false;
3038 // wiki markup in $text should be escaped
3039 $nowiki = false;
3040 // $text is HTML, armour it against wikitext transformation
3041 $isHTML = false;
3042 // Force interwiki transclusion to be done in raw mode not rendered
3043 $forceRawInterwiki = false;
3044 // $text is a DOM node needing expansion in a child frame
3045 $isChildObj = false;
3046 // $text is a DOM node needing expansion in the current frame
3047 $isLocalObj = false;
3048
3049 # Title object, where $text came from
3050 $title = false;
3051
3052 # $part1 is the bit before the first |, and must contain only title characters.
3053 # Various prefixes will be stripped from it later.
3054 $titleWithSpaces = $frame->expand( $piece['title'] );
3055 $part1 = trim( $titleWithSpaces );
3056 $titleText = false;
3057
3058 # Original title text preserved for various purposes
3059 $originalTitle = $part1;
3060
3061 # $args is a list of argument nodes, starting from index 0, not including $part1
3062 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3063 # below won't work b/c this $args isn't an object
3064 $args = ( null == $piece['parts'] ) ? [] : $piece['parts'];
3065
3066 $profileSection = null; // profile templates
3067
3068 # SUBST
3069 if ( !$found ) {
3070 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3071
3072 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3073 # Decide whether to expand template or keep wikitext as-is.
3074 if ( $this->ot['wiki'] ) {
3075 if ( $substMatch === false ) {
3076 $literal = true; # literal when in PST with no prefix
3077 } else {
3078 $literal = false; # expand when in PST with subst: or safesubst:
3079 }
3080 } else {
3081 if ( $substMatch == 'subst' ) {
3082 $literal = true; # literal when not in PST with plain subst:
3083 } else {
3084 $literal = false; # expand when not in PST with safesubst: or no prefix
3085 }
3086 }
3087 if ( $literal ) {
3088 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3089 $isLocalObj = true;
3090 $found = true;
3091 }
3092 }
3093
3094 # Variables
3095 if ( !$found && $args->getLength() == 0 ) {
3096 $id = $this->mVariables->matchStartToEnd( $part1 );
3097 if ( $id !== false ) {
3098 $text = $this->getVariableValue( $id, $frame );
3099 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3100 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3101 }
3102 $found = true;
3103 }
3104 }
3105
3106 # MSG, MSGNW and RAW
3107 if ( !$found ) {
3108 # Check for MSGNW:
3109 $mwMsgnw = MagicWord::get( 'msgnw' );
3110 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3111 $nowiki = true;
3112 } else {
3113 # Remove obsolete MSG:
3114 $mwMsg = MagicWord::get( 'msg' );
3115 $mwMsg->matchStartAndRemove( $part1 );
3116 }
3117
3118 # Check for RAW:
3119 $mwRaw = MagicWord::get( 'raw' );
3120 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3121 $forceRawInterwiki = true;
3122 }
3123 }
3124
3125 # Parser functions
3126 if ( !$found ) {
3127 $colonPos = strpos( $part1, ':' );
3128 if ( $colonPos !== false ) {
3129 $func = substr( $part1, 0, $colonPos );
3130 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3131 $argsLength = $args->getLength();
3132 for ( $i = 0; $i < $argsLength; $i++ ) {
3133 $funcArgs[] = $args->item( $i );
3134 }
3135 try {
3136 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3137 } catch ( Exception $ex ) {
3138 throw $ex;
3139 }
3140
3141 # The interface for parser functions allows for extracting
3142 # flags into the local scope. Extract any forwarded flags
3143 # here.
3144 extract( $result );
3145 }
3146 }
3147
3148 # Finish mangling title and then check for loops.
3149 # Set $title to a Title object and $titleText to the PDBK
3150 if ( !$found ) {
3151 $ns = NS_TEMPLATE;
3152 # Split the title into page and subpage
3153 $subpage = '';
3154 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3155 if ( $part1 !== $relative ) {
3156 $part1 = $relative;
3157 $ns = $this->mTitle->getNamespace();
3158 }
3159 $title = Title::newFromText( $part1, $ns );
3160 if ( $title ) {
3161 $titleText = $title->getPrefixedText();
3162 # Check for language variants if the template is not found
3163 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3164 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3165 }
3166 # Do recursion depth check
3167 $limit = $this->mOptions->getMaxTemplateDepth();
3168 if ( $frame->depth >= $limit ) {
3169 $found = true;
3170 $text = '<span class="error">'
3171 . wfMessage( 'parser-template-recursion-depth-warning' )
3172 ->numParams( $limit )->inContentLanguage()->text()
3173 . '</span>';
3174 }
3175 }
3176 }
3177
3178 # Load from database
3179 if ( !$found && $title ) {
3180 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3181 if ( !$title->isExternal() ) {
3182 if ( $title->isSpecialPage()
3183 && $this->mOptions->getAllowSpecialInclusion()
3184 && $this->ot['html']
3185 ) {
3186 $specialPage = SpecialPageFactory::getPage( $title->getDBkey() );
3187 // Pass the template arguments as URL parameters.
3188 // "uselang" will have no effect since the Language object
3189 // is forced to the one defined in ParserOptions.
3190 $pageArgs = [];
3191 $argsLength = $args->getLength();
3192 for ( $i = 0; $i < $argsLength; $i++ ) {
3193 $bits = $args->item( $i )->splitArg();
3194 if ( strval( $bits['index'] ) === '' ) {
3195 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3196 $value = trim( $frame->expand( $bits['value'] ) );
3197 $pageArgs[$name] = $value;
3198 }
3199 }
3200
3201 // Create a new context to execute the special page
3202 $context = new RequestContext;
3203 $context->setTitle( $title );
3204 $context->setRequest( new FauxRequest( $pageArgs ) );
3205 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3206 $context->setUser( $this->getUser() );
3207 } else {