Merge "Comments, tests, and tweaks for JSON decoding quirks"
[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 MediaWiki\Special\SpecialPageFactory;
26 use Wikimedia\ScopedCallback;
27
28 /**
29 * @defgroup Parser Parser
30 */
31
32 /**
33 * PHP Parser - Processes wiki markup (which uses a more user-friendly
34 * syntax, such as "[[link]]" for making links), and provides a one-way
35 * transformation of that wiki markup it into (X)HTML output / markup
36 * (which in turn the browser understands, and can display).
37 *
38 * There are seven main entry points into the Parser class:
39 *
40 * - Parser::parse()
41 * produces HTML output
42 * - Parser::preSaveTransform()
43 * produces altered wiki markup
44 * - Parser::preprocess()
45 * removes HTML comments and expands templates
46 * - Parser::cleanSig() and Parser::cleanSigInSig()
47 * cleans a signature before saving it to preferences
48 * - Parser::getSection()
49 * return the content of a section from an article for section editing
50 * - Parser::replaceSection()
51 * replaces a section by number inside an article
52 * - Parser::getPreloadText()
53 * removes <noinclude> sections and <includeonly> tags
54 *
55 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
56 *
57 * @par Settings:
58 * $wgNamespacesWithSubpages
59 *
60 * @par Settings only within ParserOptions:
61 * $wgAllowExternalImages
62 * $wgAllowSpecialInclusion
63 * $wgInterwikiMagic
64 * $wgMaxArticleSize
65 *
66 * @ingroup Parser
67 */
68 class Parser {
69 /**
70 * Update this version number when the ParserOutput format
71 * changes in an incompatible way, so the parser cache
72 * can automatically discard old data.
73 */
74 const VERSION = '1.6.4';
75
76 /**
77 * Update this version number when the output of serialiseHalfParsedText()
78 * changes in an incompatible way
79 */
80 const HALF_PARSED_VERSION = 2;
81
82 # Flags for Parser::setFunctionHook
83 const SFH_NO_HASH = 1;
84 const SFH_OBJECT_ARGS = 2;
85
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
90 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
91 # uses to replace invalid HTML characters.
92 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
93 # Simplified expression to match an IPv4 or IPv6 address, or
94 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
95 const EXT_LINK_ADDR = '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
96 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
97 // phpcs:ignore Generic.Files.LineLength
98 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
99 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
100
101 # Regular expression for a non-newline space
102 const SPACE_NOT_NL = '(?:\t|&nbsp;|&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
103
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION = 1;
106
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML = 1; # like parse()
110 const OT_WIKI = 2; # like preSaveTransform()
111 const OT_PREPROCESS = 3; # like preprocess()
112 const OT_MSG = 3;
113 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
114
115 /**
116 * @var string Prefix and suffix for temporary replacement strings
117 * for the multipass parser.
118 *
119 * \x7f should never appear in input as it's disallowed in XML.
120 * Using it at the front also gives us a little extra robustness
121 * since it shouldn't match when butted up against identifier-like
122 * string constructs.
123 *
124 * Must not consist of all title characters, or else it will change
125 * the behavior of <nowiki> in a link.
126 *
127 * Must have a character that needs escaping in attributes, otherwise
128 * someone could put a strip marker in an attribute, to get around
129 * escaping quote marks, and break out of the attribute. Thus we add
130 * `'".
131 */
132 const MARKER_SUFFIX = "-QINU`\"'\x7f";
133 const MARKER_PREFIX = "\x7f'\"`UNIQ-";
134
135 # Markers used for wrapping the table of contents
136 const TOC_START = '<mw:toc>';
137 const TOC_END = '</mw:toc>';
138
139 /** @var int Assume that no output will later be saved this many seconds after parsing */
140 const MAX_TTS = 900;
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 /**
155 * @var bool Whether firstCallInit still needs to be called
156 */
157 public $mFirstCall = true;
158
159 # Initialised by initialiseVariables()
160
161 /**
162 * @var MagicWordArray
163 */
164 public $mVariables;
165
166 /**
167 * @var MagicWordArray
168 */
169 public $mSubstWords;
170 # Initialised in constructor
171 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
172
173 # Initialized in getPreprocessor()
174 /** @var Preprocessor */
175 public $mPreprocessor;
176
177 # Cleared with clearState():
178 /**
179 * @var ParserOutput
180 */
181 public $mOutput;
182 public $mAutonumber;
183
184 /**
185 * @var StripState
186 */
187 public $mStripState;
188
189 public $mIncludeCount;
190 /**
191 * @var LinkHolderArray
192 */
193 public $mLinkHolders;
194
195 public $mLinkID;
196 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
197 public $mDefaultSort;
198 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
199 public $mExpensiveFunctionCount; # number of expensive parser function calls
200 public $mShowToc, $mForceTocPosition;
201
202 /**
203 * @var User
204 */
205 public $mUser; # User object; only used when doing pre-save transform
206
207 # Temporary
208 # These are variables reset at least once per parse regardless of $clearState
209
210 /**
211 * @var ParserOptions
212 */
213 public $mOptions;
214
215 /**
216 * @var Title
217 */
218 public $mTitle; # Title context, used for self-link rendering and similar things
219 public $mOutputType; # Output type, one of the OT_xxx constants
220 public $ot; # Shortcut alias, see setOutputType()
221 public $mRevisionObject; # The revision object of the specified revision ID
222 public $mRevisionId; # ID to display in {{REVISIONID}} tags
223 public $mRevisionTimestamp; # The timestamp of the specified revision ID
224 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
225 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
226 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
227 public $mInputSize = false; # For {{PAGESIZE}} on current page.
228
229 /**
230 * @var string Deprecated accessor for the strip marker prefix.
231 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
232 */
233 public $mUniqPrefix = self::MARKER_PREFIX;
234
235 /**
236 * @var array Array with the language name of each language link (i.e. the
237 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
238 * duplicate language links to the ParserOutput.
239 */
240 public $mLangLinkLanguages;
241
242 /**
243 * @var MapCacheLRU|null
244 * @since 1.24
245 *
246 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
247 */
248 public $currentRevisionCache;
249
250 /**
251 * @var bool|string Recursive call protection.
252 * This variable should be treated as if it were private.
253 */
254 public $mInParse = false;
255
256 /** @var SectionProfiler */
257 protected $mProfiler;
258
259 /**
260 * @var LinkRenderer
261 */
262 protected $mLinkRenderer;
263
264 /** @var MagicWordFactory */
265 private $magicWordFactory;
266
267 /** @var Language */
268 private $contLang;
269
270 /** @var ParserFactory */
271 private $factory;
272
273 /** @var SpecialPageFactory */
274 private $specialPageFactory;
275
276 /** @var Config */
277 private $siteConfig;
278
279 /**
280 * @param array $parserConf See $wgParserConf documentation
281 * @param MagicWordFactory|null $magicWordFactory
282 * @param Language|null $contLang Content language
283 * @param ParserFactory|null $factory
284 * @param string|null $urlProtocols As returned from wfUrlProtocols()
285 * @param SpecialPageFactory|null $spFactory
286 * @param Config|null $siteConfig
287 */
288 public function __construct(
289 array $parserConf = [], MagicWordFactory $magicWordFactory = null,
290 Language $contLang = null, ParserFactory $factory = null, $urlProtocols = null,
291 SpecialPageFactory $spFactory = null, Config $siteConfig = null
292 ) {
293 $this->mConf = $parserConf;
294 $this->mUrlProtocols = $urlProtocols ?? wfUrlProtocols();
295 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
296 self::EXT_LINK_ADDR .
297 self::EXT_LINK_URL_CLASS . '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
298 if ( isset( $parserConf['preprocessorClass'] ) ) {
299 $this->mPreprocessorClass = $parserConf['preprocessorClass'];
300 } elseif ( wfIsHHVM() ) {
301 # Under HHVM Preprocessor_Hash is much faster than Preprocessor_DOM
302 $this->mPreprocessorClass = Preprocessor_Hash::class;
303 } elseif ( extension_loaded( 'domxml' ) ) {
304 # PECL extension that conflicts with the core DOM extension (T15770)
305 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
306 $this->mPreprocessorClass = Preprocessor_Hash::class;
307 } elseif ( extension_loaded( 'dom' ) ) {
308 $this->mPreprocessorClass = Preprocessor_DOM::class;
309 } else {
310 $this->mPreprocessorClass = Preprocessor_Hash::class;
311 }
312 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
313
314 $services = MediaWikiServices::getInstance();
315 $this->magicWordFactory = $magicWordFactory ??
316 $services->getMagicWordFactory();
317
318 $this->contLang = $contLang ?? $services->getContentLanguage();
319
320 $this->factory = $factory ?? $services->getParserFactory();
321 $this->specialPageFactory = $spFactory ?? $services->getSpecialPageFactory();
322 $this->siteConfig = $siteConfig ?? MediaWikiServices::getInstance()->getMainConfig();
323 }
324
325 /**
326 * Reduce memory usage to reduce the impact of circular references
327 */
328 public function __destruct() {
329 if ( isset( $this->mLinkHolders ) ) {
330 unset( $this->mLinkHolders );
331 }
332 foreach ( $this as $name => $value ) {
333 unset( $this->$name );
334 }
335 }
336
337 /**
338 * Allow extensions to clean up when the parser is cloned
339 */
340 public function __clone() {
341 $this->mInParse = false;
342
343 // T58226: When you create a reference "to" an object field, that
344 // makes the object field itself be a reference too (until the other
345 // reference goes out of scope). When cloning, any field that's a
346 // reference is copied as a reference in the new object. Both of these
347 // are defined PHP5 behaviors, as inconvenient as it is for us when old
348 // hooks from PHP4 days are passing fields by reference.
349 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
350 // Make a non-reference copy of the field, then rebind the field to
351 // reference the new copy.
352 $tmp = $this->$k;
353 $this->$k =& $tmp;
354 unset( $tmp );
355 }
356
357 Hooks::run( 'ParserCloned', [ $this ] );
358 }
359
360 /**
361 * Do various kinds of initialisation on the first call of the parser
362 */
363 public function firstCallInit() {
364 if ( !$this->mFirstCall ) {
365 return;
366 }
367 $this->mFirstCall = false;
368
369 CoreParserFunctions::register( $this );
370 CoreTagHooks::register( $this );
371 $this->initialiseVariables();
372
373 // Avoid PHP 7.1 warning from passing $this by reference
374 $parser = $this;
375 Hooks::run( 'ParserFirstCallInit', [ &$parser ] );
376 }
377
378 /**
379 * Clear Parser state
380 *
381 * @private
382 */
383 public function clearState() {
384 $this->firstCallInit();
385 $this->mOutput = new ParserOutput;
386 $this->mOptions->registerWatcher( [ $this->mOutput, 'recordOption' ] );
387 $this->mAutonumber = 0;
388 $this->mIncludeCount = [];
389 $this->mLinkHolders = new LinkHolderArray( $this );
390 $this->mLinkID = 0;
391 $this->mRevisionObject = $this->mRevisionTimestamp =
392 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null;
393 $this->mVarCache = [];
394 $this->mUser = null;
395 $this->mLangLinkLanguages = [];
396 $this->currentRevisionCache = null;
397
398 $this->mStripState = new StripState( $this );
399
400 # Clear these on every parse, T6549
401 $this->mTplRedirCache = $this->mTplDomCache = [];
402
403 $this->mShowToc = true;
404 $this->mForceTocPosition = false;
405 $this->mIncludeSizes = [
406 'post-expand' => 0,
407 'arg' => 0,
408 ];
409 $this->mPPNodeCount = 0;
410 $this->mGeneratedPPNodeCount = 0;
411 $this->mHighestExpansionDepth = 0;
412 $this->mDefaultSort = false;
413 $this->mHeadings = [];
414 $this->mDoubleUnderscores = [];
415 $this->mExpensiveFunctionCount = 0;
416
417 # Fix cloning
418 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
419 $this->mPreprocessor = null;
420 }
421
422 $this->mProfiler = new SectionProfiler();
423
424 // Avoid PHP 7.1 warning from passing $this by reference
425 $parser = $this;
426 Hooks::run( 'ParserClearState', [ &$parser ] );
427 }
428
429 /**
430 * Convert wikitext to HTML
431 * Do not call this function recursively.
432 *
433 * @param string $text Text we want to parse
434 * @param-taint $text escapes_htmlnoent
435 * @param Title $title
436 * @param ParserOptions $options
437 * @param bool $linestart
438 * @param bool $clearState
439 * @param int|null $revid Number to pass in {{REVISIONID}}
440 * @return ParserOutput A ParserOutput
441 * @return-taint escaped
442 */
443 public function parse(
444 $text, Title $title, ParserOptions $options,
445 $linestart = true, $clearState = true, $revid = null
446 ) {
447 if ( $clearState ) {
448 // We use U+007F DELETE to construct strip markers, so we have to make
449 // sure that this character does not occur in the input text.
450 $text = strtr( $text, "\x7f", "?" );
451 $magicScopeVariable = $this->lock();
452 }
453 // Strip U+0000 NULL (T159174)
454 $text = str_replace( "\000", '', $text );
455
456 $this->startParse( $title, $options, self::OT_HTML, $clearState );
457
458 $this->currentRevisionCache = null;
459 $this->mInputSize = strlen( $text );
460 if ( $this->mOptions->getEnableLimitReport() ) {
461 $this->mOutput->resetParseStartTime();
462 }
463
464 $oldRevisionId = $this->mRevisionId;
465 $oldRevisionObject = $this->mRevisionObject;
466 $oldRevisionTimestamp = $this->mRevisionTimestamp;
467 $oldRevisionUser = $this->mRevisionUser;
468 $oldRevisionSize = $this->mRevisionSize;
469 if ( $revid !== null ) {
470 $this->mRevisionId = $revid;
471 $this->mRevisionObject = null;
472 $this->mRevisionTimestamp = null;
473 $this->mRevisionUser = null;
474 $this->mRevisionSize = null;
475 }
476
477 // Avoid PHP 7.1 warning from passing $this by reference
478 $parser = $this;
479 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
480 # No more strip!
481 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
482 $text = $this->internalParse( $text );
483 Hooks::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState ] );
484
485 $text = $this->internalParseHalfParsed( $text, true, $linestart );
486
487 /**
488 * A converted title will be provided in the output object if title and
489 * content conversion are enabled, the article text does not contain
490 * a conversion-suppressing double-underscore tag, and no
491 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
492 * automatic link conversion.
493 */
494 if ( !( $options->getDisableTitleConversion()
495 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
496 || isset( $this->mDoubleUnderscores['notitleconvert'] )
497 || $this->mOutput->getDisplayTitle() !== false )
498 ) {
499 $convruletitle = $this->getTargetLanguage()->getConvRuleTitle();
500 if ( $convruletitle ) {
501 $this->mOutput->setTitleText( $convruletitle );
502 } else {
503 $titleText = $this->getTargetLanguage()->convertTitle( $title );
504 $this->mOutput->setTitleText( $titleText );
505 }
506 }
507
508 # Compute runtime adaptive expiry if set
509 $this->mOutput->finalizeAdaptiveCacheExpiry();
510
511 # Warn if too many heavyweight parser functions were used
512 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
513 $this->limitationWarn( 'expensive-parserfunction',
514 $this->mExpensiveFunctionCount,
515 $this->mOptions->getExpensiveParserFunctionLimit()
516 );
517 }
518
519 # Information on limits, for the benefit of users who try to skirt them
520 if ( $this->mOptions->getEnableLimitReport() ) {
521 $text .= $this->makeLimitReport();
522 }
523
524 # Wrap non-interface parser output in a <div> so it can be targeted
525 # with CSS (T37247)
526 $class = $this->mOptions->getWrapOutputClass();
527 if ( $class !== false && !$this->mOptions->getInterfaceMessage() ) {
528 $this->mOutput->addWrapperDivClass( $class );
529 }
530
531 $this->mOutput->setText( $text );
532
533 $this->mRevisionId = $oldRevisionId;
534 $this->mRevisionObject = $oldRevisionObject;
535 $this->mRevisionTimestamp = $oldRevisionTimestamp;
536 $this->mRevisionUser = $oldRevisionUser;
537 $this->mRevisionSize = $oldRevisionSize;
538 $this->mInputSize = false;
539 $this->currentRevisionCache = null;
540
541 return $this->mOutput;
542 }
543
544 /**
545 * Set the limit report data in the current ParserOutput, and return the
546 * limit report HTML comment.
547 *
548 * @return string
549 */
550 protected function makeLimitReport() {
551 $maxIncludeSize = $this->mOptions->getMaxIncludeSize();
552
553 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' );
554 if ( $cpuTime !== null ) {
555 $this->mOutput->setLimitReportData( 'limitreport-cputime',
556 sprintf( "%.3f", $cpuTime )
557 );
558 }
559
560 $wallTime = $this->mOutput->getTimeSinceStart( 'wall' );
561 $this->mOutput->setLimitReportData( 'limitreport-walltime',
562 sprintf( "%.3f", $wallTime )
563 );
564
565 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes',
566 [ $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() ]
567 );
568 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes',
569 [ $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() ]
570 );
571 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize',
572 [ $this->mIncludeSizes['post-expand'], $maxIncludeSize ]
573 );
574 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize',
575 [ $this->mIncludeSizes['arg'], $maxIncludeSize ]
576 );
577 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth',
578 [ $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() ]
579 );
580 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount',
581 [ $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() ]
582 );
583
584 foreach ( $this->mStripState->getLimitReport() as list( $key, $value ) ) {
585 $this->mOutput->setLimitReportData( $key, $value );
586 }
587
588 Hooks::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput ] );
589
590 $limitReport = "NewPP limit report\n";
591 if ( $this->siteConfig->get( 'ShowHostnames' ) ) {
592 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
593 }
594 $limitReport .= 'Cached time: ' . $this->mOutput->getCacheTime() . "\n";
595 $limitReport .= 'Cache expiry: ' . $this->mOutput->getCacheExpiry() . "\n";
596 $limitReport .= 'Dynamic content: ' .
597 ( $this->mOutput->hasDynamicContent() ? 'true' : 'false' ) .
598 "\n";
599
600 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
601 if ( Hooks::run( 'ParserLimitReportFormat',
602 [ $key, &$value, &$limitReport, false, false ]
603 ) ) {
604 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
605 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
606 ->inLanguage( 'en' )->useDatabase( false );
607 if ( !$valueMsg->exists() ) {
608 $valueMsg = new RawMessage( '$1' );
609 }
610 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
611 $valueMsg->params( $value );
612 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
613 }
614 }
615 }
616 // Since we're not really outputting HTML, decode the entities and
617 // then re-encode the things that need hiding inside HTML comments.
618 $limitReport = htmlspecialchars_decode( $limitReport );
619
620 // Sanitize for comment. Note '‐' in the replacement is U+2010,
621 // which looks much like the problematic '-'.
622 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&amp;' ], $limitReport );
623 $text = "\n<!-- \n$limitReport-->\n";
624
625 // Add on template profiling data in human/machine readable way
626 $dataByFunc = $this->mProfiler->getFunctionStats();
627 uasort( $dataByFunc, function ( $a, $b ) {
628 return $b['real'] <=> $a['real']; // descending order
629 } );
630 $profileReport = [];
631 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
632 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
633 $item['%real'], $item['real'], $item['calls'],
634 htmlspecialchars( $item['name'] ) );
635 }
636 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
637 $text .= implode( "\n", $profileReport ) . "\n-->\n";
638
639 $this->mOutput->setLimitReportData( 'limitreport-timingprofile', $profileReport );
640
641 // Add other cache related metadata
642 if ( $this->siteConfig->get( 'ShowHostnames' ) ) {
643 $this->mOutput->setLimitReportData( 'cachereport-origin', wfHostname() );
644 }
645 $this->mOutput->setLimitReportData( 'cachereport-timestamp',
646 $this->mOutput->getCacheTime() );
647 $this->mOutput->setLimitReportData( 'cachereport-ttl',
648 $this->mOutput->getCacheExpiry() );
649 $this->mOutput->setLimitReportData( 'cachereport-transientcontent',
650 $this->mOutput->hasDynamicContent() );
651
652 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
653 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
654 $this->mTitle->getPrefixedDBkey() );
655 }
656 return $text;
657 }
658
659 /**
660 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
661 * can be called from an extension tag hook.
662 *
663 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
664 * instead, which means that lists and links have not been fully parsed yet,
665 * and strip markers are still present.
666 *
667 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
668 *
669 * Use this function if you're a parser tag hook and you want to parse
670 * wikitext before or after applying additional transformations, and you
671 * intend to *return the result as hook output*, which will cause it to go
672 * through the rest of parsing process automatically.
673 *
674 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
675 * $text are not expanded
676 *
677 * @param string $text Text extension wants to have parsed
678 * @param-taint $text escapes_htmlnoent
679 * @param bool|PPFrame $frame The frame to use for expanding any template variables
680 * @return string UNSAFE half-parsed HTML
681 * @return-taint escaped
682 */
683 public function recursiveTagParse( $text, $frame = false ) {
684 // Avoid PHP 7.1 warning from passing $this by reference
685 $parser = $this;
686 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
687 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
688 $text = $this->internalParse( $text, false, $frame );
689 return $text;
690 }
691
692 /**
693 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
694 * point can be called from an extension tag hook.
695 *
696 * The output of this function is fully-parsed HTML that is safe for output.
697 * If you're a parser tag hook, you might want to use recursiveTagParse()
698 * instead.
699 *
700 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
701 * $text are not expanded
702 *
703 * @since 1.25
704 *
705 * @param string $text Text extension wants to have parsed
706 * @param-taint $text escapes_htmlnoent
707 * @param bool|PPFrame $frame The frame to use for expanding any template variables
708 * @return string Fully parsed HTML
709 * @return-taint escaped
710 */
711 public function recursiveTagParseFully( $text, $frame = false ) {
712 $text = $this->recursiveTagParse( $text, $frame );
713 $text = $this->internalParseHalfParsed( $text, false );
714 return $text;
715 }
716
717 /**
718 * Expand templates and variables in the text, producing valid, static wikitext.
719 * Also removes comments.
720 * Do not call this function recursively.
721 * @param string $text
722 * @param Title|null $title
723 * @param ParserOptions $options
724 * @param int|null $revid
725 * @param bool|PPFrame $frame
726 * @return mixed|string
727 */
728 public function preprocess( $text, Title $title = null,
729 ParserOptions $options, $revid = null, $frame = false
730 ) {
731 $magicScopeVariable = $this->lock();
732 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
733 if ( $revid !== null ) {
734 $this->mRevisionId = $revid;
735 }
736 // Avoid PHP 7.1 warning from passing $this by reference
737 $parser = $this;
738 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
739 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
740 $text = $this->replaceVariables( $text, $frame );
741 $text = $this->mStripState->unstripBoth( $text );
742 return $text;
743 }
744
745 /**
746 * Recursive parser entry point that can be called from an extension tag
747 * hook.
748 *
749 * @param string $text Text to be expanded
750 * @param bool|PPFrame $frame The frame to use for expanding any template variables
751 * @return string
752 * @since 1.19
753 */
754 public function recursivePreprocess( $text, $frame = false ) {
755 $text = $this->replaceVariables( $text, $frame );
756 $text = $this->mStripState->unstripBoth( $text );
757 return $text;
758 }
759
760 /**
761 * Process the wikitext for the "?preload=" feature. (T7210)
762 *
763 * "<noinclude>", "<includeonly>" etc. are parsed as for template
764 * transclusion, comments, templates, arguments, tags hooks and parser
765 * functions are untouched.
766 *
767 * @param string $text
768 * @param Title $title
769 * @param ParserOptions $options
770 * @param array $params
771 * @return string
772 */
773 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = [] ) {
774 $msg = new RawMessage( $text );
775 $text = $msg->params( $params )->plain();
776
777 # Parser (re)initialisation
778 $magicScopeVariable = $this->lock();
779 $this->startParse( $title, $options, self::OT_PLAIN, true );
780
781 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
782 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
783 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
784 $text = $this->mStripState->unstripBoth( $text );
785 return $text;
786 }
787
788 /**
789 * Set the current user.
790 * Should only be used when doing pre-save transform.
791 *
792 * @param User|null $user User object or null (to reset)
793 */
794 public function setUser( $user ) {
795 $this->mUser = $user;
796 }
797
798 /**
799 * Set the context title
800 *
801 * @param Title $t
802 */
803 public function setTitle( $t ) {
804 if ( !$t ) {
805 $t = Title::newFromText( 'NO TITLE' );
806 }
807
808 if ( $t->hasFragment() ) {
809 # Strip the fragment to avoid various odd effects
810 $this->mTitle = $t->createFragmentTarget( '' );
811 } else {
812 $this->mTitle = $t;
813 }
814 }
815
816 /**
817 * Accessor for the Title object
818 *
819 * @return Title
820 */
821 public function getTitle() {
822 return $this->mTitle;
823 }
824
825 /**
826 * Accessor/mutator for the Title object
827 *
828 * @param Title|null $x Title object or null to just get the current one
829 * @return Title
830 */
831 public function Title( $x = null ) {
832 return wfSetVar( $this->mTitle, $x );
833 }
834
835 /**
836 * Set the output type
837 *
838 * @param int $ot New value
839 */
840 public function setOutputType( $ot ) {
841 $this->mOutputType = $ot;
842 # Shortcut alias
843 $this->ot = [
844 'html' => $ot == self::OT_HTML,
845 'wiki' => $ot == self::OT_WIKI,
846 'pre' => $ot == self::OT_PREPROCESS,
847 'plain' => $ot == self::OT_PLAIN,
848 ];
849 }
850
851 /**
852 * Accessor/mutator for the output type
853 *
854 * @param int|null $x New value or null to just get the current one
855 * @return int
856 */
857 public function OutputType( $x = null ) {
858 return wfSetVar( $this->mOutputType, $x );
859 }
860
861 /**
862 * Get the ParserOutput object
863 *
864 * @return ParserOutput
865 */
866 public function getOutput() {
867 return $this->mOutput;
868 }
869
870 /**
871 * Get the ParserOptions object
872 *
873 * @return ParserOptions
874 */
875 public function getOptions() {
876 return $this->mOptions;
877 }
878
879 /**
880 * Accessor/mutator for the ParserOptions object
881 *
882 * @param ParserOptions|null $x New value or null to just get the current one
883 * @return ParserOptions Current ParserOptions object
884 */
885 public function Options( $x = null ) {
886 return wfSetVar( $this->mOptions, $x );
887 }
888
889 /**
890 * @return int
891 */
892 public function nextLinkID() {
893 return $this->mLinkID++;
894 }
895
896 /**
897 * @param int $id
898 */
899 public function setLinkID( $id ) {
900 $this->mLinkID = $id;
901 }
902
903 /**
904 * Get a language object for use in parser functions such as {{FORMATNUM:}}
905 * @return Language
906 */
907 public function getFunctionLang() {
908 return $this->getTargetLanguage();
909 }
910
911 /**
912 * Get the target language for the content being parsed. This is usually the
913 * language that the content is in.
914 *
915 * @since 1.19
916 *
917 * @throws MWException
918 * @return Language
919 */
920 public function getTargetLanguage() {
921 $target = $this->mOptions->getTargetLanguage();
922
923 if ( $target !== null ) {
924 return $target;
925 } elseif ( $this->mOptions->getInterfaceMessage() ) {
926 return $this->mOptions->getUserLangObj();
927 } elseif ( is_null( $this->mTitle ) ) {
928 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
929 }
930
931 return $this->mTitle->getPageLanguage();
932 }
933
934 /**
935 * Get the language object for language conversion
936 * @deprecated since 1.32, just use getTargetLanguage()
937 * @return Language|null
938 */
939 public function getConverterLanguage() {
940 return $this->getTargetLanguage();
941 }
942
943 /**
944 * Get a User object either from $this->mUser, if set, or from the
945 * ParserOptions object otherwise
946 *
947 * @return User
948 */
949 public function getUser() {
950 if ( !is_null( $this->mUser ) ) {
951 return $this->mUser;
952 }
953 return $this->mOptions->getUser();
954 }
955
956 /**
957 * Get a preprocessor object
958 *
959 * @return Preprocessor
960 */
961 public function getPreprocessor() {
962 if ( !isset( $this->mPreprocessor ) ) {
963 $class = $this->mPreprocessorClass;
964 $this->mPreprocessor = new $class( $this );
965 }
966 return $this->mPreprocessor;
967 }
968
969 /**
970 * Get a LinkRenderer instance to make links with
971 *
972 * @since 1.28
973 * @return LinkRenderer
974 */
975 public function getLinkRenderer() {
976 if ( !$this->mLinkRenderer ) {
977 $this->mLinkRenderer = MediaWikiServices::getInstance()
978 ->getLinkRendererFactory()->create();
979 $this->mLinkRenderer->setStubThreshold(
980 $this->getOptions()->getStubThreshold()
981 );
982 }
983
984 return $this->mLinkRenderer;
985 }
986
987 /**
988 * Get the MagicWordFactory that this Parser is using
989 *
990 * @since 1.32
991 * @return MagicWordFactory
992 */
993 public function getMagicWordFactory() {
994 return $this->magicWordFactory;
995 }
996
997 /**
998 * Get the content language that this Parser is using
999 *
1000 * @since 1.32
1001 * @return Language
1002 */
1003 public function getContentLanguage() {
1004 return $this->contLang;
1005 }
1006
1007 /**
1008 * Replaces all occurrences of HTML-style comments and the given tags
1009 * in the text with a random marker and returns the next text. The output
1010 * parameter $matches will be an associative array filled with data in
1011 * the form:
1012 *
1013 * @code
1014 * 'UNIQ-xxxxx' => [
1015 * 'element',
1016 * 'tag content',
1017 * [ 'param' => 'x' ],
1018 * '<element param="x">tag content</element>' ]
1019 * @endcode
1020 *
1021 * @param array $elements List of element names. Comments are always extracted.
1022 * @param string $text Source text string.
1023 * @param array &$matches Out parameter, Array: extracted tags
1024 * @return string Stripped text
1025 */
1026 public static function extractTagsAndParams( $elements, $text, &$matches ) {
1027 static $n = 1;
1028 $stripped = '';
1029 $matches = [];
1030
1031 $taglist = implode( '|', $elements );
1032 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
1033
1034 while ( $text != '' ) {
1035 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
1036 $stripped .= $p[0];
1037 if ( count( $p ) < 5 ) {
1038 break;
1039 }
1040 if ( count( $p ) > 5 ) {
1041 # comment
1042 $element = $p[4];
1043 $attributes = '';
1044 $close = '';
1045 $inside = $p[5];
1046 } else {
1047 # tag
1048 $element = $p[1];
1049 $attributes = $p[2];
1050 $close = $p[3];
1051 $inside = $p[4];
1052 }
1053
1054 $marker = self::MARKER_PREFIX . "-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
1055 $stripped .= $marker;
1056
1057 if ( $close === '/>' ) {
1058 # Empty element tag, <tag />
1059 $content = null;
1060 $text = $inside;
1061 $tail = null;
1062 } else {
1063 if ( $element === '!--' ) {
1064 $end = '/(-->)/';
1065 } else {
1066 $end = "/(<\\/$element\\s*>)/i";
1067 }
1068 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
1069 $content = $q[0];
1070 if ( count( $q ) < 3 ) {
1071 # No end tag -- let it run out to the end of the text.
1072 $tail = '';
1073 $text = '';
1074 } else {
1075 $tail = $q[1];
1076 $text = $q[2];
1077 }
1078 }
1079
1080 $matches[$marker] = [ $element,
1081 $content,
1082 Sanitizer::decodeTagAttributes( $attributes ),
1083 "<$element$attributes$close$content$tail" ];
1084 }
1085 return $stripped;
1086 }
1087
1088 /**
1089 * Get a list of strippable XML-like elements
1090 *
1091 * @return array
1092 */
1093 public function getStripList() {
1094 return $this->mStripList;
1095 }
1096
1097 /**
1098 * Add an item to the strip state
1099 * Returns the unique tag which must be inserted into the stripped text
1100 * The tag will be replaced with the original text in unstrip()
1101 *
1102 * @param string $text
1103 *
1104 * @return string
1105 */
1106 public function insertStripItem( $text ) {
1107 $marker = self::MARKER_PREFIX . "-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
1108 $this->mMarkerIndex++;
1109 $this->mStripState->addGeneral( $marker, $text );
1110 return $marker;
1111 }
1112
1113 /**
1114 * parse the wiki syntax used to render tables
1115 *
1116 * @private
1117 * @param string $text
1118 * @return string
1119 */
1120 public function doTableStuff( $text ) {
1121 $lines = StringUtils::explode( "\n", $text );
1122 $out = '';
1123 $td_history = []; # Is currently a td tag open?
1124 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1125 $tr_history = []; # Is currently a tr tag open?
1126 $tr_attributes = []; # history of tr attributes
1127 $has_opened_tr = []; # Did this table open a <tr> element?
1128 $indent_level = 0; # indent level of the table
1129
1130 foreach ( $lines as $outLine ) {
1131 $line = trim( $outLine );
1132
1133 if ( $line === '' ) { # empty line, go to next line
1134 $out .= $outLine . "\n";
1135 continue;
1136 }
1137
1138 $first_character = $line[0];
1139 $first_two = substr( $line, 0, 2 );
1140 $matches = [];
1141
1142 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1143 # First check if we are starting a new table
1144 $indent_level = strlen( $matches[1] );
1145
1146 $attributes = $this->mStripState->unstripBoth( $matches[2] );
1147 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
1148
1149 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1150 array_push( $td_history, false );
1151 array_push( $last_tag_history, '' );
1152 array_push( $tr_history, false );
1153 array_push( $tr_attributes, '' );
1154 array_push( $has_opened_tr, false );
1155 } elseif ( count( $td_history ) == 0 ) {
1156 # Don't do any of the following
1157 $out .= $outLine . "\n";
1158 continue;
1159 } elseif ( $first_two === '|}' ) {
1160 # We are ending a table
1161 $line = '</table>' . substr( $line, 2 );
1162 $last_tag = array_pop( $last_tag_history );
1163
1164 if ( !array_pop( $has_opened_tr ) ) {
1165 $line = "<tr><td></td></tr>{$line}";
1166 }
1167
1168 if ( array_pop( $tr_history ) ) {
1169 $line = "</tr>{$line}";
1170 }
1171
1172 if ( array_pop( $td_history ) ) {
1173 $line = "</{$last_tag}>{$line}";
1174 }
1175 array_pop( $tr_attributes );
1176 if ( $indent_level > 0 ) {
1177 $outLine = rtrim( $line ) . str_repeat( '</dd></dl>', $indent_level );
1178 } else {
1179 $outLine = $line;
1180 }
1181 } elseif ( $first_two === '|-' ) {
1182 # Now we have a table row
1183 $line = preg_replace( '#^\|-+#', '', $line );
1184
1185 # Whats after the tag is now only attributes
1186 $attributes = $this->mStripState->unstripBoth( $line );
1187 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
1188 array_pop( $tr_attributes );
1189 array_push( $tr_attributes, $attributes );
1190
1191 $line = '';
1192 $last_tag = array_pop( $last_tag_history );
1193 array_pop( $has_opened_tr );
1194 array_push( $has_opened_tr, true );
1195
1196 if ( array_pop( $tr_history ) ) {
1197 $line = '</tr>';
1198 }
1199
1200 if ( array_pop( $td_history ) ) {
1201 $line = "</{$last_tag}>{$line}";
1202 }
1203
1204 $outLine = $line;
1205 array_push( $tr_history, false );
1206 array_push( $td_history, false );
1207 array_push( $last_tag_history, '' );
1208 } elseif ( $first_character === '|'
1209 || $first_character === '!'
1210 || $first_two === '|+'
1211 ) {
1212 # This might be cell elements, td, th or captions
1213 if ( $first_two === '|+' ) {
1214 $first_character = '+';
1215 $line = substr( $line, 2 );
1216 } else {
1217 $line = substr( $line, 1 );
1218 }
1219
1220 // Implies both are valid for table headings.
1221 if ( $first_character === '!' ) {
1222 $line = StringUtils::replaceMarkup( '!!', '||', $line );
1223 }
1224
1225 # Split up multiple cells on the same line.
1226 # FIXME : This can result in improper nesting of tags processed
1227 # by earlier parser steps.
1228 $cells = explode( '||', $line );
1229
1230 $outLine = '';
1231
1232 # Loop through each table cell
1233 foreach ( $cells as $cell ) {
1234 $previous = '';
1235 if ( $first_character !== '+' ) {
1236 $tr_after = array_pop( $tr_attributes );
1237 if ( !array_pop( $tr_history ) ) {
1238 $previous = "<tr{$tr_after}>\n";
1239 }
1240 array_push( $tr_history, true );
1241 array_push( $tr_attributes, '' );
1242 array_pop( $has_opened_tr );
1243 array_push( $has_opened_tr, true );
1244 }
1245
1246 $last_tag = array_pop( $last_tag_history );
1247
1248 if ( array_pop( $td_history ) ) {
1249 $previous = "</{$last_tag}>\n{$previous}";
1250 }
1251
1252 if ( $first_character === '|' ) {
1253 $last_tag = 'td';
1254 } elseif ( $first_character === '!' ) {
1255 $last_tag = 'th';
1256 } elseif ( $first_character === '+' ) {
1257 $last_tag = 'caption';
1258 } else {
1259 $last_tag = '';
1260 }
1261
1262 array_push( $last_tag_history, $last_tag );
1263
1264 # A cell could contain both parameters and data
1265 $cell_data = explode( '|', $cell, 2 );
1266
1267 # T2553: Note that a '|' inside an invalid link should not
1268 # be mistaken as delimiting cell parameters
1269 # Bug T153140: Neither should language converter markup.
1270 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1271 $cell = "{$previous}<{$last_tag}>" . trim( $cell );
1272 } elseif ( count( $cell_data ) == 1 ) {
1273 // Whitespace in cells is trimmed
1274 $cell = "{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1275 } else {
1276 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1277 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1278 // Whitespace in cells is trimmed
1279 $cell = "{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1280 }
1281
1282 $outLine .= $cell;
1283 array_push( $td_history, true );
1284 }
1285 }
1286 $out .= $outLine . "\n";
1287 }
1288
1289 # Closing open td, tr && table
1290 while ( count( $td_history ) > 0 ) {
1291 if ( array_pop( $td_history ) ) {
1292 $out .= "</td>\n";
1293 }
1294 if ( array_pop( $tr_history ) ) {
1295 $out .= "</tr>\n";
1296 }
1297 if ( !array_pop( $has_opened_tr ) ) {
1298 $out .= "<tr><td></td></tr>\n";
1299 }
1300
1301 $out .= "</table>\n";
1302 }
1303
1304 # Remove trailing line-ending (b/c)
1305 if ( substr( $out, -1 ) === "\n" ) {
1306 $out = substr( $out, 0, -1 );
1307 }
1308
1309 # special case: don't return empty table
1310 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1311 $out = '';
1312 }
1313
1314 return $out;
1315 }
1316
1317 /**
1318 * Helper function for parse() that transforms wiki markup into half-parsed
1319 * HTML. Only called for $mOutputType == self::OT_HTML.
1320 *
1321 * @private
1322 *
1323 * @param string $text The text to parse
1324 * @param-taint $text escapes_html
1325 * @param bool $isMain Whether this is being called from the main parse() function
1326 * @param PPFrame|bool $frame A pre-processor frame
1327 *
1328 * @return string
1329 */
1330 public function internalParse( $text, $isMain = true, $frame = false ) {
1331 $origText = $text;
1332
1333 // Avoid PHP 7.1 warning from passing $this by reference
1334 $parser = $this;
1335
1336 # Hook to suspend the parser in this state
1337 if ( !Hooks::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState ] ) ) {
1338 return $text;
1339 }
1340
1341 # if $frame is provided, then use $frame for replacing any variables
1342 if ( $frame ) {
1343 # use frame depth to infer how include/noinclude tags should be handled
1344 # depth=0 means this is the top-level document; otherwise it's an included document
1345 if ( !$frame->depth ) {
1346 $flag = 0;
1347 } else {
1348 $flag = self::PTD_FOR_INCLUSION;
1349 }
1350 $dom = $this->preprocessToDom( $text, $flag );
1351 $text = $frame->expand( $dom );
1352 } else {
1353 # if $frame is not provided, then use old-style replaceVariables
1354 $text = $this->replaceVariables( $text );
1355 }
1356
1357 Hooks::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState ] );
1358 $text = Sanitizer::removeHTMLtags(
1359 $text,
1360 [ $this, 'attributeStripCallback' ],
1361 false,
1362 array_keys( $this->mTransparentTagHooks ),
1363 [],
1364 [ $this, 'addTrackingCategory' ]
1365 );
1366 Hooks::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState ] );
1367
1368 # Tables need to come after variable replacement for things to work
1369 # properly; putting them before other transformations should keep
1370 # exciting things like link expansions from showing up in surprising
1371 # places.
1372 $text = $this->doTableStuff( $text );
1373
1374 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1375
1376 $text = $this->doDoubleUnderscore( $text );
1377
1378 $text = $this->doHeadings( $text );
1379 $text = $this->replaceInternalLinks( $text );
1380 $text = $this->doAllQuotes( $text );
1381 $text = $this->replaceExternalLinks( $text );
1382
1383 # replaceInternalLinks may sometimes leave behind
1384 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1385 $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text );
1386
1387 $text = $this->doMagicLinks( $text );
1388 $text = $this->formatHeadings( $text, $origText, $isMain );
1389
1390 return $text;
1391 }
1392
1393 /**
1394 * Helper function for parse() that transforms half-parsed HTML into fully
1395 * parsed HTML.
1396 *
1397 * @param string $text
1398 * @param bool $isMain
1399 * @param bool $linestart
1400 * @return string
1401 */
1402 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1403 $text = $this->mStripState->unstripGeneral( $text );
1404
1405 // Avoid PHP 7.1 warning from passing $this by reference
1406 $parser = $this;
1407
1408 if ( $isMain ) {
1409 Hooks::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1410 }
1411
1412 # Clean up special characters, only run once, next-to-last before doBlockLevels
1413 $text = Sanitizer::armorFrenchSpaces( $text );
1414
1415 $text = $this->doBlockLevels( $text, $linestart );
1416
1417 $this->replaceLinkHolders( $text );
1418
1419 /**
1420 * The input doesn't get language converted if
1421 * a) It's disabled
1422 * b) Content isn't converted
1423 * c) It's a conversion table
1424 * d) it is an interface message (which is in the user language)
1425 */
1426 if ( !( $this->mOptions->getDisableContentConversion()
1427 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
1428 ) {
1429 if ( !$this->mOptions->getInterfaceMessage() ) {
1430 # The position of the convert() call should not be changed. it
1431 # assumes that the links are all replaced and the only thing left
1432 # is the <nowiki> mark.
1433 $text = $this->getTargetLanguage()->convert( $text );
1434 }
1435 }
1436
1437 $text = $this->mStripState->unstripNoWiki( $text );
1438
1439 if ( $isMain ) {
1440 Hooks::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1441 }
1442
1443 $text = $this->replaceTransparentTags( $text );
1444 $text = $this->mStripState->unstripGeneral( $text );
1445
1446 $text = Sanitizer::normalizeCharReferences( $text );
1447
1448 if ( MWTidy::isEnabled() ) {
1449 if ( $this->mOptions->getTidy() ) {
1450 $text = MWTidy::tidy( $text );
1451 }
1452 } else {
1453 # attempt to sanitize at least some nesting problems
1454 # (T4702 and quite a few others)
1455 $tidyregs = [
1456 # ''Something [http://www.cool.com cool''] -->
1457 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1458 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1459 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1460 # fix up an anchor inside another anchor, only
1461 # at least for a single single nested link (T5695)
1462 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1463 '\\1\\2</a>\\3</a>\\1\\4</a>',
1464 # fix div inside inline elements- doBlockLevels won't wrap a line which
1465 # contains a div, so fix it up here; replace
1466 # div with escaped text
1467 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1468 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
1469 # remove empty italic or bold tag pairs, some
1470 # introduced by rules above
1471 '/<([bi])><\/\\1>/' => '',
1472 ];
1473
1474 $text = preg_replace(
1475 array_keys( $tidyregs ),
1476 array_values( $tidyregs ),
1477 $text );
1478 }
1479
1480 if ( $isMain ) {
1481 Hooks::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1482 }
1483
1484 return $text;
1485 }
1486
1487 /**
1488 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1489 * magic external links.
1490 *
1491 * DML
1492 * @private
1493 *
1494 * @param string $text
1495 *
1496 * @return string
1497 */
1498 public function doMagicLinks( $text ) {
1499 $prots = wfUrlProtocolsWithoutProtRel();
1500 $urlChar = self::EXT_LINK_URL_CLASS;
1501 $addr = self::EXT_LINK_ADDR;
1502 $space = self::SPACE_NOT_NL; # non-newline space
1503 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1504 $spaces = "$space++"; # possessive match of 1 or more spaces
1505 $text = preg_replace_callback(
1506 '!(?: # Start cases
1507 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1508 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1509 (\b # m[3]: Free external links
1510 (?i:$prots)
1511 ($addr$urlChar*) # m[4]: Post-protocol path
1512 ) |
1513 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1514 ([0-9]+)\b |
1515 \bISBN $spaces ( # m[6]: ISBN, capture number
1516 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1517 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1518 [0-9Xx] # check digit
1519 )\b
1520 )!xu", [ $this, 'magicLinkCallback' ], $text );
1521 return $text;
1522 }
1523
1524 /**
1525 * @throws MWException
1526 * @param array $m
1527 * @return string HTML
1528 */
1529 public function magicLinkCallback( $m ) {
1530 if ( isset( $m[1] ) && $m[1] !== '' ) {
1531 # Skip anchor
1532 return $m[0];
1533 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1534 # Skip HTML element
1535 return $m[0];
1536 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1537 # Free external link
1538 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1539 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1540 # RFC or PMID
1541 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1542 if ( !$this->mOptions->getMagicRFCLinks() ) {
1543 return $m[0];
1544 }
1545 $keyword = 'RFC';
1546 $urlmsg = 'rfcurl';
1547 $cssClass = 'mw-magiclink-rfc';
1548 $trackingCat = 'magiclink-tracking-rfc';
1549 $id = $m[5];
1550 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1551 if ( !$this->mOptions->getMagicPMIDLinks() ) {
1552 return $m[0];
1553 }
1554 $keyword = 'PMID';
1555 $urlmsg = 'pubmedurl';
1556 $cssClass = 'mw-magiclink-pmid';
1557 $trackingCat = 'magiclink-tracking-pmid';
1558 $id = $m[5];
1559 } else {
1560 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1561 substr( $m[0], 0, 20 ) . '"' );
1562 }
1563 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1564 $this->addTrackingCategory( $trackingCat );
1565 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle );
1566 } elseif ( isset( $m[6] ) && $m[6] !== ''
1567 && $this->mOptions->getMagicISBNLinks()
1568 ) {
1569 # ISBN
1570 $isbn = $m[6];
1571 $space = self::SPACE_NOT_NL; # non-newline space
1572 $isbn = preg_replace( "/$space/", ' ', $isbn );
1573 $num = strtr( $isbn, [
1574 '-' => '',
1575 ' ' => '',
1576 'x' => 'X',
1577 ] );
1578 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1579 return $this->getLinkRenderer()->makeKnownLink(
1580 SpecialPage::getTitleFor( 'Booksources', $num ),
1581 "ISBN $isbn",
1582 [
1583 'class' => 'internal mw-magiclink-isbn',
1584 'title' => false // suppress title attribute
1585 ]
1586 );
1587 } else {
1588 return $m[0];
1589 }
1590 }
1591
1592 /**
1593 * Make a free external link, given a user-supplied URL
1594 *
1595 * @param string $url
1596 * @param int $numPostProto
1597 * The number of characters after the protocol.
1598 * @return string HTML
1599 * @private
1600 */
1601 public function makeFreeExternalLink( $url, $numPostProto ) {
1602 $trail = '';
1603
1604 # The characters '<' and '>' (which were escaped by
1605 # removeHTMLtags()) should not be included in
1606 # URLs, per RFC 2396.
1607 # Make &nbsp; terminate a URL as well (bug T84937)
1608 $m2 = [];
1609 if ( preg_match(
1610 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1611 $url,
1612 $m2,
1613 PREG_OFFSET_CAPTURE
1614 ) ) {
1615 $trail = substr( $url, $m2[0][1] ) . $trail;
1616 $url = substr( $url, 0, $m2[0][1] );
1617 }
1618
1619 # Move trailing punctuation to $trail
1620 $sep = ',;\.:!?';
1621 # If there is no left bracket, then consider right brackets fair game too
1622 if ( strpos( $url, '(' ) === false ) {
1623 $sep .= ')';
1624 }
1625
1626 $urlRev = strrev( $url );
1627 $numSepChars = strspn( $urlRev, $sep );
1628 # Don't break a trailing HTML entity by moving the ; into $trail
1629 # This is in hot code, so use substr_compare to avoid having to
1630 # create a new string object for the comparison
1631 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1632 # more optimization: instead of running preg_match with a $
1633 # anchor, which can be slow, do the match on the reversed
1634 # string starting at the desired offset.
1635 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1636 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1637 $numSepChars--;
1638 }
1639 }
1640 if ( $numSepChars ) {
1641 $trail = substr( $url, -$numSepChars ) . $trail;
1642 $url = substr( $url, 0, -$numSepChars );
1643 }
1644
1645 # Verify that we still have a real URL after trail removal, and
1646 # not just lone protocol
1647 if ( strlen( $trail ) >= $numPostProto ) {
1648 return $url . $trail;
1649 }
1650
1651 $url = Sanitizer::cleanUrl( $url );
1652
1653 # Is this an external image?
1654 $text = $this->maybeMakeExternalImage( $url );
1655 if ( $text === false ) {
1656 # Not an image, make a link
1657 $text = Linker::makeExternalLink( $url,
1658 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1659 true, 'free',
1660 $this->getExternalLinkAttribs( $url ), $this->mTitle );
1661 # Register it in the output object...
1662 $this->mOutput->addExternalLink( $url );
1663 }
1664 return $text . $trail;
1665 }
1666
1667 /**
1668 * Parse headers and return html
1669 *
1670 * @private
1671 *
1672 * @param string $text
1673 *
1674 * @return string
1675 */
1676 public function doHeadings( $text ) {
1677 for ( $i = 6; $i >= 1; --$i ) {
1678 $h = str_repeat( '=', $i );
1679 // Trim non-newline whitespace from headings
1680 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1681 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1682 }
1683 return $text;
1684 }
1685
1686 /**
1687 * Replace single quotes with HTML markup
1688 * @private
1689 *
1690 * @param string $text
1691 *
1692 * @return string The altered text
1693 */
1694 public function doAllQuotes( $text ) {
1695 $outtext = '';
1696 $lines = StringUtils::explode( "\n", $text );
1697 foreach ( $lines as $line ) {
1698 $outtext .= $this->doQuotes( $line ) . "\n";
1699 }
1700 $outtext = substr( $outtext, 0, -1 );
1701 return $outtext;
1702 }
1703
1704 /**
1705 * Helper function for doAllQuotes()
1706 *
1707 * @param string $text
1708 *
1709 * @return string
1710 */
1711 public function doQuotes( $text ) {
1712 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1713 $countarr = count( $arr );
1714 if ( $countarr == 1 ) {
1715 return $text;
1716 }
1717
1718 // First, do some preliminary work. This may shift some apostrophes from
1719 // being mark-up to being text. It also counts the number of occurrences
1720 // of bold and italics mark-ups.
1721 $numbold = 0;
1722 $numitalics = 0;
1723 for ( $i = 1; $i < $countarr; $i += 2 ) {
1724 $thislen = strlen( $arr[$i] );
1725 // If there are ever four apostrophes, assume the first is supposed to
1726 // be text, and the remaining three constitute mark-up for bold text.
1727 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1728 if ( $thislen == 4 ) {
1729 $arr[$i - 1] .= "'";
1730 $arr[$i] = "'''";
1731 $thislen = 3;
1732 } elseif ( $thislen > 5 ) {
1733 // If there are more than 5 apostrophes in a row, assume they're all
1734 // text except for the last 5.
1735 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1736 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1737 $arr[$i] = "'''''";
1738 $thislen = 5;
1739 }
1740 // Count the number of occurrences of bold and italics mark-ups.
1741 if ( $thislen == 2 ) {
1742 $numitalics++;
1743 } elseif ( $thislen == 3 ) {
1744 $numbold++;
1745 } elseif ( $thislen == 5 ) {
1746 $numitalics++;
1747 $numbold++;
1748 }
1749 }
1750
1751 // If there is an odd number of both bold and italics, it is likely
1752 // that one of the bold ones was meant to be an apostrophe followed
1753 // by italics. Which one we cannot know for certain, but it is more
1754 // likely to be one that has a single-letter word before it.
1755 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1756 $firstsingleletterword = -1;
1757 $firstmultiletterword = -1;
1758 $firstspace = -1;
1759 for ( $i = 1; $i < $countarr; $i += 2 ) {
1760 if ( strlen( $arr[$i] ) == 3 ) {
1761 $x1 = substr( $arr[$i - 1], -1 );
1762 $x2 = substr( $arr[$i - 1], -2, 1 );
1763 if ( $x1 === ' ' ) {
1764 if ( $firstspace == -1 ) {
1765 $firstspace = $i;
1766 }
1767 } elseif ( $x2 === ' ' ) {
1768 $firstsingleletterword = $i;
1769 // if $firstsingleletterword is set, we don't
1770 // look at the other options, so we can bail early.
1771 break;
1772 } else {
1773 if ( $firstmultiletterword == -1 ) {
1774 $firstmultiletterword = $i;
1775 }
1776 }
1777 }
1778 }
1779
1780 // If there is a single-letter word, use it!
1781 if ( $firstsingleletterword > -1 ) {
1782 $arr[$firstsingleletterword] = "''";
1783 $arr[$firstsingleletterword - 1] .= "'";
1784 } elseif ( $firstmultiletterword > -1 ) {
1785 // If not, but there's a multi-letter word, use that one.
1786 $arr[$firstmultiletterword] = "''";
1787 $arr[$firstmultiletterword - 1] .= "'";
1788 } elseif ( $firstspace > -1 ) {
1789 // ... otherwise use the first one that has neither.
1790 // (notice that it is possible for all three to be -1 if, for example,
1791 // there is only one pentuple-apostrophe in the line)
1792 $arr[$firstspace] = "''";
1793 $arr[$firstspace - 1] .= "'";
1794 }
1795 }
1796
1797 // Now let's actually convert our apostrophic mush to HTML!
1798 $output = '';
1799 $buffer = '';
1800 $state = '';
1801 $i = 0;
1802 foreach ( $arr as $r ) {
1803 if ( ( $i % 2 ) == 0 ) {
1804 if ( $state === 'both' ) {
1805 $buffer .= $r;
1806 } else {
1807 $output .= $r;
1808 }
1809 } else {
1810 $thislen = strlen( $r );
1811 if ( $thislen == 2 ) {
1812 if ( $state === 'i' ) {
1813 $output .= '</i>';
1814 $state = '';
1815 } elseif ( $state === 'bi' ) {
1816 $output .= '</i>';
1817 $state = 'b';
1818 } elseif ( $state === 'ib' ) {
1819 $output .= '</b></i><b>';
1820 $state = 'b';
1821 } elseif ( $state === 'both' ) {
1822 $output .= '<b><i>' . $buffer . '</i>';
1823 $state = 'b';
1824 } else { // $state can be 'b' or ''
1825 $output .= '<i>';
1826 $state .= 'i';
1827 }
1828 } elseif ( $thislen == 3 ) {
1829 if ( $state === 'b' ) {
1830 $output .= '</b>';
1831 $state = '';
1832 } elseif ( $state === 'bi' ) {
1833 $output .= '</i></b><i>';
1834 $state = 'i';
1835 } elseif ( $state === 'ib' ) {
1836 $output .= '</b>';
1837 $state = 'i';
1838 } elseif ( $state === 'both' ) {
1839 $output .= '<i><b>' . $buffer . '</b>';
1840 $state = 'i';
1841 } else { // $state can be 'i' or ''
1842 $output .= '<b>';
1843 $state .= 'b';
1844 }
1845 } elseif ( $thislen == 5 ) {
1846 if ( $state === 'b' ) {
1847 $output .= '</b><i>';
1848 $state = 'i';
1849 } elseif ( $state === 'i' ) {
1850 $output .= '</i><b>';
1851 $state = 'b';
1852 } elseif ( $state === 'bi' ) {
1853 $output .= '</i></b>';
1854 $state = '';
1855 } elseif ( $state === 'ib' ) {
1856 $output .= '</b></i>';
1857 $state = '';
1858 } elseif ( $state === 'both' ) {
1859 $output .= '<i><b>' . $buffer . '</b></i>';
1860 $state = '';
1861 } else { // ($state == '')
1862 $buffer = '';
1863 $state = 'both';
1864 }
1865 }
1866 }
1867 $i++;
1868 }
1869 // Now close all remaining tags. Notice that the order is important.
1870 if ( $state === 'b' || $state === 'ib' ) {
1871 $output .= '</b>';
1872 }
1873 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1874 $output .= '</i>';
1875 }
1876 if ( $state === 'bi' ) {
1877 $output .= '</b>';
1878 }
1879 // There might be lonely ''''', so make sure we have a buffer
1880 if ( $state === 'both' && $buffer ) {
1881 $output .= '<b><i>' . $buffer . '</i></b>';
1882 }
1883 return $output;
1884 }
1885
1886 /**
1887 * Replace external links (REL)
1888 *
1889 * Note: this is all very hackish and the order of execution matters a lot.
1890 * Make sure to run tests/parser/parserTests.php if you change this code.
1891 *
1892 * @private
1893 *
1894 * @param string $text
1895 *
1896 * @throws MWException
1897 * @return string
1898 */
1899 public function replaceExternalLinks( $text ) {
1900 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1901 if ( $bits === false ) {
1902 throw new MWException( "PCRE needs to be compiled with "
1903 . "--enable-unicode-properties in order for MediaWiki to function" );
1904 }
1905 $s = array_shift( $bits );
1906
1907 $i = 0;
1908 while ( $i < count( $bits ) ) {
1909 $url = $bits[$i++];
1910 $i++; // protocol
1911 $text = $bits[$i++];
1912 $trail = $bits[$i++];
1913
1914 # The characters '<' and '>' (which were escaped by
1915 # removeHTMLtags()) should not be included in
1916 # URLs, per RFC 2396.
1917 $m2 = [];
1918 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1919 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1920 $url = substr( $url, 0, $m2[0][1] );
1921 }
1922
1923 # If the link text is an image URL, replace it with an <img> tag
1924 # This happened by accident in the original parser, but some people used it extensively
1925 $img = $this->maybeMakeExternalImage( $text );
1926 if ( $img !== false ) {
1927 $text = $img;
1928 }
1929
1930 $dtrail = '';
1931
1932 # Set linktype for CSS
1933 $linktype = 'text';
1934
1935 # No link text, e.g. [http://domain.tld/some.link]
1936 if ( $text == '' ) {
1937 # Autonumber
1938 $langObj = $this->getTargetLanguage();
1939 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1940 $linktype = 'autonumber';
1941 } else {
1942 # Have link text, e.g. [http://domain.tld/some.link text]s
1943 # Check for trail
1944 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1945 }
1946
1947 // Excluding protocol-relative URLs may avoid many false positives.
1948 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1949 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1950 }
1951
1952 $url = Sanitizer::cleanUrl( $url );
1953
1954 # Use the encoded URL
1955 # This means that users can paste URLs directly into the text
1956 # Funny characters like ö aren't valid in URLs anyway
1957 # This was changed in August 2004
1958 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1959 $this->getExternalLinkAttribs( $url ), $this->mTitle ) . $dtrail . $trail;
1960
1961 # Register link in the output object.
1962 $this->mOutput->addExternalLink( $url );
1963 }
1964
1965 return $s;
1966 }
1967
1968 /**
1969 * Get the rel attribute for a particular external link.
1970 *
1971 * @since 1.21
1972 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1973 * nofollow if appropriate
1974 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1975 * @return string|null Rel attribute for $url
1976 */
1977 public static function getExternalLinkRel( $url = false, $title = null ) {
1978 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1979 $ns = $title ? $title->getNamespace() : false;
1980 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1981 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1982 ) {
1983 return 'nofollow';
1984 }
1985 return null;
1986 }
1987
1988 /**
1989 * Get an associative array of additional HTML attributes appropriate for a
1990 * particular external link. This currently may include rel => nofollow
1991 * (depending on configuration, namespace, and the URL's domain) and/or a
1992 * target attribute (depending on configuration).
1993 *
1994 * @param string $url URL to extract the domain from for rel =>
1995 * nofollow if appropriate
1996 * @return array Associative array of HTML attributes
1997 */
1998 public function getExternalLinkAttribs( $url ) {
1999 $attribs = [];
2000 $rel = self::getExternalLinkRel( $url, $this->mTitle );
2001
2002 $target = $this->mOptions->getExternalLinkTarget();
2003 if ( $target ) {
2004 $attribs['target'] = $target;
2005 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
2006 // T133507. New windows can navigate parent cross-origin.
2007 // Including noreferrer due to lacking browser
2008 // support of noopener. Eventually noreferrer should be removed.
2009 if ( $rel !== '' ) {
2010 $rel .= ' ';
2011 }
2012 $rel .= 'noreferrer noopener';
2013 }
2014 }
2015 $attribs['rel'] = $rel;
2016 return $attribs;
2017 }
2018
2019 /**
2020 * Replace unusual escape codes in a URL with their equivalent characters
2021 *
2022 * This generally follows the syntax defined in RFC 3986, with special
2023 * consideration for HTTP query strings.
2024 *
2025 * @param string $url
2026 * @return string
2027 */
2028 public static function normalizeLinkUrl( $url ) {
2029 # Test for RFC 3986 IPv6 syntax
2030 $scheme = '[a-z][a-z0-9+.-]*:';
2031 $userinfo = '(?:[a-z0-9\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*';
2032 $ipv6Host = '\\[((?:[0-9a-f:]|%3[0-A]|%[46][1-6])+)\\]';
2033 if ( preg_match( "<^(?:{$scheme})?//(?:{$userinfo}@)?{$ipv6Host}(?:[:/?#].*|)$>i", $url, $m ) &&
2034 IP::isValid( rawurldecode( $m[1] ) )
2035 ) {
2036 $isIPv6 = rawurldecode( $m[1] );
2037 } else {
2038 $isIPv6 = false;
2039 }
2040
2041 # Make sure unsafe characters are encoded
2042 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2043 function ( $m ) {
2044 return rawurlencode( $m[0] );
2045 },
2046 $url
2047 );
2048
2049 $ret = '';
2050 $end = strlen( $url );
2051
2052 # Fragment part - 'fragment'
2053 $start = strpos( $url, '#' );
2054 if ( $start !== false && $start < $end ) {
2055 $ret = self::normalizeUrlComponent(
2056 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2057 $end = $start;
2058 }
2059
2060 # Query part - 'query' minus &=+;
2061 $start = strpos( $url, '?' );
2062 if ( $start !== false && $start < $end ) {
2063 $ret = self::normalizeUrlComponent(
2064 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2065 $end = $start;
2066 }
2067
2068 # Scheme and path part - 'pchar'
2069 # (we assume no userinfo or encoded colons in the host)
2070 $ret = self::normalizeUrlComponent(
2071 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2072
2073 # Fix IPv6 syntax
2074 if ( $isIPv6 !== false ) {
2075 $ipv6Host = "%5B({$isIPv6})%5D";
2076 $ret = preg_replace(
2077 "<^((?:{$scheme})?//(?:{$userinfo}@)?){$ipv6Host}(?=[:/?#]|$)>i",
2078 "$1[$2]",
2079 $ret
2080 );
2081 }
2082
2083 return $ret;
2084 }
2085
2086 private static function normalizeUrlComponent( $component, $unsafe ) {
2087 $callback = function ( $matches ) use ( $unsafe ) {
2088 $char = urldecode( $matches[0] );
2089 $ord = ord( $char );
2090 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2091 # Unescape it
2092 return $char;
2093 } else {
2094 # Leave it escaped, but use uppercase for a-f
2095 return strtoupper( $matches[0] );
2096 }
2097 };
2098 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2099 }
2100
2101 /**
2102 * make an image if it's allowed, either through the global
2103 * option, through the exception, or through the on-wiki whitelist
2104 *
2105 * @param string $url
2106 *
2107 * @return string
2108 */
2109 private function maybeMakeExternalImage( $url ) {
2110 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
2111 $imagesexception = !empty( $imagesfrom );
2112 $text = false;
2113 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2114 if ( $imagesexception && is_array( $imagesfrom ) ) {
2115 $imagematch = false;
2116 foreach ( $imagesfrom as $match ) {
2117 if ( strpos( $url, $match ) === 0 ) {
2118 $imagematch = true;
2119 break;
2120 }
2121 }
2122 } elseif ( $imagesexception ) {
2123 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2124 } else {
2125 $imagematch = false;
2126 }
2127
2128 if ( $this->mOptions->getAllowExternalImages()
2129 || ( $imagesexception && $imagematch )
2130 ) {
2131 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
2132 # Image found
2133 $text = Linker::makeExternalImage( $url );
2134 }
2135 }
2136 if ( !$text && $this->mOptions->getEnableImageWhitelist()
2137 && preg_match( self::EXT_IMAGE_REGEX, $url )
2138 ) {
2139 $whitelist = explode(
2140 "\n",
2141 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2142 );
2143
2144 foreach ( $whitelist as $entry ) {
2145 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2146 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
2147 continue;
2148 }
2149 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2150 # Image matches a whitelist entry
2151 $text = Linker::makeExternalImage( $url );
2152 break;
2153 }
2154 }
2155 }
2156 return $text;
2157 }
2158
2159 /**
2160 * Process [[ ]] wikilinks
2161 *
2162 * @param string $s
2163 *
2164 * @return string Processed text
2165 *
2166 * @private
2167 */
2168 public function replaceInternalLinks( $s ) {
2169 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
2170 return $s;
2171 }
2172
2173 /**
2174 * Process [[ ]] wikilinks (RIL)
2175 * @param string &$s
2176 * @throws MWException
2177 * @return LinkHolderArray
2178 *
2179 * @private
2180 */
2181 public function replaceInternalLinks2( &$s ) {
2182 static $tc = false, $e1, $e1_img;
2183 # the % is needed to support urlencoded titles as well
2184 if ( !$tc ) {
2185 $tc = Title::legalChars() . '#%';
2186 # Match a link having the form [[namespace:link|alternate]]trail
2187 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2188 # Match cases where there is no "]]", which might still be images
2189 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2190 }
2191
2192 $holders = new LinkHolderArray( $this );
2193
2194 # split the entire text string on occurrences of [[
2195 $a = StringUtils::explode( '[[', ' ' . $s );
2196 # get the first element (all text up to first [[), and remove the space we added
2197 $s = $a->current();
2198 $a->next();
2199 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2200 $s = substr( $s, 1 );
2201
2202 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2203 $e2 = null;
2204 if ( $useLinkPrefixExtension ) {
2205 # Match the end of a line for a word that's not followed by whitespace,
2206 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2207 $charset = $this->contLang->linkPrefixCharset();
2208 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2209 }
2210
2211 if ( is_null( $this->mTitle ) ) {
2212 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2213 }
2214 $nottalk = !$this->mTitle->isTalkPage();
2215
2216 if ( $useLinkPrefixExtension ) {
2217 $m = [];
2218 if ( preg_match( $e2, $s, $m ) ) {
2219 $first_prefix = $m[2];
2220 } else {
2221 $first_prefix = false;
2222 }
2223 } else {
2224 $prefix = '';
2225 }
2226
2227 $useSubpages = $this->areSubpagesAllowed();
2228
2229 # Loop for each link
2230 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2231 # Check for excessive memory usage
2232 if ( $holders->isBig() ) {
2233 # Too big
2234 # Do the existence check, replace the link holders and clear the array
2235 $holders->replace( $s );
2236 $holders->clear();
2237 }
2238
2239 if ( $useLinkPrefixExtension ) {
2240 if ( preg_match( $e2, $s, $m ) ) {
2241 $prefix = $m[2];
2242 $s = $m[1];
2243 } else {
2244 $prefix = '';
2245 }
2246 # first link
2247 if ( $first_prefix ) {
2248 $prefix = $first_prefix;
2249 $first_prefix = false;
2250 }
2251 }
2252
2253 $might_be_img = false;
2254
2255 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2256 $text = $m[2];
2257 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2258 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2259 # the real problem is with the $e1 regex
2260 # See T1500.
2261 # Still some problems for cases where the ] is meant to be outside punctuation,
2262 # and no image is in sight. See T4095.
2263 if ( $text !== ''
2264 && substr( $m[3], 0, 1 ) === ']'
2265 && strpos( $text, '[' ) !== false
2266 ) {
2267 $text .= ']'; # so that replaceExternalLinks($text) works later
2268 $m[3] = substr( $m[3], 1 );
2269 }
2270 # fix up urlencoded title texts
2271 if ( strpos( $m[1], '%' ) !== false ) {
2272 # Should anchors '#' also be rejected?
2273 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2274 }
2275 $trail = $m[3];
2276 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2277 # Invalid, but might be an image with a link in its caption
2278 $might_be_img = true;
2279 $text = $m[2];
2280 if ( strpos( $m[1], '%' ) !== false ) {
2281 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2282 }
2283 $trail = "";
2284 } else { # Invalid form; output directly
2285 $s .= $prefix . '[[' . $line;
2286 continue;
2287 }
2288
2289 $origLink = ltrim( $m[1], ' ' );
2290
2291 # Don't allow internal links to pages containing
2292 # PROTO: where PROTO is a valid URL protocol; these
2293 # should be external links.
2294 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) {
2295 $s .= $prefix . '[[' . $line;
2296 continue;
2297 }
2298
2299 # Make subpage if necessary
2300 if ( $useSubpages ) {
2301 $link = $this->maybeDoSubpageLink( $origLink, $text );
2302 } else {
2303 $link = $origLink;
2304 }
2305
2306 // \x7f isn't a default legal title char, so most likely strip
2307 // markers will force us into the "invalid form" path above. But,
2308 // just in case, let's assert that xmlish tags aren't valid in
2309 // the title position.
2310 $unstrip = $this->mStripState->killMarkers( $link );
2311 $noMarkers = ( $unstrip === $link );
2312
2313 $nt = $noMarkers ? Title::newFromText( $link ) : null;
2314 if ( $nt === null ) {
2315 $s .= $prefix . '[[' . $line;
2316 continue;
2317 }
2318
2319 $ns = $nt->getNamespace();
2320 $iw = $nt->getInterwiki();
2321
2322 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2323
2324 if ( $might_be_img ) { # if this is actually an invalid link
2325 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2326 $found = false;
2327 while ( true ) {
2328 # look at the next 'line' to see if we can close it there
2329 $a->next();
2330 $next_line = $a->current();
2331 if ( $next_line === false || $next_line === null ) {
2332 break;
2333 }
2334 $m = explode( ']]', $next_line, 3 );
2335 if ( count( $m ) == 3 ) {
2336 # the first ]] closes the inner link, the second the image
2337 $found = true;
2338 $text .= "[[{$m[0]}]]{$m[1]}";
2339 $trail = $m[2];
2340 break;
2341 } elseif ( count( $m ) == 2 ) {
2342 # if there's exactly one ]] that's fine, we'll keep looking
2343 $text .= "[[{$m[0]}]]{$m[1]}";
2344 } else {
2345 # if $next_line is invalid too, we need look no further
2346 $text .= '[[' . $next_line;
2347 break;
2348 }
2349 }
2350 if ( !$found ) {
2351 # we couldn't find the end of this imageLink, so output it raw
2352 # but don't ignore what might be perfectly normal links in the text we've examined
2353 $holders->merge( $this->replaceInternalLinks2( $text ) );
2354 $s .= "{$prefix}[[$link|$text";
2355 # note: no $trail, because without an end, there *is* no trail
2356 continue;
2357 }
2358 } else { # it's not an image, so output it raw
2359 $s .= "{$prefix}[[$link|$text";
2360 # note: no $trail, because without an end, there *is* no trail
2361 continue;
2362 }
2363 }
2364
2365 $wasblank = ( $text == '' );
2366 if ( $wasblank ) {
2367 $text = $link;
2368 if ( !$noforce ) {
2369 # Strip off leading ':'
2370 $text = substr( $text, 1 );
2371 }
2372 } else {
2373 # T6598 madness. Handle the quotes only if they come from the alternate part
2374 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2375 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2376 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2377 $text = $this->doQuotes( $text );
2378 }
2379
2380 # Link not escaped by : , create the various objects
2381 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2382 # Interwikis
2383 if (
2384 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2385 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2386 in_array( $iw, $this->siteConfig->get( 'ExtraInterlanguageLinkPrefixes' ) )
2387 )
2388 ) {
2389 # T26502: filter duplicates
2390 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2391 $this->mLangLinkLanguages[$iw] = true;
2392 $this->mOutput->addLanguageLink( $nt->getFullText() );
2393 }
2394
2395 /**
2396 * Strip the whitespace interwiki links produce, see T10897
2397 */
2398 $s = rtrim( $s . $prefix ) . $trail; # T175416
2399 continue;
2400 }
2401
2402 if ( $ns == NS_FILE ) {
2403 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2404 if ( $wasblank ) {
2405 # if no parameters were passed, $text
2406 # becomes something like "File:Foo.png",
2407 # which we don't want to pass on to the
2408 # image generator
2409 $text = '';
2410 } else {
2411 # recursively parse links inside the image caption
2412 # actually, this will parse them in any other parameters, too,
2413 # but it might be hard to fix that, and it doesn't matter ATM
2414 $text = $this->replaceExternalLinks( $text );
2415 $holders->merge( $this->replaceInternalLinks2( $text ) );
2416 }
2417 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2418 $s .= $prefix . $this->armorLinks(
2419 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2420 continue;
2421 }
2422 } elseif ( $ns == NS_CATEGORY ) {
2423 /**
2424 * Strip the whitespace Category links produce, see T2087
2425 */
2426 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2427
2428 if ( $wasblank ) {
2429 $sortkey = $this->getDefaultSort();
2430 } else {
2431 $sortkey = $text;
2432 }
2433 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2434 $sortkey = str_replace( "\n", '', $sortkey );
2435 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2436 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2437
2438 continue;
2439 }
2440 }
2441
2442 # Self-link checking. For some languages, variants of the title are checked in
2443 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2444 # for linking to a different variant.
2445 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2446 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2447 continue;
2448 }
2449
2450 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2451 # @todo FIXME: Should do batch file existence checks, see comment below
2452 if ( $ns == NS_MEDIA ) {
2453 # Give extensions a chance to select the file revision for us
2454 $options = [];
2455 $descQuery = false;
2456 Hooks::run( 'BeforeParserFetchFileAndTitle',
2457 [ $this, $nt, &$options, &$descQuery ] );
2458 # Fetch and register the file (file title may be different via hooks)
2459 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2460 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2461 $s .= $prefix . $this->armorLinks(
2462 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2463 continue;
2464 }
2465
2466 # Some titles, such as valid special pages or files in foreign repos, should
2467 # be shown as bluelinks even though they're not included in the page table
2468 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2469 # batch file existence checks for NS_FILE and NS_MEDIA
2470 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2471 $this->mOutput->addLink( $nt );
2472 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2473 } else {
2474 # Links will be added to the output link list after checking
2475 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2476 }
2477 }
2478 return $holders;
2479 }
2480
2481 /**
2482 * Render a forced-blue link inline; protect against double expansion of
2483 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2484 * Since this little disaster has to split off the trail text to avoid
2485 * breaking URLs in the following text without breaking trails on the
2486 * wiki links, it's been made into a horrible function.
2487 *
2488 * @param Title $nt
2489 * @param string $text
2490 * @param string $trail
2491 * @param string $prefix
2492 * @return string HTML-wikitext mix oh yuck
2493 */
2494 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2495 list( $inside, $trail ) = Linker::splitTrail( $trail );
2496
2497 if ( $text == '' ) {
2498 $text = htmlspecialchars( $nt->getPrefixedText() );
2499 }
2500
2501 $link = $this->getLinkRenderer()->makeKnownLink(
2502 $nt, new HtmlArmor( "$prefix$text$inside" )
2503 );
2504
2505 return $this->armorLinks( $link ) . $trail;
2506 }
2507
2508 /**
2509 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2510 * going to go through further parsing steps before inline URL expansion.
2511 *
2512 * Not needed quite as much as it used to be since free links are a bit
2513 * more sensible these days. But bracketed links are still an issue.
2514 *
2515 * @param string $text More-or-less HTML
2516 * @return string Less-or-more HTML with NOPARSE bits
2517 */
2518 public function armorLinks( $text ) {
2519 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2520 self::MARKER_PREFIX . "NOPARSE$1", $text );
2521 }
2522
2523 /**
2524 * Return true if subpage links should be expanded on this page.
2525 * @return bool
2526 */
2527 public function areSubpagesAllowed() {
2528 # Some namespaces don't allow subpages
2529 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2530 }
2531
2532 /**
2533 * Handle link to subpage if necessary
2534 *
2535 * @param string $target The source of the link
2536 * @param string &$text The link text, modified as necessary
2537 * @return string The full name of the link
2538 * @private
2539 */
2540 public function maybeDoSubpageLink( $target, &$text ) {
2541 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2542 }
2543
2544 /**
2545 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2546 *
2547 * @param string $text
2548 * @param bool $linestart Whether or not this is at the start of a line.
2549 * @private
2550 * @return string The lists rendered as HTML
2551 */
2552 public function doBlockLevels( $text, $linestart ) {
2553 return BlockLevelPass::doBlockLevels( $text, $linestart );
2554 }
2555
2556 /**
2557 * Return value of a magic variable (like PAGENAME)
2558 *
2559 * @private
2560 *
2561 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2562 * @param bool|PPFrame $frame
2563 *
2564 * @throws MWException
2565 * @return string
2566 */
2567 public function getVariableValue( $index, $frame = false ) {
2568 if ( is_null( $this->mTitle ) ) {
2569 // If no title set, bad things are going to happen
2570 // later. Title should always be set since this
2571 // should only be called in the middle of a parse
2572 // operation (but the unit-tests do funky stuff)
2573 throw new MWException( __METHOD__ . ' Should only be '
2574 . ' called while parsing (no title set)' );
2575 }
2576
2577 // Avoid PHP 7.1 warning from passing $this by reference
2578 $parser = $this;
2579
2580 /**
2581 * Some of these require message or data lookups and can be
2582 * expensive to check many times.
2583 */
2584 if ( Hooks::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache ] ) ) {
2585 if ( isset( $this->mVarCache[$index] ) ) {
2586 return $this->mVarCache[$index];
2587 }
2588 }
2589
2590 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2591 Hooks::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2592
2593 $pageLang = $this->getFunctionLang();
2594
2595 switch ( $index ) {
2596 case '!':
2597 $value = '|';
2598 break;
2599 case 'currentmonth':
2600 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ), true );
2601 break;
2602 case 'currentmonth1':
2603 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ), true );
2604 break;
2605 case 'currentmonthname':
2606 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2607 break;
2608 case 'currentmonthnamegen':
2609 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2610 break;
2611 case 'currentmonthabbrev':
2612 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2613 break;
2614 case 'currentday':
2615 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ), true );
2616 break;
2617 case 'currentday2':
2618 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ), true );
2619 break;
2620 case 'localmonth':
2621 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ), true );
2622 break;
2623 case 'localmonth1':
2624 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ), true );
2625 break;
2626 case 'localmonthname':
2627 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2628 break;
2629 case 'localmonthnamegen':
2630 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2631 break;
2632 case 'localmonthabbrev':
2633 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2634 break;
2635 case 'localday':
2636 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ), true );
2637 break;
2638 case 'localday2':
2639 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ), true );
2640 break;
2641 case 'pagename':
2642 $value = wfEscapeWikiText( $this->mTitle->getText() );
2643 break;
2644 case 'pagenamee':
2645 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2646 break;
2647 case 'fullpagename':
2648 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2649 break;
2650 case 'fullpagenamee':
2651 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2652 break;
2653 case 'subpagename':
2654 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2655 break;
2656 case 'subpagenamee':
2657 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2658 break;
2659 case 'rootpagename':
2660 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2661 break;
2662 case 'rootpagenamee':
2663 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2664 ' ',
2665 '_',
2666 $this->mTitle->getRootText()
2667 ) ) );
2668 break;
2669 case 'basepagename':
2670 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2671 break;
2672 case 'basepagenamee':
2673 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2674 ' ',
2675 '_',
2676 $this->mTitle->getBaseText()
2677 ) ) );
2678 break;
2679 case 'talkpagename':
2680 if ( $this->mTitle->canHaveTalkPage() ) {
2681 $talkPage = $this->mTitle->getTalkPage();
2682 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2683 } else {
2684 $value = '';
2685 }
2686 break;
2687 case 'talkpagenamee':
2688 if ( $this->mTitle->canHaveTalkPage() ) {
2689 $talkPage = $this->mTitle->getTalkPage();
2690 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2691 } else {
2692 $value = '';
2693 }
2694 break;
2695 case 'subjectpagename':
2696 $subjPage = $this->mTitle->getSubjectPage();
2697 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2698 break;
2699 case 'subjectpagenamee':
2700 $subjPage = $this->mTitle->getSubjectPage();
2701 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2702 break;
2703 case 'pageid': // requested in T25427
2704 $pageid = $this->getTitle()->getArticleID();
2705 if ( $pageid == 0 ) {
2706 # 0 means the page doesn't exist in the database,
2707 # which means the user is previewing a new page.
2708 # The vary-revision flag must be set, because the magic word
2709 # will have a different value once the page is saved.
2710 $this->mOutput->setFlag( 'vary-revision' );
2711 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2712 }
2713 $value = $pageid ?: null;
2714 break;
2715 case 'revisionid':
2716 # Let the edit saving system know we should parse the page
2717 # *after* a revision ID has been assigned.
2718 $this->mOutput->setFlag( 'vary-revision-id' );
2719 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2720 $value = $this->mRevisionId;
2721
2722 if ( !$value ) {
2723 $rev = $this->getRevisionObject();
2724 if ( $rev ) {
2725 $value = $rev->getId();
2726 }
2727 }
2728
2729 if ( !$value ) {
2730 $value = $this->mOptions->getSpeculativeRevId();
2731 if ( $value ) {
2732 $this->mOutput->setSpeculativeRevIdUsed( $value );
2733 }
2734 }
2735 break;
2736 case 'revisionday':
2737 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self::MAX_TTS, $index );
2738 break;
2739 case 'revisionday2':
2740 $value = $this->getRevisionTimestampSubstring( 6, 2, self::MAX_TTS, $index );
2741 break;
2742 case 'revisionmonth':
2743 $value = $this->getRevisionTimestampSubstring( 4, 2, self::MAX_TTS, $index );
2744 break;
2745 case 'revisionmonth1':
2746 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self::MAX_TTS, $index );
2747 break;
2748 case 'revisionyear':
2749 $value = $this->getRevisionTimestampSubstring( 0, 4, self::MAX_TTS, $index );
2750 break;
2751 case 'revisiontimestamp':
2752 # Let the edit saving system know we should parse the page
2753 # *after* a revision ID has been assigned. This is for null edits.
2754 $this->mOutput->setFlag( 'vary-revision' );
2755 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2756 $value = $this->getRevisionTimestamp();
2757 break;
2758 case 'revisionuser':
2759 # Let the edit saving system know we should parse the page
2760 # *after* a revision ID has been assigned for null edits.
2761 $this->mOutput->setFlag( 'vary-user' );
2762 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-user...\n" );
2763 $value = $this->getRevisionUser();
2764 break;
2765 case 'revisionsize':
2766 $value = $this->getRevisionSize();
2767 break;
2768 case 'namespace':
2769 $value = str_replace( '_', ' ',
2770 $this->contLang->getNsText( $this->mTitle->getNamespace() ) );
2771 break;
2772 case 'namespacee':
2773 $value = wfUrlencode( $this->contLang->getNsText( $this->mTitle->getNamespace() ) );
2774 break;
2775 case 'namespacenumber':
2776 $value = $this->mTitle->getNamespace();
2777 break;
2778 case 'talkspace':
2779 $value = $this->mTitle->canHaveTalkPage()
2780 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
2781 : '';
2782 break;
2783 case 'talkspacee':
2784 $value = $this->mTitle->canHaveTalkPage() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2785 break;
2786 case 'subjectspace':
2787 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
2788 break;
2789 case 'subjectspacee':
2790 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2791 break;
2792 case 'currentdayname':
2793 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
2794 break;
2795 case 'currentyear':
2796 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
2797 break;
2798 case 'currenttime':
2799 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2800 break;
2801 case 'currenthour':
2802 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
2803 break;
2804 case 'currentweek':
2805 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2806 # int to remove the padding
2807 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
2808 break;
2809 case 'currentdow':
2810 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
2811 break;
2812 case 'localdayname':
2813 $value = $pageLang->getWeekdayName(
2814 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
2815 );
2816 break;
2817 case 'localyear':
2818 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
2819 break;
2820 case 'localtime':
2821 $value = $pageLang->time(
2822 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
2823 false,
2824 false
2825 );
2826 break;
2827 case 'localhour':
2828 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
2829 break;
2830 case 'localweek':
2831 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2832 # int to remove the padding
2833 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
2834 break;
2835 case 'localdow':
2836 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
2837 break;
2838 case 'numberofarticles':
2839 $value = $pageLang->formatNum( SiteStats::articles() );
2840 break;
2841 case 'numberoffiles':
2842 $value = $pageLang->formatNum( SiteStats::images() );
2843 break;
2844 case 'numberofusers':
2845 $value = $pageLang->formatNum( SiteStats::users() );
2846 break;
2847 case 'numberofactiveusers':
2848 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2849 break;
2850 case 'numberofpages':
2851 $value = $pageLang->formatNum( SiteStats::pages() );
2852 break;
2853 case 'numberofadmins':
2854 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2855 break;
2856 case 'numberofedits':
2857 $value = $pageLang->formatNum( SiteStats::edits() );
2858 break;
2859 case 'currenttimestamp':
2860 $value = wfTimestamp( TS_MW, $ts );
2861 break;
2862 case 'localtimestamp':
2863 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
2864 break;
2865 case 'currentversion':
2866 $value = SpecialVersion::getVersion();
2867 break;
2868 case 'articlepath':
2869 return $this->siteConfig->get( 'ArticlePath' );
2870 case 'sitename':
2871 return $this->siteConfig->get( 'Sitename' );
2872 case 'server':
2873 return $this->siteConfig->get( 'Server' );
2874 case 'servername':
2875 return $this->siteConfig->get( 'ServerName' );
2876 case 'scriptpath':
2877 return $this->siteConfig->get( 'ScriptPath' );
2878 case 'stylepath':
2879 return $this->siteConfig->get( 'StylePath' );
2880 case 'directionmark':
2881 return $pageLang->getDirMark();
2882 case 'contentlanguage':
2883 return $this->siteConfig->get( 'LanguageCode' );
2884 case 'pagelanguage':
2885 $value = $pageLang->getCode();
2886 break;
2887 case 'cascadingsources':
2888 $value = CoreParserFunctions::cascadingsources( $this );
2889 break;
2890 default:
2891 $ret = null;
2892 Hooks::run(
2893 'ParserGetVariableValueSwitch',
2894 [ &$parser, &$this->mVarCache, &$index, &$ret, &$frame ]
2895 );
2896
2897 return $ret;
2898 }
2899
2900 if ( $index ) {
2901 $this->mVarCache[$index] = $value;
2902 }
2903
2904 return $value;
2905 }
2906
2907 /**
2908 * @param int $start
2909 * @param int $len
2910 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2911 * @param string $variable Parser variable name
2912 * @return string
2913 */
2914 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2915 # Get the timezone-adjusted timestamp to be used for this revision
2916 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2917 # Possibly set vary-revision if there is not yet an associated revision
2918 if ( !$this->getRevisionObject() ) {
2919 # Get the timezone-adjusted timestamp $mtts seconds in the future
2920 $resThen = substr(
2921 $this->contLang->userAdjust( wfTimestamp( TS_MW, time() + $mtts ), '' ),
2922 $start,
2923 $len
2924 );
2925
2926 if ( $resNow !== $resThen ) {
2927 # Let the edit saving system know we should parse the page
2928 # *after* a revision ID has been assigned. This is for null edits.
2929 $this->mOutput->setFlag( 'vary-revision' );
2930 wfDebug( __METHOD__ . ": $variable used, setting vary-revision...\n" );
2931 }
2932 }
2933
2934 return $resNow;
2935 }
2936
2937 /**
2938 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2939 *
2940 * @private
2941 */
2942 public function initialiseVariables() {
2943 $variableIDs = $this->magicWordFactory->getVariableIDs();
2944 $substIDs = $this->magicWordFactory->getSubstIDs();
2945
2946 $this->mVariables = $this->magicWordFactory->newArray( $variableIDs );
2947 $this->mSubstWords = $this->magicWordFactory->newArray( $substIDs );
2948 }
2949
2950 /**
2951 * Preprocess some wikitext and return the document tree.
2952 * This is the ghost of replace_variables().
2953 *
2954 * @param string $text The text to parse
2955 * @param int $flags Bitwise combination of:
2956 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2957 * included. Default is to assume a direct page view.
2958 *
2959 * The generated DOM tree must depend only on the input text and the flags.
2960 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2961 *
2962 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2963 * change in the DOM tree for a given text, must be passed through the section identifier
2964 * in the section edit link and thus back to extractSections().
2965 *
2966 * The output of this function is currently only cached in process memory, but a persistent
2967 * cache may be implemented at a later date which takes further advantage of these strict
2968 * dependency requirements.
2969 *
2970 * @return PPNode
2971 */
2972 public function preprocessToDom( $text, $flags = 0 ) {
2973 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2974 return $dom;
2975 }
2976
2977 /**
2978 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2979 *
2980 * @param string $s
2981 *
2982 * @return array
2983 */
2984 public static function splitWhitespace( $s ) {
2985 $ltrimmed = ltrim( $s );
2986 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2987 $trimmed = rtrim( $ltrimmed );
2988 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2989 if ( $diff > 0 ) {
2990 $w2 = substr( $ltrimmed, -$diff );
2991 } else {
2992 $w2 = '';
2993 }
2994 return [ $w1, $trimmed, $w2 ];
2995 }
2996
2997 /**
2998 * Replace magic variables, templates, and template arguments
2999 * with the appropriate text. Templates are substituted recursively,
3000 * taking care to avoid infinite loops.
3001 *
3002 * Note that the substitution depends on value of $mOutputType:
3003 * self::OT_WIKI: only {{subst:}} templates
3004 * self::OT_PREPROCESS: templates but not extension tags
3005 * self::OT_HTML: all templates and extension tags
3006 *
3007 * @param string $text The text to transform
3008 * @param bool|PPFrame $frame Object describing the arguments passed to the
3009 * template. Arguments may also be provided as an associative array, as
3010 * was the usual case before MW1.12. Providing arguments this way may be
3011 * useful for extensions wishing to perform variable replacement
3012 * explicitly.
3013 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3014 * double-brace expansion.
3015 * @return string
3016 */
3017 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3018 # Is there any text? Also, Prevent too big inclusions!
3019 $textSize = strlen( $text );
3020 if ( $textSize < 1 || $textSize > $this->mOptions->getMaxIncludeSize() ) {
3021 return $text;
3022 }
3023
3024 if ( $frame === false ) {
3025 $frame = $this->getPreprocessor()->newFrame();
3026 } elseif ( !( $frame instanceof PPFrame ) ) {
3027 wfDebug( __METHOD__ . " called using plain parameters instead of "
3028 . "a PPFrame instance. Creating custom frame.\n" );
3029 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3030 }
3031
3032 $dom = $this->preprocessToDom( $text );
3033 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3034 $text = $frame->expand( $dom, $flags );
3035
3036 return $text;
3037 }
3038
3039 /**
3040 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3041 *
3042 * @param array $args
3043 *
3044 * @return array
3045 */
3046 public static function createAssocArgs( $args ) {
3047 $assocArgs = [];
3048 $index = 1;
3049 foreach ( $args as $arg ) {
3050 $eqpos = strpos( $arg, '=' );
3051 if ( $eqpos === false ) {
3052 $assocArgs[$index++] = $arg;
3053 } else {
3054 $name = trim( substr( $arg, 0, $eqpos ) );
3055 $value = trim( substr( $arg, $eqpos + 1 ) );
3056 if ( $value === false ) {
3057 $value = '';
3058 }
3059 if ( $name !== false ) {
3060 $assocArgs[$name] = $value;
3061 }
3062 }
3063 }
3064
3065 return $assocArgs;
3066 }
3067
3068 /**
3069 * Warn the user when a parser limitation is reached
3070 * Will warn at most once the user per limitation type
3071 *
3072 * The results are shown during preview and run through the Parser (See EditPage.php)
3073 *
3074 * @param string $limitationType Should be one of:
3075 * 'expensive-parserfunction' (corresponding messages:
3076 * 'expensive-parserfunction-warning',
3077 * 'expensive-parserfunction-category')
3078 * 'post-expand-template-argument' (corresponding messages:
3079 * 'post-expand-template-argument-warning',
3080 * 'post-expand-template-argument-category')
3081 * 'post-expand-template-inclusion' (corresponding messages:
3082 * 'post-expand-template-inclusion-warning',
3083 * 'post-expand-template-inclusion-category')
3084 * 'node-count-exceeded' (corresponding messages:
3085 * 'node-count-exceeded-warning',
3086 * 'node-count-exceeded-category')
3087 * 'expansion-depth-exceeded' (corresponding messages:
3088 * 'expansion-depth-exceeded-warning',
3089 * 'expansion-depth-exceeded-category')
3090 * @param string|int|null $current Current value
3091 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3092 * exceeded, provide the values (optional)
3093 */
3094 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3095 # does no harm if $current and $max are present but are unnecessary for the message
3096 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3097 # only during preview, and that would split the parser cache unnecessarily.
3098 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3099 ->text();
3100 $this->mOutput->addWarning( $warning );
3101 $this->addTrackingCategory( "$limitationType-category" );
3102 }
3103
3104 /**
3105 * Return the text of a template, after recursively
3106 * replacing any variables or templates within the template.
3107 *
3108 * @param array $piece The parts of the template
3109 * $piece['title']: the title, i.e. the part before the |
3110 * $piece['parts']: the parameter array
3111 * $piece['lineStart']: whether the brace was at the start of a line
3112 * @param PPFrame $frame The current frame, contains template arguments
3113 * @throws Exception
3114 * @return string The text of the template
3115 */
3116 public function braceSubstitution( $piece, $frame ) {
3117 // Flags
3118
3119 // $text has been filled
3120 $found = false;
3121 // wiki markup in $text should be escaped
3122 $nowiki = false;
3123 // $text is HTML, armour it against wikitext transformation
3124 $isHTML = false;
3125 // Force interwiki transclusion to be done in raw mode not rendered
3126 $forceRawInterwiki = false;
3127 // $text is a DOM node needing expansion in a child frame
3128 $isChildObj = false;
3129 // $text is a DOM node needing expansion in the current frame
3130 $isLocalObj = false;
3131
3132 # Title object, where $text came from
3133 $title = false;
3134
3135 # $part1 is the bit before the first |, and must contain only title characters.
3136 # Various prefixes will be stripped from it later.
3137 $titleWithSpaces = $frame->expand( $piece['title'] );
3138 $part1 = trim( $titleWithSpaces );
3139 $titleText = false;
3140
3141 # Original title text preserved for various purposes
3142 $originalTitle = $part1;
3143
3144 # $args is a list of argument nodes, starting from index 0, not including $part1
3145 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3146 # below won't work b/c this $args isn't an object
3147 $args = ( null == $piece['parts'] ) ? [] : $piece['parts'];
3148
3149 $profileSection = null; // profile templates
3150
3151 # SUBST
3152 if ( !$found ) {
3153 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3154
3155 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3156 # Decide whether to expand template or keep wikitext as-is.
3157 if ( $this->ot['wiki'] ) {
3158 if ( $substMatch === false ) {
3159 $literal = true; # literal when in PST with no prefix
3160 } else {
3161 $literal = false; # expand when in PST with subst: or safesubst:
3162 }
3163 } else {
3164 if ( $substMatch == 'subst' ) {
3165 $literal = true; # literal when not in PST with plain subst:
3166 } else {
3167 $literal = false; # expand when not in PST with safesubst: or no prefix
3168 }
3169 }
3170 if ( $literal ) {
3171 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3172 $isLocalObj = true;
3173 $found = true;
3174 }
3175 }
3176
3177 # Variables
3178 if ( !$found && $args->getLength() == 0 ) {
3179 $id = $this->mVariables->matchStartToEnd( $part1 );
3180 if ( $id !== false ) {
3181 $text = $this->getVariableValue( $id, $frame );
3182 if ( $this->magicWordFactory->getCacheTTL( $id ) > -1 ) {
3183 $this->mOutput->updateCacheExpiry(
3184 $this->magicWordFactory->getCacheTTL( $id ) );
3185 }
3186 $found = true;
3187 }
3188 }
3189
3190 # MSG, MSGNW and RAW
3191 if ( !$found ) {
3192 # Check for MSGNW:
3193 $mwMsgnw = $this->magicWordFactory->get( 'msgnw' );
3194 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3195 $nowiki = true;
3196 } else {
3197 # Remove obsolete MSG:
3198 $mwMsg = $this->magicWordFactory->get( 'msg' );
3199 $mwMsg->matchStartAndRemove( $part1 );
3200 }
3201
3202 # Check for RAW:
3203 $mwRaw = $this->magicWordFactory->get( 'raw' );
3204 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3205 $forceRawInterwiki = true;
3206 }
3207 }
3208
3209 # Parser functions
3210 if ( !$found ) {
3211 $colonPos = strpos( $part1, ':' );
3212 if ( $colonPos !== false ) {
3213 $func = substr( $part1, 0, $colonPos );
3214 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3215 $argsLength = $args->getLength();
3216 for ( $i = 0; $i < $argsLength; $i++ ) {
3217 $funcArgs[] = $args->item( $i );
3218 }
3219
3220 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3221
3222 // Extract any forwarded flags
3223 if ( isset( $result['title'] ) ) {
3224 $title = $result['title'];
3225 }
3226 if ( isset( $result['found'] ) ) {
3227 $found = $result['found'];
3228 }
3229 if ( array_key_exists( 'text', $result ) ) {
3230 // a string or null
3231 $text = $result['text'];
3232 }
3233 if ( isset( $result['nowiki'] ) ) {
3234 $nowiki = $result['nowiki'];
3235 }
3236 if ( isset( $result['isHTML'] ) ) {
3237 $isHTML = $result['isHTML'];
3238 }
3239 if ( isset( $result['forceRawInterwiki'] ) ) {
3240 $forceRawInterwiki = $result['forceRawInterwiki'];
3241 }
3242 if ( isset( $result['isChildObj'] ) ) {
3243 $isChildObj = $result['isChildObj'];
3244 }
3245 if ( isset( $result['isLocalObj'] ) ) {
3246 $isLocalObj = $result['isLocalObj'];
3247 }
3248 }
3249 }
3250
3251 # Finish mangling title and then check for loops.
3252 # Set $title to a Title object and $titleText to the PDBK
3253 if ( !$found ) {
3254 $ns = NS_TEMPLATE;
3255 # Split the title into page and subpage
3256 $subpage = '';
3257 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3258 if ( $part1 !== $relative ) {
3259 $part1 = $relative;
3260 $ns = $this->mTitle->getNamespace();
3261 }
3262 $title = Title::newFromText( $part1, $ns );
3263 if ( $title ) {
3264 $titleText = $title->getPrefixedText();
3265 # Check for language variants if the template is not found
3266 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3267 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3268 }
3269 # Do recursion depth check
3270 $limit = $this->mOptions->getMaxTemplateDepth();
3271 if ( $frame->depth >= $limit ) {
3272 $found = true;
3273 $text = '<span class="error">'
3274 . wfMessage( 'parser-template-recursion-depth-warning' )
3275 ->numParams( $limit )->inContentLanguage()->text()
3276 . '</span>';
3277 }
3278 }
3279 }
3280
3281 # Load from database
3282 if ( !$found && $title ) {
3283 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3284 if ( !$title->isExternal() ) {
3285 if ( $title->isSpecialPage()
3286 && $this->mOptions->getAllowSpecialInclusion()
3287 && $this->ot['html']
3288 ) {
3289 $specialPage = $this->specialPageFactory->getPage( $title->getDBkey() );
3290 // Pass the template arguments as URL parameters.
3291 // "uselang" will have no effect since the Language object
3292 // is forced to the one defined in ParserOptions.
3293 $pageArgs = [];
3294 $argsLength = $args->getLength();
3295 for ( $i = 0; $i < $argsLength; $i++ ) {
3296 $bits = $args->item( $i )->splitArg();
3297 if ( strval( $bits['index'] ) === '' ) {
3298 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3299 $value = trim( $frame->expand( $bits['value'] ) );
3300 $pageArgs[$name] = $value;
3301 }
3302 }
3303
3304 // Create a new context to execute the special page
3305 $context = new RequestContext;
3306 $context->setTitle( $title );
3307 $context->setRequest( new FauxRequest( $pageArgs ) );
3308 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3309 $context->setUser( $this->getUser() );
3310 } else {
3311 // If this page is cached, then we better not be per user.
3312 $context->setUser( User::newFromName( '127.0.0.1', false ) );
3313 }
3314 $context->setLanguage( $this->mOptions->getUserLangObj() );
3315 $ret = $this->specialPageFactory->capturePath( $title, $context, $this->getLinkRenderer() );
3316 if ( $ret ) {
3317 $text = $context->getOutput()->getHTML();
3318 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3319 $found = true;
3320 $isHTML = true;
3321 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3322 $this->mOutput->updateRuntimeAdaptiveExpiry(
3323 $specialPage->maxIncludeCacheTime()
3324 );
3325 }
3326 }
3327 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3328 $found = false; # access denied
3329 wfDebug( __METHOD__ . ": template inclusion denied for " .
3330 $title->getPrefixedDBkey() . "\n" );
3331 } else {
3332 list( $text, $title ) = $this->getTemplateDom( $title );
3333 if ( $text !== false ) {
3334 $found = true;
3335 $isChildObj = true;
3336 }
3337 }
3338
3339 # If the title is valid but undisplayable, make a link to it
3340 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3341 $text = "[[:$titleText]]";
3342 $found = true;
3343 }
3344 } elseif ( $title->isTrans() ) {
3345 # Interwiki transclusion
3346 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3347 $text = $this->interwikiTransclude( $title, 'render' );
3348 $isHTML = true;
3349 } else {
3350 $text = $this->interwikiTransclude( $title, 'raw' );
3351 # Preprocess it like a template
3352 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3353 $isChildObj = true;
3354 }
3355 $found = true;
3356 }
3357
3358 # Do infinite loop check
3359 # This has to be done after redirect resolution to avoid infinite loops via redirects
3360 if ( !$frame->loopCheck( $title ) ) {
3361 $found = true;
3362 $text = '<span class="error">'
3363 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3364 . '</span>';
3365 $this->addTrackingCategory( 'template-loop-category' );
3366 $this->mOutput->addWarning( wfMessage( 'template-loop-warning',
3367 wfEscapeWikiText( $titleText ) )->text() );
3368 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3369 }
3370 }
3371
3372 # If we haven't found text to substitute by now, we're done
3373 # Recover the source wikitext and return it
3374 if ( !$found ) {
3375 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3376 if ( $profileSection ) {
3377 $this->mProfiler->scopedProfileOut( $profileSection );
3378 }
3379 return [ 'object' => $text ];
3380 }
3381
3382 # Expand DOM-style return values in a child frame
3383 if ( $isChildObj ) {
3384 # Clean up argument array
3385 $newFrame = $frame->newChild( $args, $title );
3386
3387 if ( $nowiki ) {
3388 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3389 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3390 # Expansion is eligible for the empty-frame cache
3391 $text = $newFrame->cachedExpand( $titleText, $text );
3392 } else {
3393 # Uncached expansion
3394 $text = $newFrame->expand( $text );
3395 }
3396 }
3397 if ( $isLocalObj && $nowiki ) {
3398 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3399 $isLocalObj = false;
3400 }
3401
3402 if ( $profileSection ) {
3403 $this->mProfiler->scopedProfileOut( $profileSection );
3404 }
3405
3406 # Replace raw HTML by a placeholder
3407 if ( $isHTML ) {
3408 $text = $this->insertStripItem( $text );
3409 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3410 # Escape nowiki-style return values
3411 $text = wfEscapeWikiText( $text );
3412 } elseif ( is_string( $text )
3413 && !$piece['lineStart']
3414 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3415 ) {
3416 # T2529: if the template begins with a table or block-level
3417 # element, it should be treated as beginning a new line.
3418 # This behavior is somewhat controversial.
3419 $text = "\n" . $text;
3420 }
3421
3422 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3423 # Error, oversize inclusion
3424 if ( $titleText !== false ) {
3425 # Make a working, properly escaped link if possible (T25588)
3426 $text = "[[:$titleText]]";
3427 } else {
3428 # This will probably not be a working link, but at least it may
3429 # provide some hint of where the problem is
3430 preg_replace( '/^:/', '', $originalTitle );
3431 $text = "[[:$originalTitle]]";
3432 }
3433 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3434 . 'post-expand include size too large -->' );
3435 $this->limitationWarn( 'post-expand-template-inclusion' );
3436 }
3437
3438 if ( $isLocalObj ) {
3439 $ret = [ 'object' => $text ];
3440 } else {
3441 $ret = [ 'text' => $text ];
3442 }
3443
3444 return $ret;
3445 }
3446
3447 /**
3448 * Call a parser function and return an array with text and flags.
3449 *
3450 * The returned array will always contain a boolean 'found', indicating
3451 * whether the parser function was found or not. It may also contain the
3452 * following:
3453 * text: string|object, resulting wikitext or PP DOM object
3454 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3455 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3456 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3457 * nowiki: bool, wiki markup in $text should be escaped
3458 *
3459 * @since 1.21
3460 * @param PPFrame $frame The current frame, contains template arguments
3461 * @param string $function Function name
3462 * @param array $args Arguments to the function
3463 * @throws MWException
3464 * @return array
3465 */
3466 public function callParserFunction( $frame, $function, array $args = [] ) {
3467 # Case sensitive functions
3468 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3469 $function = $this->mFunctionSynonyms[1][$function];
3470 } else {
3471 # Case insensitive functions
3472 $function = $this->contLang->lc( $function );
3473 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3474 $function = $this->mFunctionSynonyms[0][$function];
3475 } else {
3476 return [ 'found' => false ];
3477 }
3478 }
3479
3480 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3481
3482 // Avoid PHP 7.1 warning from passing $this by reference
3483 $parser = $this;
3484
3485 $allArgs = [ &$parser ];
3486 if ( $flags & self::SFH_OBJECT_ARGS ) {
3487 # Convert arguments to PPNodes and collect for appending to $allArgs
3488 $funcArgs = [];
3489 foreach ( $args as $k => $v ) {
3490 if ( $v instanceof PPNode || $k === 0 ) {
3491 $funcArgs[] = $v;
3492 } else {
3493 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( [ $k => $v ] )->item( 0 );
3494 }
3495 }
3496
3497 # Add a frame parameter, and pass the arguments as an array
3498 $allArgs[] = $frame;
3499 $allArgs[] = $funcArgs;
3500 } else {
3501 # Convert arguments to plain text and append to $allArgs
3502 foreach ( $args as $k => $v ) {
3503 if ( $v instanceof PPNode ) {
3504 $allArgs[] = trim( $frame->expand( $v ) );
3505 } elseif ( is_int( $k ) && $k >= 0 ) {
3506 $allArgs[] = trim( $v );
3507 } else {
3508 $allArgs[] = trim( "$k=$v" );
3509 }
3510 }
3511 }
3512
3513 $result = $callback( ...$allArgs );
3514
3515 # The interface for function hooks allows them to return a wikitext
3516 # string or an array containing the string and any flags. This mungs
3517 # things around to match what this method should return.
3518 if ( !is_array( $result ) ) {
3519 $result = [
3520 'found' => true,
3521 'text' => $result,
3522 ];
3523 } else {
3524 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3525 $result['text'] = $result[0];
3526 }
3527 unset( $result[0] );
3528 $result += [
3529 'found' => true,
3530 ];
3531 }
3532
3533 $noparse = true;
3534 $preprocessFlags = 0;
3535 if ( isset( $result['noparse'] ) ) {
3536 $noparse = $result['noparse'];
3537 }
3538 if ( isset( $result['preprocessFlags'] ) ) {
3539 $preprocessFlags = $result['preprocessFlags'];
3540 }
3541
3542 if ( !$noparse ) {
3543 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3544 $result['isChildObj'] = true;
3545 }
3546
3547 return $result;
3548 }
3549
3550 /**
3551 * Get the semi-parsed DOM representation of a template with a given title,
3552 * and its redirect destination title. Cached.
3553 *
3554 * @param Title $title
3555 *
3556 * @return array
3557 */
3558 public function getTemplateDom( $title ) {
3559 $cacheTitle = $title;
3560 $titleText = $title->getPrefixedDBkey();
3561
3562 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3563 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3564 $title = Title::makeTitle( $ns, $dbk );
3565 $titleText = $title->getPrefixedDBkey();
3566 }
3567 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3568 return [ $this->mTplDomCache[$titleText], $title ];
3569 }
3570
3571 # Cache miss, go to the database
3572 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3573
3574 if ( $text === false ) {
3575 $this->mTplDomCache[$titleText] = false;
3576 return [ false, $title ];
3577 }
3578
3579 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3580 $this->mTplDomCache[$titleText] = $dom;
3581
3582 if ( !$title->equals( $cacheTitle ) ) {
3583 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3584 [ $title->getNamespace(), $title->getDBkey() ];
3585 }
3586
3587 return [ $dom, $title ];
3588 }
3589
3590 /**
3591 * Fetch the current revision of a given title. Note that the revision
3592 * (and even the title) may not exist in the database, so everything
3593 * contributing to the output of the parser should use this method
3594 * where possible, rather than getting the revisions themselves. This
3595 * method also caches its results, so using it benefits performance.
3596 *
3597 * @since 1.24
3598 * @param Title $title
3599 * @return Revision
3600 */
3601 public function fetchCurrentRevisionOfTitle( $title ) {
3602 $cacheKey = $title->getPrefixedDBkey();
3603 if ( !$this->currentRevisionCache ) {
3604 $this->currentRevisionCache = new MapCacheLRU( 100 );
3605 }
3606 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3607 $this->currentRevisionCache->set( $cacheKey,
3608 // Defaults to Parser::statelessFetchRevision()
3609 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3610 );
3611 }
3612 return $this->currentRevisionCache->get( $cacheKey );
3613 }
3614
3615 /**
3616 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3617 * without passing them on to it.
3618 *
3619 * @since 1.24
3620 * @param Title $title
3621 * @param Parser|bool $parser
3622 * @return Revision|bool False if missing
3623 */
3624 public static function statelessFetchRevision( Title $title, $parser = false ) {
3625 $rev = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
3626
3627 return $rev;
3628 }
3629
3630 /**
3631 * Fetch the unparsed text of a template and register a reference to it.
3632 * @param Title $title
3633 * @return array ( string or false, Title )
3634 */
3635 public function fetchTemplateAndTitle( $title ) {
3636 // Defaults to Parser::statelessFetchTemplate()
3637 $templateCb = $this->mOptions->getTemplateCallback();
3638 $stuff = call_user_func( $templateCb, $title, $this );
3639 // We use U+007F DELETE to distinguish strip markers from regular text.
3640 $text = $stuff['text'];
3641 if ( is_string( $stuff['text'] ) ) {
3642 $text = strtr( $text, "\x7f", "?" );
3643 }
3644 $finalTitle = $stuff['finalTitle'] ?? $title;
3645 if ( isset( $stuff['deps'] ) ) {
3646 foreach ( $stuff['deps'] as $dep ) {
3647 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3648 if ( $dep['title']->equals( $this->getTitle() ) ) {
3649 // If we transclude ourselves, the final result
3650 // will change based on the new version of the page
3651 $this->mOutput->setFlag( 'vary-revision' );
3652 }
3653 }
3654 }
3655 return [ $text, $finalTitle ];
3656 }
3657
3658 /**
3659 * Fetch the unparsed text of a template and register a reference to it.
3660 * @param Title $title
3661 * @return string|bool
3662 */
3663 public function fetchTemplate( $title ) {
3664 return $this->fetchTemplateAndTitle( $title )[0];
3665 }
3666
3667 /**
3668 * Static function to get a template
3669 * Can be overridden via ParserOptions::setTemplateCallback().
3670 *
3671 * @param Title $title
3672 * @param bool|Parser $parser
3673 *
3674 * @return array
3675 */
3676 public static function statelessFetchTemplate( $title, $parser = false ) {
3677 $text = $skip = false;
3678 $finalTitle = $title;
3679 $deps = [];
3680
3681 # Loop to fetch the article, with up to 1 redirect
3682 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3683 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3684 # Give extensions a chance to select the revision instead
3685 $id = false; # Assume current
3686 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3687 [ $parser, $title, &$skip, &$id ] );
3688
3689 if ( $skip ) {
3690 $text = false;
3691 $deps[] = [
3692 'title' => $title,
3693 'page_id' => $title->getArticleID(),
3694 'rev_id' => null
3695 ];
3696 break;
3697 }
3698 # Get the revision
3699 if ( $id ) {
3700 $rev = Revision::newFromId( $id );
3701 } elseif ( $parser ) {
3702 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3703 } else {
3704 $rev = Revision::newFromTitle( $title );
3705 }
3706 $rev_id = $rev ? $rev->getId() : 0;
3707 # If there is no current revision, there is no page
3708 if ( $id === false && !$rev ) {
3709 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3710 $linkCache->addBadLinkObj( $title );
3711 }
3712
3713 $deps[] = [
3714 'title' => $title,
3715 'page_id' => $title->getArticleID(),
3716 'rev_id' => $rev_id ];
3717 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3718 # We fetched a rev from a different title; register it too...
3719 $deps[] = [
3720 'title' => $rev->getTitle(),
3721 'page_id' => $rev->getPage(),
3722 'rev_id' => $rev_id ];
3723 }
3724
3725 if ( $rev ) {
3726 $content = $rev->getContent();
3727 $text = $content ? $content->getWikitextForTransclusion() : null;
3728
3729 Hooks::run( 'ParserFetchTemplate',
3730 [ $parser, $title, $rev, &$text, &$deps ] );
3731
3732 if ( $text === false || $text === null ) {
3733 $text = false;
3734 break;
3735 }
3736 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3737 $message = wfMessage( MediaWikiServices::getInstance()->getContentLanguage()->
3738 lcfirst( $title->getText() ) )->inContentLanguage();
3739 if ( !$message->exists() ) {
3740 $text = false;
3741 break;
3742 }
3743 $content = $message->content();
3744 $text = $message->plain();
3745 } else {
3746 break;
3747 }
3748 if ( !$content ) {
3749 break;
3750 }
3751 # Redirect?
3752 $finalTitle = $title;
3753 $title = $content->getRedirectTarget();
3754 }
3755 return [
3756 'text' => $text,
3757 'finalTitle' => $finalTitle,
3758 'deps' => $deps ];
3759 }
3760
3761 /**
3762 * Fetch a file and its title and register a reference to it.
3763 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3764 * @param Title $title
3765 * @param array $options Array of options to RepoGroup::findFile
3766 * @return File|bool
3767 * @deprecated since 1.32, use fetchFileAndTitle instead
3768 */
3769 public function fetchFile( $title, $options = [] ) {
3770 wfDeprecated( __METHOD__, '1.32' );
3771 return $this->fetchFileAndTitle( $title, $options )[0];
3772 }
3773
3774 /**
3775 * Fetch a file and its title and register a reference to it.
3776 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3777 * @param Title $title
3778 * @param array $options Array of options to RepoGroup::findFile
3779 * @return array ( File or false, Title of file )
3780 */
3781 public function fetchFileAndTitle( $title, $options = [] ) {
3782 $file = $this->fetchFileNoRegister( $title, $options );
3783
3784 $time = $file ? $file->getTimestamp() : false;
3785 $sha1 = $file ? $file->getSha1() : false;
3786 # Register the file as a dependency...
3787 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3788 if ( $file && !$title->equals( $file->getTitle() ) ) {
3789 # Update fetched file title
3790 $title = $file->getTitle();
3791 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3792 }
3793 return [ $file, $title ];
3794 }
3795
3796 /**
3797 * Helper function for fetchFileAndTitle.
3798 *
3799 * Also useful if you need to fetch a file but not use it yet,
3800 * for example to get the file's handler.
3801 *
3802 * @param Title $title
3803 * @param array $options Array of options to RepoGroup::findFile
3804 * @return File|bool
3805 */
3806 protected function fetchFileNoRegister( $title, $options = [] ) {
3807 if ( isset( $options['broken'] ) ) {
3808 $file = false; // broken thumbnail forced by hook
3809 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3810 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3811 } else { // get by (name,timestamp)
3812 $file = wfFindFile( $title, $options );
3813 }
3814 return $file;
3815 }
3816
3817 /**
3818 * Transclude an interwiki link.
3819 *
3820 * @param Title $title
3821 * @param string $action Usually one of (raw, render)
3822 *
3823 * @return string
3824 */
3825 public function interwikiTransclude( $title, $action ) {
3826 if ( !$this->siteConfig->get( 'EnableScaryTranscluding' ) ) {
3827 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3828 }
3829
3830 $url = $title->getFullURL( [ 'action' => $action ] );
3831 if ( strlen( $url ) > 1024 ) {
3832 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3833 }
3834
3835 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3836
3837 $fname = __METHOD__;
3838 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
3839
3840 $data = $cache->getWithSetCallback(
3841 $cache->makeGlobalKey(
3842 'interwiki-transclude',
3843 ( $wikiId !== false ) ? $wikiId : 'external',
3844 sha1( $url )
3845 ),
3846 $this->siteConfig->get( 'TranscludeCacheExpiry' ),
3847 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3848 $req = MWHttpRequest::factory( $url, [], $fname );
3849
3850 $status = $req->execute(); // Status object
3851 if ( !$status->isOK() ) {
3852 $ttl = $cache::TTL_UNCACHEABLE;
3853 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3854 $ttl = min( $cache::TTL_LAGGED, $ttl );
3855 }
3856
3857 return [
3858 'text' => $status->isOK() ? $req->getContent() : null,
3859 'code' => $req->getStatus()
3860 ];
3861 },
3862 [
3863 'checkKeys' => ( $wikiId !== false )
3864 ? [ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
3865 : [],
3866 'pcGroup' => 'interwiki-transclude:5',
3867 'pcTTL' => $cache::TTL_PROC_LONG
3868 ]
3869 );
3870
3871 if ( is_string( $data['text'] ) ) {
3872 $text = $data['text'];
3873 } elseif ( $data['code'] != 200 ) {
3874 // Though we failed to fetch the content, this status is useless.
3875 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
3876 ->params( $url, $data['code'] )->inContentLanguage()->text();
3877 } else {
3878 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3879 }
3880
3881 return $text;
3882 }
3883
3884 /**
3885 * Triple brace replacement -- used for template arguments
3886 * @private
3887 *
3888 * @param array $piece
3889 * @param PPFrame $frame
3890 *
3891 * @return array
3892 */
3893 public function argSubstitution( $piece, $frame ) {
3894 $error = false;
3895 $parts = $piece['parts'];
3896 $nameWithSpaces = $frame->expand( $piece['title'] );
3897 $argName = trim( $nameWithSpaces );
3898 $object = false;
3899 $text = $frame->getArgument( $argName );
3900 if ( $text === false && $parts->getLength() > 0
3901 && ( $this->ot['html']
3902 || $this->ot['pre']
3903 || ( $this->ot['wiki'] && $frame->isTemplate() )
3904 )
3905 ) {
3906 # No match in frame, use the supplied default
3907 $object = $parts->item( 0 )->getChildren();
3908 }
3909 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3910 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3911 $this->limitationWarn( 'post-expand-template-argument' );
3912 }
3913
3914 if ( $text === false && $object === false ) {
3915 # No match anywhere
3916 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3917 }
3918 if ( $error !== false ) {
3919 $text .= $error;
3920 }
3921 if ( $object !== false ) {
3922 $ret = [ 'object' => $object ];
3923 } else {
3924 $ret = [ 'text' => $text ];
3925 }
3926
3927 return $ret;
3928 }
3929
3930 /**
3931 * Return the text to be used for a given extension tag.
3932 * This is the ghost of strip().
3933 *
3934 * @param array $params Associative array of parameters:
3935 * name PPNode for the tag name
3936 * attr PPNode for unparsed text where tag attributes are thought to be
3937 * attributes Optional associative array of parsed attributes
3938 * inner Contents of extension element
3939 * noClose Original text did not have a close tag
3940 * @param PPFrame $frame
3941 *
3942 * @throws MWException
3943 * @return string
3944 */
3945 public function extensionSubstitution( $params, $frame ) {
3946 static $errorStr = '<span class="error">';
3947 static $errorLen = 20;
3948
3949 $name = $frame->expand( $params['name'] );
3950 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3951 // Probably expansion depth or node count exceeded. Just punt the
3952 // error up.
3953 return $name;
3954 }
3955
3956 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3957 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3958 // See above
3959 return $attrText;
3960 }
3961
3962 // We can't safely check if the expansion for $content resulted in an
3963 // error, because the content could happen to be the error string
3964 // (T149622).
3965 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3966
3967 $marker = self::MARKER_PREFIX . "-$name-"
3968 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3969
3970 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3971 ( $this->ot['html'] || $this->ot['pre'] );
3972 if ( $isFunctionTag ) {
3973 $markerType = 'none';
3974 } else {
3975 $markerType = 'general';
3976 }
3977 if ( $this->ot['html'] || $isFunctionTag ) {
3978 $name = strtolower( $name );
3979 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3980 if ( isset( $params['attributes'] ) ) {
3981 $attributes = $attributes + $params['attributes'];
3982 }
3983
3984 if ( isset( $this->mTagHooks[$name] ) ) {
3985 $output = call_user_func_array( $this->mTagHooks[$name],
3986 [ $content, $attributes, $this, $frame ] );
3987 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3988 list( $callback, ) = $this->mFunctionTagHooks[$name];
3989
3990 // Avoid PHP 7.1 warning from passing $this by reference
3991 $parser = $this;
3992 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3993 } else {
3994 $output = '<span class="error">Invalid tag extension name: ' .
3995 htmlspecialchars( $name ) . '</span>';
3996 }
3997
3998 if ( is_array( $output ) ) {
3999 // Extract flags
4000 $flags = $output;
4001 $output = $flags[0];
4002 if ( isset( $flags['markerType'] ) ) {
4003 $markerType = $flags['markerType'];
4004 }
4005 }
4006 } else {
4007 if ( is_null( $attrText ) ) {
4008 $attrText = '';
4009 }
4010 if ( isset( $params['attributes'] ) ) {
4011 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4012 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4013 htmlspecialchars( $attrValue ) . '"';
4014 }
4015 }
4016 if ( $content === null ) {
4017 $output = "<$name$attrText/>";
4018 } else {
4019 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4020 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4021 // See above
4022 return $close;
4023 }
4024 $output = "<$name$attrText>$content$close";
4025 }
4026 }
4027
4028 if ( $markerType === 'none' ) {
4029 return $output;
4030 } elseif ( $markerType === 'nowiki' ) {
4031 $this->mStripState->addNoWiki( $marker, $output );
4032 } elseif ( $markerType === 'general' ) {
4033 $this->mStripState->addGeneral( $marker, $output );
4034 } else {
4035 throw new MWException( __METHOD__ . ': invalid marker type' );
4036 }
4037 return $marker;
4038 }
4039
4040 /**
4041 * Increment an include size counter
4042 *
4043 * @param string $type The type of expansion
4044 * @param int $size The size of the text
4045 * @return bool False if this inclusion would take it over the maximum, true otherwise
4046 */
4047 public function incrementIncludeSize( $type, $size ) {
4048 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4049 return false;
4050 } else {
4051 $this->mIncludeSizes[$type] += $size;
4052 return true;
4053 }
4054 }
4055
4056 /**
4057 * Increment the expensive function count
4058 *
4059 * @return bool False if the limit has been exceeded
4060 */
4061 public function incrementExpensiveFunctionCount() {
4062 $this->mExpensiveFunctionCount++;
4063 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4064 }
4065
4066 /**
4067 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4068 * Fills $this->mDoubleUnderscores, returns the modified text
4069 *
4070 * @param string $text
4071 *
4072 * @return string
4073 */
4074 public function doDoubleUnderscore( $text ) {
4075 # The position of __TOC__ needs to be recorded
4076 $mw = $this->magicWordFactory->get( 'toc' );
4077 if ( $mw->match( $text ) ) {
4078 $this->mShowToc = true;
4079 $this->mForceTocPosition = true;
4080
4081 # Set a placeholder. At the end we'll fill it in with the TOC.
4082 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4083
4084 # Only keep the first one.
4085 $text = $mw->replace( '', $text );
4086 }
4087
4088 # Now match and remove the rest of them
4089 $mwa = $this->magicWordFactory->getDoubleUnderscoreArray();
4090 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4091
4092 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4093 $this->mOutput->mNoGallery = true;
4094 }
4095 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4096 $this->mShowToc = false;
4097 }
4098 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4099 && $this->mTitle->getNamespace() == NS_CATEGORY
4100 ) {
4101 $this->addTrackingCategory( 'hidden-category-category' );
4102 }
4103 # (T10068) Allow control over whether robots index a page.
4104 # __INDEX__ always overrides __NOINDEX__, see T16899
4105 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4106 $this->mOutput->setIndexPolicy( 'noindex' );
4107 $this->addTrackingCategory( 'noindex-category' );
4108 }
4109 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4110 $this->mOutput->setIndexPolicy( 'index' );
4111 $this->addTrackingCategory( 'index-category' );
4112 }
4113
4114 # Cache all double underscores in the database
4115 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4116 $this->mOutput->setProperty( $key, '' );
4117 }
4118
4119 return $text;
4120 }
4121
4122 /**
4123 * @see ParserOutput::addTrackingCategory()
4124 * @param string $msg Message key
4125 * @return bool Whether the addition was successful
4126 */
4127 public function addTrackingCategory( $msg ) {
4128 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4129 }
4130
4131 /**
4132 * This function accomplishes several tasks:
4133 * 1) Auto-number headings if that option is enabled
4134 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4135 * 3) Add a Table of contents on the top for users who have enabled the option
4136 * 4) Auto-anchor headings
4137 *
4138 * It loops through all headlines, collects the necessary data, then splits up the
4139 * string and re-inserts the newly formatted headlines.
4140 *
4141 * @param string $text
4142 * @param string $origText Original, untouched wikitext
4143 * @param bool $isMain
4144 * @return mixed|string
4145 * @private
4146 */
4147 public function formatHeadings( $text, $origText, $isMain = true ) {
4148 # Inhibit editsection links if requested in the page
4149 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4150 $maybeShowEditLink = false;
4151 } else {
4152 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4153 }
4154
4155 # Get all headlines for numbering them and adding funky stuff like [edit]
4156 # links - this is for later, but we need the number of headlines right now
4157 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4158 # be trimmed here since whitespace in HTML headings is significant.
4159 $matches = [];
4160 $numMatches = preg_match_all(
4161 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4162 $text,
4163 $matches
4164 );
4165
4166 # if there are fewer than 4 headlines in the article, do not show TOC
4167 # unless it's been explicitly enabled.
4168 $enoughToc = $this->mShowToc &&
4169 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4170
4171 # Allow user to stipulate that a page should have a "new section"
4172 # link added via __NEWSECTIONLINK__
4173 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4174 $this->mOutput->setNewSection( true );
4175 }
4176
4177 # Allow user to remove the "new section"
4178 # link via __NONEWSECTIONLINK__
4179 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4180 $this->mOutput->hideNewSection( true );
4181 }
4182
4183 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4184 # override above conditions and always show TOC above first header
4185 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4186 $this->mShowToc = true;
4187 $enoughToc = true;
4188 }
4189
4190 # headline counter
4191 $headlineCount = 0;
4192 $numVisible = 0;
4193
4194 # Ugh .. the TOC should have neat indentation levels which can be
4195 # passed to the skin functions. These are determined here
4196 $toc = '';
4197 $full = '';
4198 $head = [];
4199 $sublevelCount = [];
4200 $levelCount = [];
4201 $level = 0;
4202 $prevlevel = 0;
4203 $toclevel = 0;
4204 $prevtoclevel = 0;
4205 $markerRegex = self::MARKER_PREFIX . "-h-(\d+)-" . self::MARKER_SUFFIX;
4206 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4207 $oldType = $this->mOutputType;
4208 $this->setOutputType( self::OT_WIKI );
4209 $frame = $this->getPreprocessor()->newFrame();
4210 $root = $this->preprocessToDom( $origText );
4211 $node = $root->getFirstChild();
4212 $byteOffset = 0;
4213 $tocraw = [];
4214 $refers = [];
4215
4216 $headlines = $numMatches !== false ? $matches[3] : [];
4217
4218 $maxTocLevel = $this->siteConfig->get( 'MaxTocLevel' );
4219 foreach ( $headlines as $headline ) {
4220 $isTemplate = false;
4221 $titleText = false;
4222 $sectionIndex = false;
4223 $numbering = '';
4224 $markerMatches = [];
4225 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4226 $serial = $markerMatches[1];
4227 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4228 $isTemplate = ( $titleText != $baseTitleText );
4229 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4230 }
4231
4232 if ( $toclevel ) {
4233 $prevlevel = $level;
4234 }
4235 $level = $matches[1][$headlineCount];
4236
4237 if ( $level > $prevlevel ) {
4238 # Increase TOC level
4239 $toclevel++;
4240 $sublevelCount[$toclevel] = 0;
4241 if ( $toclevel < $maxTocLevel ) {
4242 $prevtoclevel = $toclevel;
4243 $toc .= Linker::tocIndent();
4244 $numVisible++;
4245 }
4246 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4247 # Decrease TOC level, find level to jump to
4248
4249 for ( $i = $toclevel; $i > 0; $i-- ) {
4250 if ( $levelCount[$i] == $level ) {
4251 # Found last matching level
4252 $toclevel = $i;
4253 break;
4254 } elseif ( $levelCount[$i] < $level ) {
4255 # Found first matching level below current level
4256 $toclevel = $i + 1;
4257 break;
4258 }
4259 }
4260 if ( $i == 0 ) {
4261 $toclevel = 1;
4262 }
4263 if ( $toclevel < $maxTocLevel ) {
4264 if ( $prevtoclevel < $maxTocLevel ) {
4265 # Unindent only if the previous toc level was shown :p
4266 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4267 $prevtoclevel = $toclevel;
4268 } else {
4269 $toc .= Linker::tocLineEnd();
4270 }
4271 }
4272 } else {
4273 # No change in level, end TOC line
4274 if ( $toclevel < $maxTocLevel ) {
4275 $toc .= Linker::tocLineEnd();
4276 }
4277 }
4278
4279 $levelCount[$toclevel] = $level;
4280
4281 # count number of headlines for each level
4282 $sublevelCount[$toclevel]++;
4283 $dot = 0;
4284 for ( $i = 1; $i <= $toclevel; $i++ ) {
4285 if ( !empty( $sublevelCount[$i] ) ) {
4286 if ( $dot ) {
4287 $numbering .= '.';
4288 }
4289 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4290 $dot = 1;
4291 }
4292 }
4293
4294 # The safe header is a version of the header text safe to use for links
4295
4296 # Remove link placeholders by the link text.
4297 # <!--LINK number-->
4298 # turns into
4299 # link text with suffix
4300 # Do this before unstrip since link text can contain strip markers
4301 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4302
4303 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4304 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4305
4306 # Remove any <style> or <script> tags (T198618)
4307 $safeHeadline = preg_replace(
4308 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4309 '',
4310 $safeHeadline
4311 );
4312
4313 # Strip out HTML (first regex removes any tag not allowed)
4314 # Allowed tags are:
4315 # * <sup> and <sub> (T10393)
4316 # * <i> (T28375)
4317 # * <b> (r105284)
4318 # * <bdi> (T74884)
4319 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4320 # * <s> and <strike> (T35715)
4321 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4322 # to allow setting directionality in toc items.
4323 $tocline = preg_replace(
4324 [
4325 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4326 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4327 ],
4328 [ '', '<$1>' ],
4329 $safeHeadline
4330 );
4331
4332 # Strip '<span></span>', which is the result from the above if
4333 # <span id="foo"></span> is used to produce an additional anchor
4334 # for a section.
4335 $tocline = str_replace( '<span></span>', '', $tocline );
4336
4337 $tocline = trim( $tocline );
4338
4339 # For the anchor, strip out HTML-y stuff period
4340 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4341 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4342
4343 # Save headline for section edit hint before it's escaped
4344 $headlineHint = $safeHeadline;
4345
4346 # Decode HTML entities
4347 $safeHeadline = Sanitizer::decodeCharReferences( $safeHeadline );
4348
4349 $safeHeadline = self::normalizeSectionName( $safeHeadline );
4350
4351 $fallbackHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_FALLBACK );
4352 $linkAnchor = Sanitizer::escapeIdForLink( $safeHeadline );
4353 $safeHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_PRIMARY );
4354 if ( $fallbackHeadline === $safeHeadline ) {
4355 # No reason to have both (in fact, we can't)
4356 $fallbackHeadline = false;
4357 }
4358
4359 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4360 # @todo FIXME: We may be changing them depending on the current locale.
4361 $arrayKey = strtolower( $safeHeadline );
4362 if ( $fallbackHeadline === false ) {
4363 $fallbackArrayKey = false;
4364 } else {
4365 $fallbackArrayKey = strtolower( $fallbackHeadline );
4366 }
4367
4368 # Create the anchor for linking from the TOC to the section
4369 $anchor = $safeHeadline;
4370 $fallbackAnchor = $fallbackHeadline;
4371 if ( isset( $refers[$arrayKey] ) ) {
4372 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4373 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++$i );
4374 $anchor .= "_$i";
4375 $linkAnchor .= "_$i";
4376 $refers["${arrayKey}_$i"] = true;
4377 } else {
4378 $refers[$arrayKey] = true;
4379 }
4380 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4381 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4382 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++$i );
4383 $fallbackAnchor .= "_$i";
4384 $refers["${fallbackArrayKey}_$i"] = true;
4385 } else {
4386 $refers[$fallbackArrayKey] = true;
4387 }
4388
4389 # Don't number the heading if it is the only one (looks silly)
4390 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4391 # the two are different if the line contains a link
4392 $headline = Html::element(
4393 'span',
4394 [ 'class' => 'mw-headline-number' ],
4395 $numbering
4396 ) . ' ' . $headline;
4397 }
4398
4399 if ( $enoughToc && ( !isset( $maxTocLevel ) || $toclevel < $maxTocLevel ) ) {
4400 $toc .= Linker::tocLine( $linkAnchor, $tocline,
4401 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4402 }
4403
4404 # Add the section to the section tree
4405 # Find the DOM node for this header
4406 $noOffset = ( $isTemplate || $sectionIndex === false );
4407 while ( $node && !$noOffset ) {
4408 if ( $node->getName() === 'h' ) {
4409 $bits = $node->splitHeading();
4410 if ( $bits['i'] == $sectionIndex ) {
4411 break;
4412 }
4413 }
4414 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4415 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4416 $node = $node->getNextSibling();
4417 }
4418 $tocraw[] = [
4419 'toclevel' => $toclevel,
4420 'level' => $level,
4421 'line' => $tocline,
4422 'number' => $numbering,
4423 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4424 'fromtitle' => $titleText,
4425 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4426 'anchor' => $anchor,
4427 ];
4428
4429 # give headline the correct <h#> tag
4430 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4431 // Output edit section links as markers with styles that can be customized by skins
4432 if ( $isTemplate ) {
4433 # Put a T flag in the section identifier, to indicate to extractSections()
4434 # that sections inside <includeonly> should be counted.
4435 $editsectionPage = $titleText;
4436 $editsectionSection = "T-$sectionIndex";
4437 $editsectionContent = null;
4438 } else {
4439 $editsectionPage = $this->mTitle->getPrefixedText();
4440 $editsectionSection = $sectionIndex;
4441 $editsectionContent = $headlineHint;
4442 }
4443 // We use a bit of pesudo-xml for editsection markers. The
4444 // language converter is run later on. Using a UNIQ style marker
4445 // leads to the converter screwing up the tokens when it
4446 // converts stuff. And trying to insert strip tags fails too. At
4447 // this point all real inputted tags have already been escaped,
4448 // so we don't have to worry about a user trying to input one of
4449 // these markers directly. We use a page and section attribute
4450 // to stop the language converter from converting these
4451 // important bits of data, but put the headline hint inside a
4452 // content block because the language converter is supposed to
4453 // be able to convert that piece of data.
4454 // Gets replaced with html in ParserOutput::getText
4455 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4456 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4457 if ( $editsectionContent !== null ) {
4458 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4459 } else {
4460 $editlink .= '/>';
4461 }
4462 } else {
4463 $editlink = '';
4464 }
4465 $head[$headlineCount] = Linker::makeHeadline( $level,
4466 $matches['attrib'][$headlineCount], $anchor, $headline,
4467 $editlink, $fallbackAnchor );
4468
4469 $headlineCount++;
4470 }
4471
4472 $this->setOutputType( $oldType );
4473
4474 # Never ever show TOC if no headers
4475 if ( $numVisible < 1 ) {
4476 $enoughToc = false;
4477 }
4478
4479 if ( $enoughToc ) {
4480 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4481 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4482 }
4483 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4484 $this->mOutput->setTOCHTML( $toc );
4485 $toc = self::TOC_START . $toc . self::TOC_END;
4486 }
4487
4488 if ( $isMain ) {
4489 $this->mOutput->setSections( $tocraw );
4490 }
4491
4492 # split up and insert constructed headlines
4493 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4494 $i = 0;
4495
4496 // build an array of document sections
4497 $sections = [];
4498 foreach ( $blocks as $block ) {
4499 // $head is zero-based, sections aren't.
4500 if ( empty( $head[$i - 1] ) ) {
4501 $sections[$i] = $block;
4502 } else {
4503 $sections[$i] = $head[$i - 1] . $block;
4504 }
4505
4506 /**
4507 * Send a hook, one per section.
4508 * The idea here is to be able to make section-level DIVs, but to do so in a
4509 * lower-impact, more correct way than r50769
4510 *
4511 * $this : caller
4512 * $section : the section number
4513 * &$sectionContent : ref to the content of the section
4514 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4515 */
4516 Hooks::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4517
4518 $i++;
4519 }
4520
4521 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4522 // append the TOC at the beginning
4523 // Top anchor now in skin
4524 $sections[0] = $sections[0] . $toc . "\n";
4525 }
4526
4527 $full .= implode( '', $sections );
4528
4529 if ( $this->mForceTocPosition ) {
4530 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4531 } else {
4532 return $full;
4533 }
4534 }
4535
4536 /**
4537 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4538 * conversion, substituting signatures, {{subst:}} templates, etc.
4539 *
4540 * @param string $text The text to transform
4541 * @param Title $title The Title object for the current article
4542 * @param User $user The User object describing the current user
4543 * @param ParserOptions $options Parsing options
4544 * @param bool $clearState Whether to clear the parser state first
4545 * @return string The altered wiki markup
4546 */
4547 public function preSaveTransform( $text, Title $title, User $user,
4548 ParserOptions $options, $clearState = true
4549 ) {
4550 if ( $clearState ) {
4551 $magicScopeVariable = $this->lock();
4552 }
4553 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4554 $this->setUser( $user );
4555
4556 // Strip U+0000 NULL (T159174)
4557 $text = str_replace( "\000", '', $text );
4558
4559 // We still normalize line endings for backwards-compatibility
4560 // with other code that just calls PST, but this should already
4561 // be handled in TextContent subclasses
4562 $text = TextContent::normalizeLineEndings( $text );
4563
4564 if ( $options->getPreSaveTransform() ) {
4565 $text = $this->pstPass2( $text, $user );
4566 }
4567 $text = $this->mStripState->unstripBoth( $text );
4568
4569 $this->setUser( null ); # Reset
4570
4571 return $text;
4572 }
4573
4574 /**
4575 * Pre-save transform helper function
4576 *
4577 * @param string $text
4578 * @param User $user
4579 *
4580 * @return string
4581 */
4582 private function pstPass2( $text, $user ) {
4583 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4584 # $this->contLang here in order to give everyone the same signature and use the default one
4585 # rather than the one selected in each user's preferences. (see also T14815)
4586 $ts = $this->mOptions->getTimestamp();
4587 $timestamp = MWTimestamp::getLocalInstance( $ts );
4588 $ts = $timestamp->format( 'YmdHis' );
4589 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4590
4591 $d = $this->contLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4592
4593 # Variable replacement
4594 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4595 $text = $this->replaceVariables( $text );
4596
4597 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4598 # which may corrupt this parser instance via its wfMessage()->text() call-
4599
4600 # Signatures
4601 if ( strpos( $text, '~~~' ) !== false ) {
4602 $sigText = $this->getUserSig( $user );
4603 $text = strtr( $text, [
4604 '~~~~~' => $d,
4605 '~~~~' => "$sigText $d",
4606 '~~~' => $sigText
4607 ] );
4608 # The main two signature forms used above are time-sensitive
4609 $this->mOutput->setFlag( 'user-signature' );
4610 }
4611
4612 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4613 $tc = '[' . Title::legalChars() . ']';
4614 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4615
4616 // [[ns:page (context)|]]
4617 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4618 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4619 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4620 // [[ns:page (context), context|]] (using either single or double-width comma)
4621 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4622 // [[|page]] (reverse pipe trick: add context from page title)
4623 $p2 = "/\[\[\\|($tc+)]]/";
4624
4625 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4626 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4627 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4628 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4629
4630 $t = $this->mTitle->getText();
4631 $m = [];
4632 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4633 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4634 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4635 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4636 } else {
4637 # if there's no context, don't bother duplicating the title
4638 $text = preg_replace( $p2, '[[\\1]]', $text );
4639 }
4640
4641 return $text;
4642 }
4643
4644 /**
4645 * Fetch the user's signature text, if any, and normalize to
4646 * validated, ready-to-insert wikitext.
4647 * If you have pre-fetched the nickname or the fancySig option, you can
4648 * specify them here to save a database query.
4649 * Do not reuse this parser instance after calling getUserSig(),
4650 * as it may have changed if it's the $wgParser.
4651 *
4652 * @param User &$user
4653 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4654 * @param bool|null $fancySig whether the nicknname is the complete signature
4655 * or null to use default value
4656 * @return string
4657 */
4658 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4659 $username = $user->getName();
4660
4661 # If not given, retrieve from the user object.
4662 if ( $nickname === false ) {
4663 $nickname = $user->getOption( 'nickname' );
4664 }
4665
4666 if ( is_null( $fancySig ) ) {
4667 $fancySig = $user->getBoolOption( 'fancysig' );
4668 }
4669
4670 $nickname = $nickname == null ? $username : $nickname;
4671
4672 if ( mb_strlen( $nickname ) > $this->siteConfig->get( 'MaxSigChars' ) ) {
4673 $nickname = $username;
4674 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4675 } elseif ( $fancySig !== false ) {
4676 # Sig. might contain markup; validate this
4677 if ( $this->validateSig( $nickname ) !== false ) {
4678 # Validated; clean up (if needed) and return it
4679 return $this->cleanSig( $nickname, true );
4680 } else {
4681 # Failed to validate; fall back to the default
4682 $nickname = $username;
4683 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4684 }
4685 }
4686
4687 # Make sure nickname doesnt get a sig in a sig
4688 $nickname = self::cleanSigInSig( $nickname );
4689
4690 # If we're still here, make it a link to the user page
4691 $userText = wfEscapeWikiText( $username );
4692 $nickText = wfEscapeWikiText( $nickname );
4693 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4694
4695 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4696 ->title( $this->getTitle() )->text();
4697 }
4698
4699 /**
4700 * Check that the user's signature contains no bad XML
4701 *
4702 * @param string $text
4703 * @return string|bool An expanded string, or false if invalid.
4704 */
4705 public function validateSig( $text ) {
4706 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4707 }
4708
4709 /**
4710 * Clean up signature text
4711 *
4712 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4713 * 2) Substitute all transclusions
4714 *
4715 * @param string $text
4716 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4717 * @return string Signature text
4718 */
4719 public function cleanSig( $text, $parsing = false ) {
4720 if ( !$parsing ) {
4721 global $wgTitle;
4722 $magicScopeVariable = $this->lock();
4723 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4724 }
4725
4726 # Option to disable this feature
4727 if ( !$this->mOptions->getCleanSignatures() ) {
4728 return $text;
4729 }
4730
4731 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4732 # => Move this logic to braceSubstitution()
4733 $substWord = $this->magicWordFactory->get( 'subst' );
4734 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4735 $substText = '{{' . $substWord->getSynonym( 0 );
4736
4737 $text = preg_replace( $substRegex, $substText, $text );
4738 $text = self::cleanSigInSig( $text );
4739 $dom = $this->preprocessToDom( $text );
4740 $frame = $this->getPreprocessor()->newFrame();
4741 $text = $frame->expand( $dom );
4742
4743 if ( !$parsing ) {
4744 $text = $this->mStripState->unstripBoth( $text );
4745 }
4746
4747 return $text;
4748 }
4749
4750 /**
4751 * Strip 3, 4 or 5 tildes out of signatures.
4752 *
4753 * @param string $text
4754 * @return string Signature text with /~{3,5}/ removed
4755 */
4756 public static function cleanSigInSig( $text ) {
4757 $text = preg_replace( '/~{3,5}/', '', $text );
4758 return $text;
4759 }
4760
4761 /**
4762 * Set up some variables which are usually set up in parse()
4763 * so that an external function can call some class members with confidence
4764 *
4765 * @param Title|null $title
4766 * @param ParserOptions $options
4767 * @param int $outputType
4768 * @param bool $clearState
4769 */
4770 public function startExternalParse( Title $title = null, ParserOptions $options,
4771 $outputType, $clearState = true
4772 ) {
4773 $this->startParse( $title, $options, $outputType, $clearState );
4774 }
4775
4776 /**
4777 * @param Title|null $title
4778 * @param ParserOptions $options
4779 * @param int $outputType
4780 * @param bool $clearState
4781 */
4782 private function startParse( Title $title = null, ParserOptions $options,
4783 $outputType, $clearState = true
4784 ) {
4785 $this->setTitle( $title );
4786 $this->mOptions = $options;
4787 $this->setOutputType( $outputType );
4788 if ( $clearState ) {
4789 $this->clearState();
4790 }
4791 }
4792
4793 /**
4794 * Wrapper for preprocess()
4795 *
4796 * @param string $text The text to preprocess
4797 * @param ParserOptions $options
4798 * @param Title|null $title Title object or null to use $wgTitle
4799 * @return string
4800 */
4801 public function transformMsg( $text, $options, $title = null ) {
4802 static $executing = false;
4803
4804 # Guard against infinite recursion
4805 if ( $executing ) {
4806 return $text;
4807 }
4808 $executing = true;
4809
4810 if ( !$title ) {
4811 global $wgTitle;
4812 $title = $wgTitle;
4813 }
4814
4815 $text = $this->preprocess( $text, $title, $options );
4816
4817 $executing = false;
4818 return $text;
4819 }
4820
4821 /**
4822 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4823 * The callback should have the following form:
4824 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4825 *
4826 * Transform and return $text. Use $parser for any required context, e.g. use
4827 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4828 *
4829 * Hooks may return extended information by returning an array, of which the
4830 * first numbered element (index 0) must be the return string, and all other
4831 * entries are extracted into local variables within an internal function
4832 * in the Parser class.
4833 *
4834 * This interface (introduced r61913) appears to be undocumented, but
4835 * 'markerType' is used by some core tag hooks to override which strip
4836 * array their results are placed in. **Use great caution if attempting
4837 * this interface, as it is not documented and injudicious use could smash
4838 * private variables.**
4839 *
4840 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4841 * @param callable $callback The callback function (and object) to use for the tag
4842 * @throws MWException
4843 * @return callable|null The old value of the mTagHooks array associated with the hook
4844 */
4845 public function setHook( $tag, callable $callback ) {
4846 $tag = strtolower( $tag );
4847 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4848 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4849 }
4850 $oldVal = $this->mTagHooks[$tag] ?? null;
4851 $this->mTagHooks[$tag] = $callback;
4852 if ( !in_array( $tag, $this->mStripList ) ) {
4853 $this->mStripList[] = $tag;
4854 }
4855
4856 return $oldVal;
4857 }
4858
4859 /**
4860 * As setHook(), but letting the contents be parsed.
4861 *
4862 * Transparent tag hooks are like regular XML-style tag hooks, except they
4863 * operate late in the transformation sequence, on HTML instead of wikitext.
4864 *
4865 * This is probably obsoleted by things dealing with parser frames?
4866 * The only extension currently using it is geoserver.
4867 *
4868 * @since 1.10
4869 * @todo better document or deprecate this
4870 *
4871 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4872 * @param callable $callback The callback function (and object) to use for the tag
4873 * @throws MWException
4874 * @return callable|null The old value of the mTagHooks array associated with the hook
4875 */
4876 public function setTransparentTagHook( $tag, callable $callback ) {
4877 $tag = strtolower( $tag );
4878 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4879 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4880 }
4881 $oldVal = $this->mTransparentTagHooks[$tag] ?? null;
4882 $this->mTransparentTagHooks[$tag] = $callback;
4883
4884 return $oldVal;
4885 }
4886
4887 /**
4888 * Remove all tag hooks
4889 */
4890 public function clearTagHooks() {
4891 $this->mTagHooks = [];
4892 $this->mFunctionTagHooks = [];
4893 $this->mStripList = $this->mDefaultStripList;
4894 }
4895
4896 /**
4897 * Create a function, e.g. {{sum:1|2|3}}
4898 * The callback function should have the form:
4899 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4900 *
4901 * Or with Parser::SFH_OBJECT_ARGS:
4902 * function myParserFunction( $parser, $frame, $args ) { ... }
4903 *
4904 * The callback may either return the text result of the function, or an array with the text
4905 * in element 0, and a number of flags in the other elements. The names of the flags are
4906 * specified in the keys. Valid flags are:
4907 * found The text returned is valid, stop processing the template. This
4908 * is on by default.
4909 * nowiki Wiki markup in the return value should be escaped
4910 * isHTML The returned text is HTML, armour it against wikitext transformation
4911 *
4912 * @param string $id The magic word ID
4913 * @param callable $callback The callback function (and object) to use
4914 * @param int $flags A combination of the following flags:
4915 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4916 *
4917 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4918 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4919 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4920 * the arguments, and to control the way they are expanded.
4921 *
4922 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4923 * arguments, for instance:
4924 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4925 *
4926 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4927 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4928 * working if/when this is changed.
4929 *
4930 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4931 * expansion.
4932 *
4933 * Please read the documentation in includes/parser/Preprocessor.php for more information
4934 * about the methods available in PPFrame and PPNode.
4935 *
4936 * @throws MWException
4937 * @return string|callable The old callback function for this name, if any
4938 */
4939 public function setFunctionHook( $id, callable $callback, $flags = 0 ) {
4940 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4941 $this->mFunctionHooks[$id] = [ $callback, $flags ];
4942
4943 # Add to function cache
4944 $mw = $this->magicWordFactory->get( $id );
4945 if ( !$mw ) {
4946 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4947 }
4948
4949 $synonyms = $mw->getSynonyms();
4950 $sensitive = intval( $mw->isCaseSensitive() );
4951
4952 foreach ( $synonyms as $syn ) {
4953 # Case
4954 if ( !$sensitive ) {
4955 $syn = $this->contLang->lc( $syn );
4956 }
4957 # Add leading hash
4958 if ( !( $flags & self::SFH_NO_HASH ) ) {
4959 $syn = '#' . $syn;
4960 }
4961 # Remove trailing colon
4962 if ( substr( $syn, -1, 1 ) === ':' ) {
4963 $syn = substr( $syn, 0, -1 );
4964 }
4965 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4966 }
4967 return $oldVal;
4968 }
4969
4970 /**
4971 * Get all registered function hook identifiers
4972 *
4973 * @return array
4974 */
4975 public function getFunctionHooks() {
4976 $this->firstCallInit();
4977 return array_keys( $this->mFunctionHooks );
4978 }
4979
4980 /**
4981 * Create a tag function, e.g. "<test>some stuff</test>".
4982 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4983 * Unlike parser functions, their content is not preprocessed.
4984 * @param string $tag
4985 * @param callable $callback
4986 * @param int $flags
4987 * @throws MWException
4988 * @return null
4989 */
4990 public function setFunctionTagHook( $tag, callable $callback, $flags ) {
4991 $tag = strtolower( $tag );
4992 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4993 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4994 }
4995 $old = $this->mFunctionTagHooks[$tag] ?? null;
4996 $this->mFunctionTagHooks[$tag] = [ $callback, $flags ];
4997
4998 if ( !in_array( $tag, $this->mStripList ) ) {
4999 $this->mStripList[] = $tag;
5000 }
5001
5002 return $old;
5003 }
5004
5005 /**
5006 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5007 * Placeholders created in Linker::link()
5008 *
5009 * @param string &$text
5010 * @param int $options
5011 */
5012 public function replaceLinkHolders( &$text, $options = 0 ) {
5013 $this->mLinkHolders->replace( $text );
5014 }
5015
5016 /**
5017 * Replace "<!--LINK-->" link placeholders with plain text of links
5018 * (not HTML-formatted).
5019 *
5020 * @param string $text
5021 * @return string
5022 */
5023 public function replaceLinkHoldersText( $text ) {
5024 return $this->mLinkHolders->replaceText( $text );
5025 }
5026
5027 /**
5028 * Renders an image gallery from a text with one line per image.
5029 * text labels may be given by using |-style alternative text. E.g.
5030 * Image:one.jpg|The number "1"
5031 * Image:tree.jpg|A tree
5032 * given as text will return the HTML of a gallery with two images,
5033 * labeled 'The number "1"' and
5034 * 'A tree'.
5035 *
5036 * @param string $text
5037 * @param array $params
5038 * @return string HTML
5039 */
5040 public function renderImageGallery( $text, $params ) {
5041 $mode = false;
5042 if ( isset( $params['mode'] ) ) {
5043 $mode = $params['mode'];
5044 }
5045
5046 try {
5047 $ig = ImageGalleryBase::factory( $mode );
5048 } catch ( Exception $e ) {
5049 // If invalid type set, fallback to default.
5050 $ig = ImageGalleryBase::factory( false );
5051 }
5052
5053 $ig->setContextTitle( $this->mTitle );
5054 $ig->setShowBytes( false );
5055 $ig->setShowDimensions( false );
5056 $ig->setShowFilename( false );
5057 $ig->setParser( $this );
5058 $ig->setHideBadImages();
5059 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'ul' ) );
5060
5061 if ( isset( $params['showfilename'] ) ) {
5062 $ig->setShowFilename( true );
5063 } else {
5064 $ig->setShowFilename( false );
5065 }
5066 if ( isset( $params['caption'] ) ) {
5067 $caption = $params['caption'];
5068 $caption = htmlspecialchars( $caption );
5069 $caption = $this->replaceInternalLinks( $caption );
5070 $ig->setCaptionHtml( $caption );
5071 }
5072 if ( isset( $params['perrow'] ) ) {
5073 $ig->setPerRow( $params['perrow'] );
5074 }
5075 if ( isset( $params['widths'] ) ) {
5076 $ig->setWidths( $params['widths'] );
5077 }
5078 if ( isset( $params['heights'] ) ) {
5079 $ig->setHeights( $params['heights'] );
5080 }
5081 $ig->setAdditionalOptions( $params );
5082
5083 // Avoid PHP 7.1 warning from passing $this by reference
5084 $parser = $this;
5085 Hooks::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5086
5087 $lines = StringUtils::explode( "\n", $text );
5088 foreach ( $lines as $line ) {
5089 # match lines like these:
5090 # Image:someimage.jpg|This is some image
5091 $matches = [];
5092 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5093 # Skip empty lines
5094 if ( count( $matches ) == 0 ) {
5095 continue;
5096 }
5097
5098 if ( strpos( $matches[0], '%' ) !== false ) {
5099 $matches[1] = rawurldecode( $matches[1] );
5100 }
5101 $title = Title::newFromText( $matches[1], NS_FILE );
5102 if ( is_null( $title ) ) {
5103 # Bogus title. Ignore these so we don't bomb out later.
5104 continue;
5105 }
5106
5107 # We need to get what handler the file uses, to figure out parameters.
5108 # Note, a hook can overide the file name, and chose an entirely different
5109 # file (which potentially could be of a different type and have different handler).
5110 $options = [];
5111 $descQuery = false;
5112 Hooks::run( 'BeforeParserFetchFileAndTitle',
5113 [ $this, $title, &$options, &$descQuery ] );
5114 # Don't register it now, as TraditionalImageGallery does that later.
5115 $file = $this->fetchFileNoRegister( $title, $options );
5116 $handler = $file ? $file->getHandler() : false;
5117
5118 $paramMap = [
5119 'img_alt' => 'gallery-internal-alt',
5120 'img_link' => 'gallery-internal-link',
5121 ];
5122 if ( $handler ) {
5123 $paramMap = $paramMap + $handler->getParamMap();
5124 // We don't want people to specify per-image widths.
5125 // Additionally the width parameter would need special casing anyhow.
5126 unset( $paramMap['img_width'] );
5127 }
5128
5129 $mwArray = $this->magicWordFactory->newArray( array_keys( $paramMap ) );
5130
5131 $label = '';
5132 $alt = '';
5133 $link = '';
5134 $handlerOptions = [];
5135 if ( isset( $matches[3] ) ) {
5136 // look for an |alt= definition while trying not to break existing
5137 // captions with multiple pipes (|) in it, until a more sensible grammar
5138 // is defined for images in galleries
5139
5140 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5141 // splitting on '|' is a bit odd, and different from makeImage.
5142 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5143 // Protect LanguageConverter markup
5144 $parameterMatches = StringUtils::delimiterExplode(
5145 '-{', '}-', '|', $matches[3], true /* nested */
5146 );
5147
5148 foreach ( $parameterMatches as $parameterMatch ) {
5149 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5150 if ( $magicName ) {
5151 $paramName = $paramMap[$magicName];
5152
5153 switch ( $paramName ) {
5154 case 'gallery-internal-alt':
5155 $alt = $this->stripAltText( $match, false );
5156 break;
5157 case 'gallery-internal-link':
5158 $linkValue = $this->stripAltText( $match, false );
5159 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5160 // Result of LanguageConverter::markNoConversion
5161 // invoked on an external link.
5162 $linkValue = substr( $linkValue, 4, -2 );
5163 }
5164 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5165 if ( $type === 'link-url' ) {
5166 $link = $target;
5167 $this->mOutput->addExternalLink( $target );
5168 } elseif ( $type === 'link-title' ) {
5169 $link = $target->getLinkURL();
5170 $this->mOutput->addLink( $target );
5171 }
5172 break;
5173 default:
5174 // Must be a handler specific parameter.
5175 if ( $handler->validateParam( $paramName, $match ) ) {
5176 $handlerOptions[$paramName] = $match;
5177 } else {
5178 // Guess not, consider it as caption.
5179 wfDebug( "$parameterMatch failed parameter validation\n" );
5180 $label = $parameterMatch;
5181 }
5182 }
5183
5184 } else {
5185 // Last pipe wins.
5186 $label = $parameterMatch;
5187 }
5188 }
5189 }
5190
5191 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5192 }
5193 $html = $ig->toHTML();
5194 Hooks::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5195 return $html;
5196 }
5197
5198 /**
5199 * @param MediaHandler $handler
5200 * @return array
5201 */
5202 public function getImageParams( $handler ) {
5203 if ( $handler ) {
5204 $handlerClass = get_class( $handler );
5205 } else {
5206 $handlerClass = '';
5207 }
5208 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5209 # Initialise static lists
5210 static $internalParamNames = [
5211 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5212 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5213 'bottom', 'text-bottom' ],
5214 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5215 'upright', 'border', 'link', 'alt', 'class' ],
5216 ];
5217 static $internalParamMap;
5218 if ( !$internalParamMap ) {
5219 $internalParamMap = [];
5220 foreach ( $internalParamNames as $type => $names ) {
5221 foreach ( $names as $name ) {
5222 // For grep: img_left, img_right, img_center, img_none,
5223 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5224 // img_bottom, img_text_bottom,
5225 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5226 // img_border, img_link, img_alt, img_class
5227 $magicName = str_replace( '-', '_', "img_$name" );
5228 $internalParamMap[$magicName] = [ $type, $name ];
5229 }
5230 }
5231 }
5232
5233 # Add handler params
5234 $paramMap = $internalParamMap;
5235 if ( $handler ) {
5236 $handlerParamMap = $handler->getParamMap();
5237 foreach ( $handlerParamMap as $magic => $paramName ) {
5238 $paramMap[$magic] = [ 'handler', $paramName ];
5239 }
5240 }
5241 $this->mImageParams[$handlerClass] = $paramMap;
5242 $this->mImageParamsMagicArray[$handlerClass] =
5243 $this->magicWordFactory->newArray( array_keys( $paramMap ) );
5244 }
5245 return [ $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ];
5246 }
5247
5248 /**
5249 * Parse image options text and use it to make an image
5250 *
5251 * @param Title $title
5252 * @param string $options
5253 * @param LinkHolderArray|bool $holders
5254 * @return string HTML
5255 */
5256 public function makeImage( $title, $options, $holders = false ) {
5257 # Check if the options text is of the form "options|alt text"
5258 # Options are:
5259 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5260 # * left no resizing, just left align. label is used for alt= only
5261 # * right same, but right aligned
5262 # * none same, but not aligned
5263 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5264 # * center center the image
5265 # * frame Keep original image size, no magnify-button.
5266 # * framed Same as "frame"
5267 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5268 # * upright reduce width for upright images, rounded to full __0 px
5269 # * border draw a 1px border around the image
5270 # * alt Text for HTML alt attribute (defaults to empty)
5271 # * class Set a class for img node
5272 # * link Set the target of the image link. Can be external, interwiki, or local
5273 # vertical-align values (no % or length right now):
5274 # * baseline
5275 # * sub
5276 # * super
5277 # * top
5278 # * text-top
5279 # * middle
5280 # * bottom
5281 # * text-bottom
5282
5283 global $wgMediaInTargetLanguage;
5284
5285 # Protect LanguageConverter markup when splitting into parts
5286 $parts = StringUtils::delimiterExplode(
5287 '-{', '}-', '|', $options, true /* allow nesting */
5288 );
5289
5290 # Give extensions a chance to select the file revision for us
5291 $options = [];
5292 $descQuery = false;
5293 Hooks::run( 'BeforeParserFetchFileAndTitle',
5294 [ $this, $title, &$options, &$descQuery ] );
5295 # Fetch and register the file (file title may be different via hooks)
5296 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5297
5298 # Get parameter map
5299 $handler = $file ? $file->getHandler() : false;
5300
5301 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5302
5303 if ( !$file ) {
5304 $this->addTrackingCategory( 'broken-file-category' );
5305 }
5306
5307 # Process the input parameters
5308 $caption = '';
5309 $params = [ 'frame' => [], 'handler' => [],
5310 'horizAlign' => [], 'vertAlign' => [] ];
5311 $seenformat = false;
5312 foreach ( $parts as $part ) {
5313 $part = trim( $part );
5314 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5315 $validated = false;
5316 if ( isset( $paramMap[$magicName] ) ) {
5317 list( $type, $paramName ) = $paramMap[$magicName];
5318
5319 # Special case; width and height come in one variable together
5320 if ( $type === 'handler' && $paramName === 'width' ) {
5321 $parsedWidthParam = self::parseWidthParam( $value );
5322 if ( isset( $parsedWidthParam['width'] ) ) {
5323 $width = $parsedWidthParam['width'];
5324 if ( $handler->validateParam( 'width', $width ) ) {
5325 $params[$type]['width'] = $width;
5326 $validated = true;
5327 }
5328 }
5329 if ( isset( $parsedWidthParam['height'] ) ) {
5330 $height = $parsedWidthParam['height'];
5331 if ( $handler->validateParam( 'height', $height ) ) {
5332 $params[$type]['height'] = $height;
5333 $validated = true;
5334 }
5335 }
5336 # else no validation -- T15436
5337 } else {
5338 if ( $type === 'handler' ) {
5339 # Validate handler parameter
5340 $validated = $handler->validateParam( $paramName, $value );
5341 } else {
5342 # Validate internal parameters
5343 switch ( $paramName ) {
5344 case 'manualthumb':
5345 case 'alt':
5346 case 'class':
5347 # @todo FIXME: Possibly check validity here for
5348 # manualthumb? downstream behavior seems odd with
5349 # missing manual thumbs.
5350 $validated = true;
5351 $value = $this->stripAltText( $value, $holders );
5352 break;
5353 case 'link':
5354 list( $paramName, $value ) =
5355 $this->parseLinkParameter(
5356 $this->stripAltText( $value, $holders )
5357 );
5358 if ( $paramName ) {
5359 $validated = true;
5360 if ( $paramName === 'no-link' ) {
5361 $value = true;
5362 }
5363 if ( $paramName === 'link-url' ) {
5364 if ( $this->mOptions->getExternalLinkTarget() ) {
5365 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5366 }
5367 }
5368 }
5369 break;
5370 case 'frameless':
5371 case 'framed':
5372 case 'thumbnail':
5373 // use first appearing option, discard others.
5374 $validated = !$seenformat;
5375 $seenformat = true;
5376 break;
5377 default:
5378 # Most other things appear to be empty or numeric...
5379 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5380 }
5381 }
5382
5383 if ( $validated ) {
5384 $params[$type][$paramName] = $value;
5385 }
5386 }
5387 }
5388 if ( !$validated ) {
5389 $caption = $part;
5390 }
5391 }
5392
5393 # Process alignment parameters
5394 if ( $params['horizAlign'] ) {
5395 $params['frame']['align'] = key( $params['horizAlign'] );
5396 }
5397 if ( $params['vertAlign'] ) {
5398 $params['frame']['valign'] = key( $params['vertAlign'] );
5399 }
5400
5401 $params['frame']['caption'] = $caption;
5402
5403 # Will the image be presented in a frame, with the caption below?
5404 $imageIsFramed = isset( $params['frame']['frame'] )
5405 || isset( $params['frame']['framed'] )
5406 || isset( $params['frame']['thumbnail'] )
5407 || isset( $params['frame']['manualthumb'] );
5408
5409 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5410 # came to also set the caption, ordinary text after the image -- which
5411 # makes no sense, because that just repeats the text multiple times in
5412 # screen readers. It *also* came to set the title attribute.
5413 # Now that we have an alt attribute, we should not set the alt text to
5414 # equal the caption: that's worse than useless, it just repeats the
5415 # text. This is the framed/thumbnail case. If there's no caption, we
5416 # use the unnamed parameter for alt text as well, just for the time be-
5417 # ing, if the unnamed param is set and the alt param is not.
5418 # For the future, we need to figure out if we want to tweak this more,
5419 # e.g., introducing a title= parameter for the title; ignoring the un-
5420 # named parameter entirely for images without a caption; adding an ex-
5421 # plicit caption= parameter and preserving the old magic unnamed para-
5422 # meter for BC; ...
5423 if ( $imageIsFramed ) { # Framed image
5424 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5425 # No caption or alt text, add the filename as the alt text so
5426 # that screen readers at least get some description of the image
5427 $params['frame']['alt'] = $title->getText();
5428 }
5429 # Do not set $params['frame']['title'] because tooltips don't make sense
5430 # for framed images
5431 } else { # Inline image
5432 if ( !isset( $params['frame']['alt'] ) ) {
5433 # No alt text, use the "caption" for the alt text
5434 if ( $caption !== '' ) {
5435 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5436 } else {
5437 # No caption, fall back to using the filename for the
5438 # alt text
5439 $params['frame']['alt'] = $title->getText();
5440 }
5441 }
5442 # Use the "caption" for the tooltip text
5443 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5444 }
5445 if ( $wgMediaInTargetLanguage ) {
5446 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5447 }
5448
5449 Hooks::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5450
5451 # Linker does the rest
5452 $time = $options['time'] ?? false;
5453 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5454 $time, $descQuery, $this->mOptions->getThumbSize() );
5455
5456 # Give the handler a chance to modify the parser object
5457 if ( $handler ) {
5458 $handler->parserTransformHook( $this, $file );
5459 }
5460
5461 return $ret;
5462 }
5463
5464 /**
5465 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5466 *
5467 * Adds an entry to appropriate link tables.
5468 *
5469 * @since 1.32
5470 * @return array of `[ type, target ]`, where:
5471 * - `type` is one of:
5472 * - `null`: Given value is not a valid link target, use default
5473 * - `'no-link'`: Given value is empty, do not generate a link
5474 * - `'link-url'`: Given value is a valid external link
5475 * - `'link-title'`: Given value is a valid internal link
5476 * - `target` is:
5477 * - When `type` is `null` or `'no-link'`: `false`
5478 * - When `type` is `'link-url'`: URL string corresponding to given value
5479 * - When `type` is `'link-title'`: Title object corresponding to given value
5480 */
5481 public function parseLinkParameter( $value ) {
5482 $chars = self::EXT_LINK_URL_CLASS;
5483 $addr = self::EXT_LINK_ADDR;
5484 $prots = $this->mUrlProtocols;
5485 $type = null;
5486 $target = false;
5487 if ( $value === '' ) {
5488 $type = 'no-link';
5489 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5490 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5491 $this->mOutput->addExternalLink( $value );
5492 $type = 'link-url';
5493 $target = $value;
5494 }
5495 } else {
5496 $linkTitle = Title::newFromText( $value );
5497 if ( $linkTitle ) {
5498 $this->mOutput->addLink( $linkTitle );
5499 $type = 'link-title';
5500 $target = $linkTitle;
5501 }
5502 }
5503 return [ $type, $target ];
5504 }
5505
5506 /**
5507 * @param string $caption
5508 * @param LinkHolderArray|bool $holders
5509 * @return mixed|string
5510 */
5511 protected function stripAltText( $caption, $holders ) {
5512 # Strip bad stuff out of the title (tooltip). We can't just use
5513 # replaceLinkHoldersText() here, because if this function is called
5514 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5515 if ( $holders ) {
5516 $tooltip = $holders->replaceText( $caption );
5517 } else {
5518 $tooltip = $this->replaceLinkHoldersText( $caption );
5519 }
5520
5521 # make sure there are no placeholders in thumbnail attributes
5522 # that are later expanded to html- so expand them now and
5523 # remove the tags
5524 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5525 $tooltip = Sanitizer::stripAllTags( $tooltip );
5526
5527 return $tooltip;
5528 }
5529
5530 /**
5531 * Set a flag in the output object indicating that the content is dynamic and
5532 * shouldn't be cached.
5533 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5534 */
5535 public function disableCache() {
5536 wfDebug( "Parser output marked as uncacheable.\n" );
5537 if ( !$this->mOutput ) {
5538 throw new MWException( __METHOD__ .
5539 " can only be called when actually parsing something" );
5540 }
5541 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5542 }
5543
5544 /**
5545 * Callback from the Sanitizer for expanding items found in HTML attribute
5546 * values, so they can be safely tested and escaped.
5547 *
5548 * @param string &$text
5549 * @param bool|PPFrame $frame
5550 * @return string
5551 */
5552 public function attributeStripCallback( &$text, $frame = false ) {
5553 $text = $this->replaceVariables( $text, $frame );
5554 $text = $this->mStripState->unstripBoth( $text );
5555 return $text;
5556 }
5557
5558 /**
5559 * Accessor
5560 *
5561 * @return array
5562 */
5563 public function getTags() {
5564 $this->firstCallInit();
5565 return array_merge(
5566 array_keys( $this->mTransparentTagHooks ),
5567 array_keys( $this->mTagHooks ),
5568 array_keys( $this->mFunctionTagHooks )
5569 );
5570 }
5571
5572 /**
5573 * @since 1.32
5574 * @return array
5575 */
5576 public function getFunctionSynonyms() {
5577 $this->firstCallInit();
5578 return $this->mFunctionSynonyms;
5579 }
5580
5581 /**
5582 * @since 1.32
5583 * @return string
5584 */
5585 public function getUrlProtocols() {
5586 return $this->mUrlProtocols;
5587 }
5588
5589 /**
5590 * Replace transparent tags in $text with the values given by the callbacks.
5591 *
5592 * Transparent tag hooks are like regular XML-style tag hooks, except they
5593 * operate late in the transformation sequence, on HTML instead of wikitext.
5594 *
5595 * @param string $text
5596 *
5597 * @return string
5598 */
5599 public function replaceTransparentTags( $text ) {
5600 $matches = [];
5601 $elements = array_keys( $this->mTransparentTagHooks );
5602 $text = self::extractTagsAndParams( $elements, $text, $matches );
5603 $replacements = [];
5604
5605 foreach ( $matches as $marker => $data ) {
5606 list( $element, $content, $params, $tag ) = $data;
5607 $tagName = strtolower( $element );
5608 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5609 $output = call_user_func_array(
5610 $this->mTransparentTagHooks[$tagName],
5611 [ $content, $params, $this ]
5612 );
5613 } else {
5614 $output = $tag;
5615 }
5616 $replacements[$marker] = $output;
5617 }
5618 return strtr( $text, $replacements );
5619 }
5620
5621 /**
5622 * Break wikitext input into sections, and either pull or replace
5623 * some particular section's text.
5624 *
5625 * External callers should use the getSection and replaceSection methods.
5626 *
5627 * @param string $text Page wikitext
5628 * @param string|int $sectionId A section identifier string of the form:
5629 * "<flag1> - <flag2> - ... - <section number>"
5630 *
5631 * Currently the only recognised flag is "T", which means the target section number
5632 * was derived during a template inclusion parse, in other words this is a template
5633 * section edit link. If no flags are given, it was an ordinary section edit link.
5634 * This flag is required to avoid a section numbering mismatch when a section is
5635 * enclosed by "<includeonly>" (T8563).
5636 *
5637 * The section number 0 pulls the text before the first heading; other numbers will
5638 * pull the given section along with its lower-level subsections. If the section is
5639 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5640 *
5641 * Section 0 is always considered to exist, even if it only contains the empty
5642 * string. If $text is the empty string and section 0 is replaced, $newText is
5643 * returned.
5644 *
5645 * @param string $mode One of "get" or "replace"
5646 * @param string $newText Replacement text for section data.
5647 * @return string For "get", the extracted section text.
5648 * for "replace", the whole page with the section replaced.
5649 */
5650 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5651 global $wgTitle; # not generally used but removes an ugly failure mode
5652
5653 $magicScopeVariable = $this->lock();
5654 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5655 $outText = '';
5656 $frame = $this->getPreprocessor()->newFrame();
5657
5658 # Process section extraction flags
5659 $flags = 0;
5660 $sectionParts = explode( '-', $sectionId );
5661 $sectionIndex = array_pop( $sectionParts );
5662 foreach ( $sectionParts as $part ) {
5663 if ( $part === 'T' ) {
5664 $flags |= self::PTD_FOR_INCLUSION;
5665 }
5666 }
5667
5668 # Check for empty input
5669 if ( strval( $text ) === '' ) {
5670 # Only sections 0 and T-0 exist in an empty document
5671 if ( $sectionIndex == 0 ) {
5672 if ( $mode === 'get' ) {
5673 return '';
5674 } else {
5675 return $newText;
5676 }
5677 } else {
5678 if ( $mode === 'get' ) {
5679 return $newText;
5680 } else {
5681 return $text;
5682 }
5683 }
5684 }
5685
5686 # Preprocess the text
5687 $root = $this->preprocessToDom( $text, $flags );
5688
5689 # <h> nodes indicate section breaks
5690 # They can only occur at the top level, so we can find them by iterating the root's children
5691 $node = $root->getFirstChild();
5692
5693 # Find the target section
5694 if ( $sectionIndex == 0 ) {
5695 # Section zero doesn't nest, level=big
5696 $targetLevel = 1000;
5697 } else {
5698 while ( $node ) {
5699 if ( $node->getName() === 'h' ) {
5700 $bits = $node->splitHeading();
5701 if ( $bits['i'] == $sectionIndex ) {
5702 $targetLevel = $bits['level'];
5703 break;
5704 }
5705 }
5706 if ( $mode === 'replace' ) {
5707 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5708 }
5709 $node = $node->getNextSibling();
5710 }
5711 }
5712
5713 if ( !$node ) {
5714 # Not found
5715 if ( $mode === 'get' ) {
5716 return $newText;
5717 } else {
5718 return $text;
5719 }
5720 }
5721
5722 # Find the end of the section, including nested sections
5723 do {
5724 if ( $node->getName() === 'h' ) {
5725 $bits = $node->splitHeading();
5726 $curLevel = $bits['level'];
5727 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5728 break;
5729 }
5730 }
5731 if ( $mode === 'get' ) {
5732 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5733 }
5734 $node = $node->getNextSibling();
5735 } while ( $node );
5736
5737 # Write out the remainder (in replace mode only)
5738 if ( $mode === 'replace' ) {
5739 # Output the replacement text
5740 # Add two newlines on -- trailing whitespace in $newText is conventionally
5741 # stripped by the editor, so we need both newlines to restore the paragraph gap
5742 # Only add trailing whitespace if there is newText
5743 if ( $newText != "" ) {
5744 $outText .= $newText . "\n\n";
5745 }
5746
5747 while ( $node ) {
5748 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5749 $node = $node->getNextSibling();
5750 }
5751 }
5752
5753 if ( is_string( $outText ) ) {
5754 # Re-insert stripped tags
5755 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5756 }
5757
5758 return $outText;
5759 }
5760
5761 /**
5762 * This function returns the text of a section, specified by a number ($section).
5763 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5764 * the first section before any such heading (section 0).
5765 *
5766 * If a section contains subsections, these are also returned.
5767 *
5768 * @param string $text Text to look in
5769 * @param string|int $sectionId Section identifier as a number or string
5770 * (e.g. 0, 1 or 'T-1').
5771 * @param string $defaultText Default to return if section is not found
5772 *
5773 * @return string Text of the requested section
5774 */
5775 public function getSection( $text, $sectionId, $defaultText = '' ) {
5776 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5777 }
5778
5779 /**
5780 * This function returns $oldtext after the content of the section
5781 * specified by $section has been replaced with $text. If the target
5782 * section does not exist, $oldtext is returned unchanged.
5783 *
5784 * @param string $oldText Former text of the article
5785 * @param string|int $sectionId Section identifier as a number or string
5786 * (e.g. 0, 1 or 'T-1').
5787 * @param string $newText Replacing text
5788 *
5789 * @return string Modified text
5790 */
5791 public function replaceSection( $oldText, $sectionId, $newText ) {
5792 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5793 }
5794
5795 /**
5796 * Get the ID of the revision we are parsing
5797 *
5798 * @return int|null
5799 */
5800 public function getRevisionId() {
5801 return $this->mRevisionId;
5802 }
5803
5804 /**
5805 * Get the revision object for $this->mRevisionId
5806 *
5807 * @return Revision|null Either a Revision object or null
5808 * @since 1.23 (public since 1.23)
5809 */
5810 public function getRevisionObject() {
5811 if ( !is_null( $this->mRevisionObject ) ) {
5812 return $this->mRevisionObject;
5813 }
5814
5815 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5816 // This is useful when parsing revision that has not yet been saved.
5817 // However, if we get back a saved revision even though we are in
5818 // preview mode, we'll have to ignore it, see below.
5819 // NOTE: This callback may be used to inject an OLD revision that was
5820 // already loaded, so "current" is a bit of a misnomer. We can't just
5821 // skip it if mRevisionId is set.
5822 $rev = call_user_func(
5823 $this->mOptions->getCurrentRevisionCallback(), $this->getTitle(), $this
5824 );
5825
5826 if ( $this->mRevisionId === null && $rev && $rev->getId() ) {
5827 // We are in preview mode (mRevisionId is null), and the current revision callback
5828 // returned an existing revision. Ignore it and return null, it's probably the page's
5829 // current revision, which is not what we want here. Note that we do want to call the
5830 // callback to allow the unsaved revision to be injected here, e.g. for
5831 // self-transclusion previews.
5832 return null;
5833 }
5834
5835 // If the parse is for a new revision, then the callback should have
5836 // already been set to force the object and should match mRevisionId.
5837 // If not, try to fetch by mRevisionId for sanity.
5838 if ( $this->mRevisionId && $rev && $rev->getId() != $this->mRevisionId ) {
5839 $rev = Revision::newFromId( $this->mRevisionId );
5840 }
5841
5842 $this->mRevisionObject = $rev;
5843
5844 return $this->mRevisionObject;
5845 }
5846
5847 /**
5848 * Get the timestamp associated with the current revision, adjusted for
5849 * the default server-local timestamp
5850 * @return string
5851 */
5852 public function getRevisionTimestamp() {
5853 if ( is_null( $this->mRevisionTimestamp ) ) {
5854 $revObject = $this->getRevisionObject();
5855 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5856
5857 # The cryptic '' timezone parameter tells to use the site-default
5858 # timezone offset instead of the user settings.
5859 # Since this value will be saved into the parser cache, served
5860 # to other users, and potentially even used inside links and such,
5861 # it needs to be consistent for all visitors.
5862 $this->mRevisionTimestamp = $this->contLang->userAdjust( $timestamp, '' );
5863 }
5864 return $this->mRevisionTimestamp;
5865 }
5866
5867 /**
5868 * Get the name of the user that edited the last revision
5869 *
5870 * @return string User name
5871 */
5872 public function getRevisionUser() {
5873 if ( is_null( $this->mRevisionUser ) ) {
5874 $revObject = $this->getRevisionObject();
5875
5876 # if this template is subst: the revision id will be blank,
5877 # so just use the current user's name
5878 if ( $revObject ) {
5879 $this->mRevisionUser = $revObject->getUserText();
5880 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5881 $this->mRevisionUser = $this->getUser()->getName();
5882 }
5883 }
5884 return $this->mRevisionUser;
5885 }
5886
5887 /**
5888 * Get the size of the revision
5889 *
5890 * @return int|null Revision size
5891 */
5892 public function getRevisionSize() {
5893 if ( is_null( $this->mRevisionSize ) ) {
5894 $revObject = $this->getRevisionObject();
5895
5896 # if this variable is subst: the revision id will be blank,
5897 # so just use the parser input size, because the own substituation
5898 # will change the size.
5899 if ( $revObject ) {
5900 $this->mRevisionSize = $revObject->getSize();
5901 } else {
5902 $this->mRevisionSize = $this->mInputSize;
5903 }
5904 }
5905 return $this->mRevisionSize;
5906 }
5907
5908 /**
5909 * Mutator for $mDefaultSort
5910 *
5911 * @param string $sort New value
5912 */
5913 public function setDefaultSort( $sort ) {
5914 $this->mDefaultSort = $sort;
5915 $this->mOutput->setProperty( 'defaultsort', $sort );
5916 }
5917
5918 /**
5919 * Accessor for $mDefaultSort
5920 * Will use the empty string if none is set.
5921 *
5922 * This value is treated as a prefix, so the
5923 * empty string is equivalent to sorting by
5924 * page name.
5925 *
5926 * @return string
5927 */
5928 public function getDefaultSort() {
5929 if ( $this->mDefaultSort !== false ) {
5930 return $this->mDefaultSort;
5931 } else {
5932 return '';
5933 }
5934 }
5935
5936 /**
5937 * Accessor for $mDefaultSort
5938 * Unlike getDefaultSort(), will return false if none is set
5939 *
5940 * @return string|bool
5941 */
5942 public function getCustomDefaultSort() {
5943 return $this->mDefaultSort;
5944 }
5945
5946 private static function getSectionNameFromStrippedText( $text ) {
5947 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5948 $text = Sanitizer::decodeCharReferences( $text );
5949 $text = self::normalizeSectionName( $text );
5950 return $text;
5951 }
5952
5953 private static function makeAnchor( $sectionName ) {
5954 return '#' . Sanitizer::escapeIdForLink( $sectionName );
5955 }
5956
5957 private function makeLegacyAnchor( $sectionName ) {
5958 $fragmentMode = $this->siteConfig->get( 'FragmentMode' );
5959 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
5960 // ForAttribute() and ForLink() are the same for legacy encoding
5961 $id = Sanitizer::escapeIdForAttribute( $sectionName, Sanitizer::ID_FALLBACK );
5962 } else {
5963 $id = Sanitizer::escapeIdForLink( $sectionName );
5964 }
5965
5966 return "#$id";
5967 }
5968
5969 /**
5970 * Try to guess the section anchor name based on a wikitext fragment
5971 * presumably extracted from a heading, for example "Header" from
5972 * "== Header ==".
5973 *
5974 * @param string $text
5975 * @return string Anchor (starting with '#')
5976 */
5977 public function guessSectionNameFromWikiText( $text ) {
5978 # Strip out wikitext links(they break the anchor)
5979 $text = $this->stripSectionName( $text );
5980 $sectionName = self::getSectionNameFromStrippedText( $text );
5981 return self::makeAnchor( $sectionName );
5982 }
5983
5984 /**
5985 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5986 * instead, if possible. For use in redirects, since various versions
5987 * of Microsoft browsers interpret Location: headers as something other
5988 * than UTF-8, resulting in breakage.
5989 *
5990 * @param string $text The section name
5991 * @return string Anchor (starting with '#')
5992 */
5993 public function guessLegacySectionNameFromWikiText( $text ) {
5994 # Strip out wikitext links(they break the anchor)
5995 $text = $this->stripSectionName( $text );
5996 $sectionName = self::getSectionNameFromStrippedText( $text );
5997 return $this->makeLegacyAnchor( $sectionName );
5998 }
5999
6000 /**
6001 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6002 * @param string $text Section name (plain text)
6003 * @return string Anchor (starting with '#')
6004 */
6005 public static function guessSectionNameFromStrippedText( $text ) {
6006 $sectionName = self::getSectionNameFromStrippedText( $text );
6007 return self::makeAnchor( $sectionName );
6008 }
6009
6010 /**
6011 * Apply the same normalization as code making links to this section would
6012 *
6013 * @param string $text
6014 * @return string
6015 */
6016 private static function normalizeSectionName( $text ) {
6017 # T90902: ensure the same normalization is applied for IDs as to links
6018 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
6019 try {
6020
6021 $parts = $titleParser->splitTitleString( "#$text" );
6022 } catch ( MalformedTitleException $ex ) {
6023 return $text;
6024 }
6025 return $parts['fragment'];
6026 }
6027
6028 /**
6029 * Strips a text string of wikitext for use in a section anchor
6030 *
6031 * Accepts a text string and then removes all wikitext from the
6032 * string and leaves only the resultant text (i.e. the result of
6033 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6034 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6035 * to create valid section anchors by mimicing the output of the
6036 * parser when headings are parsed.
6037 *
6038 * @param string $text Text string to be stripped of wikitext
6039 * for use in a Section anchor
6040 * @return string Filtered text string
6041 */
6042 public function stripSectionName( $text ) {
6043 # Strip internal link markup
6044 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6045 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6046
6047 # Strip external link markup
6048 # @todo FIXME: Not tolerant to blank link text
6049 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6050 # on how many empty links there are on the page - need to figure that out.
6051 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6052
6053 # Parse wikitext quotes (italics & bold)
6054 $text = $this->doQuotes( $text );
6055
6056 # Strip HTML tags
6057 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
6058 return $text;
6059 }
6060
6061 /**
6062 * strip/replaceVariables/unstrip for preprocessor regression testing
6063 *
6064 * @param string $text
6065 * @param Title $title
6066 * @param ParserOptions $options
6067 * @param int $outputType
6068 *
6069 * @return string
6070 */
6071 public function testSrvus( $text, Title $title, ParserOptions $options,
6072 $outputType = self::OT_HTML
6073 ) {
6074 $magicScopeVariable = $this->lock();
6075 $this->startParse( $title, $options, $outputType, true );
6076
6077 $text = $this->replaceVariables( $text );
6078 $text = $this->mStripState->unstripBoth( $text );
6079 $text = Sanitizer::removeHTMLtags( $text );
6080 return $text;
6081 }
6082
6083 /**
6084 * @param string $text
6085 * @param Title $title
6086 * @param ParserOptions $options
6087 * @return string
6088 */
6089 public function testPst( $text, Title $title, ParserOptions $options ) {
6090 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6091 }
6092
6093 /**
6094 * @param string $text
6095 * @param Title $title
6096 * @param ParserOptions $options
6097 * @return string
6098 */
6099 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
6100 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
6101 }
6102
6103 /**
6104 * Call a callback function on all regions of the given text that are not
6105 * inside strip markers, and replace those regions with the return value
6106 * of the callback. For example, with input:
6107 *
6108 * aaa<MARKER>bbb
6109 *
6110 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6111 * two strings will be replaced with the value returned by the callback in
6112 * each case.
6113 *
6114 * @param string $s
6115 * @param callable $callback
6116 *
6117 * @return string
6118 */
6119 public function markerSkipCallback( $s, $callback ) {
6120 $i = 0;
6121 $out = '';
6122 while ( $i < strlen( $s ) ) {
6123 $markerStart = strpos( $s, self::MARKER_PREFIX, $i );
6124 if ( $markerStart === false ) {
6125 $out .= call_user_func( $callback, substr( $s, $i ) );
6126 break;
6127 } else {
6128 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6129 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
6130 if ( $markerEnd === false ) {
6131 $out .= substr( $s, $markerStart );
6132 break;
6133 } else {
6134 $markerEnd += strlen( self::MARKER_SUFFIX );
6135 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6136 $i = $markerEnd;
6137 }
6138 }
6139 }
6140 return $out;
6141 }
6142
6143 /**
6144 * Remove any strip markers found in the given text.
6145 *
6146 * @param string $text
6147 * @return string
6148 */
6149 public function killMarkers( $text ) {
6150 return $this->mStripState->killMarkers( $text );
6151 }
6152
6153 /**
6154 * Save the parser state required to convert the given half-parsed text to
6155 * HTML. "Half-parsed" in this context means the output of
6156 * recursiveTagParse() or internalParse(). This output has strip markers
6157 * from replaceVariables (extensionSubstitution() etc.), and link
6158 * placeholders from replaceLinkHolders().
6159 *
6160 * Returns an array which can be serialized and stored persistently. This
6161 * array can later be loaded into another parser instance with
6162 * unserializeHalfParsedText(). The text can then be safely incorporated into
6163 * the return value of a parser hook.
6164 *
6165 * @deprecated since 1.31
6166 * @param string $text
6167 *
6168 * @return array
6169 */
6170 public function serializeHalfParsedText( $text ) {
6171 wfDeprecated( __METHOD__, '1.31' );
6172 $data = [
6173 'text' => $text,
6174 'version' => self::HALF_PARSED_VERSION,
6175 'stripState' => $this->mStripState->getSubState( $text ),
6176 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6177 ];
6178 return $data;
6179 }
6180
6181 /**
6182 * Load the parser state given in the $data array, which is assumed to
6183 * have been generated by serializeHalfParsedText(). The text contents is
6184 * extracted from the array, and its markers are transformed into markers
6185 * appropriate for the current Parser instance. This transformed text is
6186 * returned, and can be safely included in the return value of a parser
6187 * hook.
6188 *
6189 * If the $data array has been stored persistently, the caller should first
6190 * check whether it is still valid, by calling isValidHalfParsedText().
6191 *
6192 * @deprecated since 1.31
6193 * @param array $data Serialized data
6194 * @throws MWException
6195 * @return string
6196 */
6197 public function unserializeHalfParsedText( $data ) {
6198 wfDeprecated( __METHOD__, '1.31' );
6199 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6200 throw new MWException( __METHOD__ . ': invalid version' );
6201 }
6202
6203 # First, extract the strip state.
6204 $texts = [ $data['text'] ];
6205 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6206
6207 # Now renumber links
6208 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6209
6210 # Should be good to go.
6211 return $texts[0];
6212 }
6213
6214 /**
6215 * Returns true if the given array, presumed to be generated by
6216 * serializeHalfParsedText(), is compatible with the current version of the
6217 * parser.
6218 *
6219 * @deprecated since 1.31
6220 * @param array $data
6221 *
6222 * @return bool
6223 */
6224 public function isValidHalfParsedText( $data ) {
6225 wfDeprecated( __METHOD__, '1.31' );
6226 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6227 }
6228
6229 /**
6230 * Parsed a width param of imagelink like 300px or 200x300px
6231 *
6232 * @param string $value
6233 * @param bool $parseHeight
6234 *
6235 * @return array
6236 * @since 1.20
6237 */
6238 public static function parseWidthParam( $value, $parseHeight = true ) {
6239 $parsedWidthParam = [];
6240 if ( $value === '' ) {
6241 return $parsedWidthParam;
6242 }
6243 $m = [];
6244 # (T15500) In both cases (width/height and width only),
6245 # permit trailing "px" for backward compatibility.
6246 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6247 $width = intval( $m[1] );
6248 $height = intval( $m[2] );
6249 $parsedWidthParam['width'] = $width;
6250 $parsedWidthParam['height'] = $height;
6251 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6252 $width = intval( $value );
6253 $parsedWidthParam['width'] = $width;
6254 }
6255 return $parsedWidthParam;
6256 }
6257
6258 /**
6259 * Lock the current instance of the parser.
6260 *
6261 * This is meant to stop someone from calling the parser
6262 * recursively and messing up all the strip state.
6263 *
6264 * @throws MWException If parser is in a parse
6265 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6266 */
6267 protected function lock() {
6268 if ( $this->mInParse ) {
6269 throw new MWException( "Parser state cleared while parsing. "
6270 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse );
6271 }
6272
6273 // Save the backtrace when locking, so that if some code tries locking again,
6274 // we can print the lock owner's backtrace for easier debugging
6275 $e = new Exception;
6276 $this->mInParse = $e->getTraceAsString();
6277
6278 $recursiveCheck = new ScopedCallback( function () {
6279 $this->mInParse = false;
6280 } );
6281
6282 return $recursiveCheck;
6283 }
6284
6285 /**
6286 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6287 *
6288 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6289 * or if there is more than one <p/> tag in the input HTML.
6290 *
6291 * @param string $html
6292 * @return string
6293 * @since 1.24
6294 */
6295 public static function stripOuterParagraph( $html ) {
6296 $m = [];
6297 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6298 if ( strpos( $m[1], '</p>' ) === false ) {
6299 $html = $m[1];
6300 }
6301 }
6302
6303 return $html;
6304 }
6305
6306 /**
6307 * Return this parser if it is not doing anything, otherwise
6308 * get a fresh parser. You can use this method by doing
6309 * $myParser = $wgParser->getFreshParser(), or more simply
6310 * $wgParser->getFreshParser()->parse( ... );
6311 * if you're unsure if $wgParser is safe to use.
6312 *
6313 * @since 1.24
6314 * @return Parser A parser object that is not parsing anything
6315 */
6316 public function getFreshParser() {
6317 if ( $this->mInParse ) {
6318 return $this->factory->create();
6319 } else {
6320 return $this;
6321 }
6322 }
6323
6324 /**
6325 * Set's up the PHP implementation of OOUI for use in this request
6326 * and instructs OutputPage to enable OOUI for itself.
6327 *
6328 * @since 1.26
6329 */
6330 public function enableOOUI() {
6331 OutputPage::setupOOUI();
6332 $this->mOutput->setEnableOOUI( true );
6333 }
6334 }