Disable expensive {{REVISIONID}} magic word in miser mode
[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 # This code path is buggy and deprecated!
1456 wfDeprecated( 'disabling tidy', '1.33' );
1457 $tidyregs = [
1458 # ''Something [http://www.cool.com cool''] -->
1459 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1460 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1461 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1462 # fix up an anchor inside another anchor, only
1463 # at least for a single single nested link (T5695)
1464 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1465 '\\1\\2</a>\\3</a>\\1\\4</a>',
1466 # fix div inside inline elements- doBlockLevels won't wrap a line which
1467 # contains a div, so fix it up here; replace
1468 # div with escaped text
1469 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1470 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
1471 # remove empty italic or bold tag pairs, some
1472 # introduced by rules above
1473 '/<([bi])><\/\\1>/' => '',
1474 ];
1475
1476 $text = preg_replace(
1477 array_keys( $tidyregs ),
1478 array_values( $tidyregs ),
1479 $text );
1480 }
1481
1482 if ( $isMain ) {
1483 Hooks::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1484 }
1485
1486 return $text;
1487 }
1488
1489 /**
1490 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1491 * magic external links.
1492 *
1493 * DML
1494 * @private
1495 *
1496 * @param string $text
1497 *
1498 * @return string
1499 */
1500 public function doMagicLinks( $text ) {
1501 $prots = wfUrlProtocolsWithoutProtRel();
1502 $urlChar = self::EXT_LINK_URL_CLASS;
1503 $addr = self::EXT_LINK_ADDR;
1504 $space = self::SPACE_NOT_NL; # non-newline space
1505 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1506 $spaces = "$space++"; # possessive match of 1 or more spaces
1507 $text = preg_replace_callback(
1508 '!(?: # Start cases
1509 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1510 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1511 (\b # m[3]: Free external links
1512 (?i:$prots)
1513 ($addr$urlChar*) # m[4]: Post-protocol path
1514 ) |
1515 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1516 ([0-9]+)\b |
1517 \bISBN $spaces ( # m[6]: ISBN, capture number
1518 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1519 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1520 [0-9Xx] # check digit
1521 )\b
1522 )!xu", [ $this, 'magicLinkCallback' ], $text );
1523 return $text;
1524 }
1525
1526 /**
1527 * @throws MWException
1528 * @param array $m
1529 * @return string HTML
1530 */
1531 public function magicLinkCallback( $m ) {
1532 if ( isset( $m[1] ) && $m[1] !== '' ) {
1533 # Skip anchor
1534 return $m[0];
1535 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1536 # Skip HTML element
1537 return $m[0];
1538 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1539 # Free external link
1540 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1541 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1542 # RFC or PMID
1543 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1544 if ( !$this->mOptions->getMagicRFCLinks() ) {
1545 return $m[0];
1546 }
1547 $keyword = 'RFC';
1548 $urlmsg = 'rfcurl';
1549 $cssClass = 'mw-magiclink-rfc';
1550 $trackingCat = 'magiclink-tracking-rfc';
1551 $id = $m[5];
1552 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1553 if ( !$this->mOptions->getMagicPMIDLinks() ) {
1554 return $m[0];
1555 }
1556 $keyword = 'PMID';
1557 $urlmsg = 'pubmedurl';
1558 $cssClass = 'mw-magiclink-pmid';
1559 $trackingCat = 'magiclink-tracking-pmid';
1560 $id = $m[5];
1561 } else {
1562 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1563 substr( $m[0], 0, 20 ) . '"' );
1564 }
1565 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1566 $this->addTrackingCategory( $trackingCat );
1567 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle );
1568 } elseif ( isset( $m[6] ) && $m[6] !== ''
1569 && $this->mOptions->getMagicISBNLinks()
1570 ) {
1571 # ISBN
1572 $isbn = $m[6];
1573 $space = self::SPACE_NOT_NL; # non-newline space
1574 $isbn = preg_replace( "/$space/", ' ', $isbn );
1575 $num = strtr( $isbn, [
1576 '-' => '',
1577 ' ' => '',
1578 'x' => 'X',
1579 ] );
1580 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1581 return $this->getLinkRenderer()->makeKnownLink(
1582 SpecialPage::getTitleFor( 'Booksources', $num ),
1583 "ISBN $isbn",
1584 [
1585 'class' => 'internal mw-magiclink-isbn',
1586 'title' => false // suppress title attribute
1587 ]
1588 );
1589 } else {
1590 return $m[0];
1591 }
1592 }
1593
1594 /**
1595 * Make a free external link, given a user-supplied URL
1596 *
1597 * @param string $url
1598 * @param int $numPostProto
1599 * The number of characters after the protocol.
1600 * @return string HTML
1601 * @private
1602 */
1603 public function makeFreeExternalLink( $url, $numPostProto ) {
1604 $trail = '';
1605
1606 # The characters '<' and '>' (which were escaped by
1607 # removeHTMLtags()) should not be included in
1608 # URLs, per RFC 2396.
1609 # Make &nbsp; terminate a URL as well (bug T84937)
1610 $m2 = [];
1611 if ( preg_match(
1612 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1613 $url,
1614 $m2,
1615 PREG_OFFSET_CAPTURE
1616 ) ) {
1617 $trail = substr( $url, $m2[0][1] ) . $trail;
1618 $url = substr( $url, 0, $m2[0][1] );
1619 }
1620
1621 # Move trailing punctuation to $trail
1622 $sep = ',;\.:!?';
1623 # If there is no left bracket, then consider right brackets fair game too
1624 if ( strpos( $url, '(' ) === false ) {
1625 $sep .= ')';
1626 }
1627
1628 $urlRev = strrev( $url );
1629 $numSepChars = strspn( $urlRev, $sep );
1630 # Don't break a trailing HTML entity by moving the ; into $trail
1631 # This is in hot code, so use substr_compare to avoid having to
1632 # create a new string object for the comparison
1633 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1634 # more optimization: instead of running preg_match with a $
1635 # anchor, which can be slow, do the match on the reversed
1636 # string starting at the desired offset.
1637 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1638 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1639 $numSepChars--;
1640 }
1641 }
1642 if ( $numSepChars ) {
1643 $trail = substr( $url, -$numSepChars ) . $trail;
1644 $url = substr( $url, 0, -$numSepChars );
1645 }
1646
1647 # Verify that we still have a real URL after trail removal, and
1648 # not just lone protocol
1649 if ( strlen( $trail ) >= $numPostProto ) {
1650 return $url . $trail;
1651 }
1652
1653 $url = Sanitizer::cleanUrl( $url );
1654
1655 # Is this an external image?
1656 $text = $this->maybeMakeExternalImage( $url );
1657 if ( $text === false ) {
1658 # Not an image, make a link
1659 $text = Linker::makeExternalLink( $url,
1660 $this->getTargetLanguage()->getConverter()->markNoConversion( $url ),
1661 true, 'free',
1662 $this->getExternalLinkAttribs( $url ), $this->mTitle );
1663 # Register it in the output object...
1664 $this->mOutput->addExternalLink( $url );
1665 }
1666 return $text . $trail;
1667 }
1668
1669 /**
1670 * Parse headers and return html
1671 *
1672 * @private
1673 *
1674 * @param string $text
1675 *
1676 * @return string
1677 */
1678 public function doHeadings( $text ) {
1679 for ( $i = 6; $i >= 1; --$i ) {
1680 $h = str_repeat( '=', $i );
1681 // Trim non-newline whitespace from headings
1682 // Using \s* will break for: "==\n===\n" and parse as <h2>=</h2>
1683 $text = preg_replace( "/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m", "<h$i>\\1</h$i>", $text );
1684 }
1685 return $text;
1686 }
1687
1688 /**
1689 * Replace single quotes with HTML markup
1690 * @private
1691 *
1692 * @param string $text
1693 *
1694 * @return string The altered text
1695 */
1696 public function doAllQuotes( $text ) {
1697 $outtext = '';
1698 $lines = StringUtils::explode( "\n", $text );
1699 foreach ( $lines as $line ) {
1700 $outtext .= $this->doQuotes( $line ) . "\n";
1701 }
1702 $outtext = substr( $outtext, 0, -1 );
1703 return $outtext;
1704 }
1705
1706 /**
1707 * Helper function for doAllQuotes()
1708 *
1709 * @param string $text
1710 *
1711 * @return string
1712 */
1713 public function doQuotes( $text ) {
1714 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1715 $countarr = count( $arr );
1716 if ( $countarr == 1 ) {
1717 return $text;
1718 }
1719
1720 // First, do some preliminary work. This may shift some apostrophes from
1721 // being mark-up to being text. It also counts the number of occurrences
1722 // of bold and italics mark-ups.
1723 $numbold = 0;
1724 $numitalics = 0;
1725 for ( $i = 1; $i < $countarr; $i += 2 ) {
1726 $thislen = strlen( $arr[$i] );
1727 // If there are ever four apostrophes, assume the first is supposed to
1728 // be text, and the remaining three constitute mark-up for bold text.
1729 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1730 if ( $thislen == 4 ) {
1731 $arr[$i - 1] .= "'";
1732 $arr[$i] = "'''";
1733 $thislen = 3;
1734 } elseif ( $thislen > 5 ) {
1735 // If there are more than 5 apostrophes in a row, assume they're all
1736 // text except for the last 5.
1737 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1738 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1739 $arr[$i] = "'''''";
1740 $thislen = 5;
1741 }
1742 // Count the number of occurrences of bold and italics mark-ups.
1743 if ( $thislen == 2 ) {
1744 $numitalics++;
1745 } elseif ( $thislen == 3 ) {
1746 $numbold++;
1747 } elseif ( $thislen == 5 ) {
1748 $numitalics++;
1749 $numbold++;
1750 }
1751 }
1752
1753 // If there is an odd number of both bold and italics, it is likely
1754 // that one of the bold ones was meant to be an apostrophe followed
1755 // by italics. Which one we cannot know for certain, but it is more
1756 // likely to be one that has a single-letter word before it.
1757 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1758 $firstsingleletterword = -1;
1759 $firstmultiletterword = -1;
1760 $firstspace = -1;
1761 for ( $i = 1; $i < $countarr; $i += 2 ) {
1762 if ( strlen( $arr[$i] ) == 3 ) {
1763 $x1 = substr( $arr[$i - 1], -1 );
1764 $x2 = substr( $arr[$i - 1], -2, 1 );
1765 if ( $x1 === ' ' ) {
1766 if ( $firstspace == -1 ) {
1767 $firstspace = $i;
1768 }
1769 } elseif ( $x2 === ' ' ) {
1770 $firstsingleletterword = $i;
1771 // if $firstsingleletterword is set, we don't
1772 // look at the other options, so we can bail early.
1773 break;
1774 } else {
1775 if ( $firstmultiletterword == -1 ) {
1776 $firstmultiletterword = $i;
1777 }
1778 }
1779 }
1780 }
1781
1782 // If there is a single-letter word, use it!
1783 if ( $firstsingleletterword > -1 ) {
1784 $arr[$firstsingleletterword] = "''";
1785 $arr[$firstsingleletterword - 1] .= "'";
1786 } elseif ( $firstmultiletterword > -1 ) {
1787 // If not, but there's a multi-letter word, use that one.
1788 $arr[$firstmultiletterword] = "''";
1789 $arr[$firstmultiletterword - 1] .= "'";
1790 } elseif ( $firstspace > -1 ) {
1791 // ... otherwise use the first one that has neither.
1792 // (notice that it is possible for all three to be -1 if, for example,
1793 // there is only one pentuple-apostrophe in the line)
1794 $arr[$firstspace] = "''";
1795 $arr[$firstspace - 1] .= "'";
1796 }
1797 }
1798
1799 // Now let's actually convert our apostrophic mush to HTML!
1800 $output = '';
1801 $buffer = '';
1802 $state = '';
1803 $i = 0;
1804 foreach ( $arr as $r ) {
1805 if ( ( $i % 2 ) == 0 ) {
1806 if ( $state === 'both' ) {
1807 $buffer .= $r;
1808 } else {
1809 $output .= $r;
1810 }
1811 } else {
1812 $thislen = strlen( $r );
1813 if ( $thislen == 2 ) {
1814 if ( $state === 'i' ) {
1815 $output .= '</i>';
1816 $state = '';
1817 } elseif ( $state === 'bi' ) {
1818 $output .= '</i>';
1819 $state = 'b';
1820 } elseif ( $state === 'ib' ) {
1821 $output .= '</b></i><b>';
1822 $state = 'b';
1823 } elseif ( $state === 'both' ) {
1824 $output .= '<b><i>' . $buffer . '</i>';
1825 $state = 'b';
1826 } else { // $state can be 'b' or ''
1827 $output .= '<i>';
1828 $state .= 'i';
1829 }
1830 } elseif ( $thislen == 3 ) {
1831 if ( $state === 'b' ) {
1832 $output .= '</b>';
1833 $state = '';
1834 } elseif ( $state === 'bi' ) {
1835 $output .= '</i></b><i>';
1836 $state = 'i';
1837 } elseif ( $state === 'ib' ) {
1838 $output .= '</b>';
1839 $state = 'i';
1840 } elseif ( $state === 'both' ) {
1841 $output .= '<i><b>' . $buffer . '</b>';
1842 $state = 'i';
1843 } else { // $state can be 'i' or ''
1844 $output .= '<b>';
1845 $state .= 'b';
1846 }
1847 } elseif ( $thislen == 5 ) {
1848 if ( $state === 'b' ) {
1849 $output .= '</b><i>';
1850 $state = 'i';
1851 } elseif ( $state === 'i' ) {
1852 $output .= '</i><b>';
1853 $state = 'b';
1854 } elseif ( $state === 'bi' ) {
1855 $output .= '</i></b>';
1856 $state = '';
1857 } elseif ( $state === 'ib' ) {
1858 $output .= '</b></i>';
1859 $state = '';
1860 } elseif ( $state === 'both' ) {
1861 $output .= '<i><b>' . $buffer . '</b></i>';
1862 $state = '';
1863 } else { // ($state == '')
1864 $buffer = '';
1865 $state = 'both';
1866 }
1867 }
1868 }
1869 $i++;
1870 }
1871 // Now close all remaining tags. Notice that the order is important.
1872 if ( $state === 'b' || $state === 'ib' ) {
1873 $output .= '</b>';
1874 }
1875 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1876 $output .= '</i>';
1877 }
1878 if ( $state === 'bi' ) {
1879 $output .= '</b>';
1880 }
1881 // There might be lonely ''''', so make sure we have a buffer
1882 if ( $state === 'both' && $buffer ) {
1883 $output .= '<b><i>' . $buffer . '</i></b>';
1884 }
1885 return $output;
1886 }
1887
1888 /**
1889 * Replace external links (REL)
1890 *
1891 * Note: this is all very hackish and the order of execution matters a lot.
1892 * Make sure to run tests/parser/parserTests.php if you change this code.
1893 *
1894 * @private
1895 *
1896 * @param string $text
1897 *
1898 * @throws MWException
1899 * @return string
1900 */
1901 public function replaceExternalLinks( $text ) {
1902 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1903 if ( $bits === false ) {
1904 throw new MWException( "PCRE needs to be compiled with "
1905 . "--enable-unicode-properties in order for MediaWiki to function" );
1906 }
1907 $s = array_shift( $bits );
1908
1909 $i = 0;
1910 while ( $i < count( $bits ) ) {
1911 $url = $bits[$i++];
1912 $i++; // protocol
1913 $text = $bits[$i++];
1914 $trail = $bits[$i++];
1915
1916 # The characters '<' and '>' (which were escaped by
1917 # removeHTMLtags()) should not be included in
1918 # URLs, per RFC 2396.
1919 $m2 = [];
1920 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1921 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1922 $url = substr( $url, 0, $m2[0][1] );
1923 }
1924
1925 # If the link text is an image URL, replace it with an <img> tag
1926 # This happened by accident in the original parser, but some people used it extensively
1927 $img = $this->maybeMakeExternalImage( $text );
1928 if ( $img !== false ) {
1929 $text = $img;
1930 }
1931
1932 $dtrail = '';
1933
1934 # Set linktype for CSS
1935 $linktype = 'text';
1936
1937 # No link text, e.g. [http://domain.tld/some.link]
1938 if ( $text == '' ) {
1939 # Autonumber
1940 $langObj = $this->getTargetLanguage();
1941 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1942 $linktype = 'autonumber';
1943 } else {
1944 # Have link text, e.g. [http://domain.tld/some.link text]s
1945 # Check for trail
1946 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1947 }
1948
1949 // Excluding protocol-relative URLs may avoid many false positives.
1950 if ( preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
1951 $text = $this->getTargetLanguage()->getConverter()->markNoConversion( $text );
1952 }
1953
1954 $url = Sanitizer::cleanUrl( $url );
1955
1956 # Use the encoded URL
1957 # This means that users can paste URLs directly into the text
1958 # Funny characters like ö aren't valid in URLs anyway
1959 # This was changed in August 2004
1960 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1961 $this->getExternalLinkAttribs( $url ), $this->mTitle ) . $dtrail . $trail;
1962
1963 # Register link in the output object.
1964 $this->mOutput->addExternalLink( $url );
1965 }
1966
1967 return $s;
1968 }
1969
1970 /**
1971 * Get the rel attribute for a particular external link.
1972 *
1973 * @since 1.21
1974 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1975 * nofollow if appropriate
1976 * @param Title|null $title Optional Title, for wgNoFollowNsExceptions lookups
1977 * @return string|null Rel attribute for $url
1978 */
1979 public static function getExternalLinkRel( $url = false, $title = null ) {
1980 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1981 $ns = $title ? $title->getNamespace() : false;
1982 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1983 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1984 ) {
1985 return 'nofollow';
1986 }
1987 return null;
1988 }
1989
1990 /**
1991 * Get an associative array of additional HTML attributes appropriate for a
1992 * particular external link. This currently may include rel => nofollow
1993 * (depending on configuration, namespace, and the URL's domain) and/or a
1994 * target attribute (depending on configuration).
1995 *
1996 * @param string $url URL to extract the domain from for rel =>
1997 * nofollow if appropriate
1998 * @return array Associative array of HTML attributes
1999 */
2000 public function getExternalLinkAttribs( $url ) {
2001 $attribs = [];
2002 $rel = self::getExternalLinkRel( $url, $this->mTitle );
2003
2004 $target = $this->mOptions->getExternalLinkTarget();
2005 if ( $target ) {
2006 $attribs['target'] = $target;
2007 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
2008 // T133507. New windows can navigate parent cross-origin.
2009 // Including noreferrer due to lacking browser
2010 // support of noopener. Eventually noreferrer should be removed.
2011 if ( $rel !== '' ) {
2012 $rel .= ' ';
2013 }
2014 $rel .= 'noreferrer noopener';
2015 }
2016 }
2017 $attribs['rel'] = $rel;
2018 return $attribs;
2019 }
2020
2021 /**
2022 * Replace unusual escape codes in a URL with their equivalent characters
2023 *
2024 * This generally follows the syntax defined in RFC 3986, with special
2025 * consideration for HTTP query strings.
2026 *
2027 * @param string $url
2028 * @return string
2029 */
2030 public static function normalizeLinkUrl( $url ) {
2031 # Test for RFC 3986 IPv6 syntax
2032 $scheme = '[a-z][a-z0-9+.-]*:';
2033 $userinfo = '(?:[a-z0-9\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*';
2034 $ipv6Host = '\\[((?:[0-9a-f:]|%3[0-A]|%[46][1-6])+)\\]';
2035 if ( preg_match( "<^(?:{$scheme})?//(?:{$userinfo}@)?{$ipv6Host}(?:[:/?#].*|)$>i", $url, $m ) &&
2036 IP::isValid( rawurldecode( $m[1] ) )
2037 ) {
2038 $isIPv6 = rawurldecode( $m[1] );
2039 } else {
2040 $isIPv6 = false;
2041 }
2042
2043 # Make sure unsafe characters are encoded
2044 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
2045 function ( $m ) {
2046 return rawurlencode( $m[0] );
2047 },
2048 $url
2049 );
2050
2051 $ret = '';
2052 $end = strlen( $url );
2053
2054 # Fragment part - 'fragment'
2055 $start = strpos( $url, '#' );
2056 if ( $start !== false && $start < $end ) {
2057 $ret = self::normalizeUrlComponent(
2058 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2059 $end = $start;
2060 }
2061
2062 # Query part - 'query' minus &=+;
2063 $start = strpos( $url, '?' );
2064 if ( $start !== false && $start < $end ) {
2065 $ret = self::normalizeUrlComponent(
2066 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2067 $end = $start;
2068 }
2069
2070 # Scheme and path part - 'pchar'
2071 # (we assume no userinfo or encoded colons in the host)
2072 $ret = self::normalizeUrlComponent(
2073 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2074
2075 # Fix IPv6 syntax
2076 if ( $isIPv6 !== false ) {
2077 $ipv6Host = "%5B({$isIPv6})%5D";
2078 $ret = preg_replace(
2079 "<^((?:{$scheme})?//(?:{$userinfo}@)?){$ipv6Host}(?=[:/?#]|$)>i",
2080 "$1[$2]",
2081 $ret
2082 );
2083 }
2084
2085 return $ret;
2086 }
2087
2088 private static function normalizeUrlComponent( $component, $unsafe ) {
2089 $callback = function ( $matches ) use ( $unsafe ) {
2090 $char = urldecode( $matches[0] );
2091 $ord = ord( $char );
2092 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2093 # Unescape it
2094 return $char;
2095 } else {
2096 # Leave it escaped, but use uppercase for a-f
2097 return strtoupper( $matches[0] );
2098 }
2099 };
2100 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2101 }
2102
2103 /**
2104 * make an image if it's allowed, either through the global
2105 * option, through the exception, or through the on-wiki whitelist
2106 *
2107 * @param string $url
2108 *
2109 * @return string
2110 */
2111 private function maybeMakeExternalImage( $url ) {
2112 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
2113 $imagesexception = !empty( $imagesfrom );
2114 $text = false;
2115 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2116 if ( $imagesexception && is_array( $imagesfrom ) ) {
2117 $imagematch = false;
2118 foreach ( $imagesfrom as $match ) {
2119 if ( strpos( $url, $match ) === 0 ) {
2120 $imagematch = true;
2121 break;
2122 }
2123 }
2124 } elseif ( $imagesexception ) {
2125 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2126 } else {
2127 $imagematch = false;
2128 }
2129
2130 if ( $this->mOptions->getAllowExternalImages()
2131 || ( $imagesexception && $imagematch )
2132 ) {
2133 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
2134 # Image found
2135 $text = Linker::makeExternalImage( $url );
2136 }
2137 }
2138 if ( !$text && $this->mOptions->getEnableImageWhitelist()
2139 && preg_match( self::EXT_IMAGE_REGEX, $url )
2140 ) {
2141 $whitelist = explode(
2142 "\n",
2143 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2144 );
2145
2146 foreach ( $whitelist as $entry ) {
2147 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2148 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
2149 continue;
2150 }
2151 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2152 # Image matches a whitelist entry
2153 $text = Linker::makeExternalImage( $url );
2154 break;
2155 }
2156 }
2157 }
2158 return $text;
2159 }
2160
2161 /**
2162 * Process [[ ]] wikilinks
2163 *
2164 * @param string $s
2165 *
2166 * @return string Processed text
2167 *
2168 * @private
2169 */
2170 public function replaceInternalLinks( $s ) {
2171 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
2172 return $s;
2173 }
2174
2175 /**
2176 * Process [[ ]] wikilinks (RIL)
2177 * @param string &$s
2178 * @throws MWException
2179 * @return LinkHolderArray
2180 *
2181 * @private
2182 */
2183 public function replaceInternalLinks2( &$s ) {
2184 static $tc = false, $e1, $e1_img;
2185 # the % is needed to support urlencoded titles as well
2186 if ( !$tc ) {
2187 $tc = Title::legalChars() . '#%';
2188 # Match a link having the form [[namespace:link|alternate]]trail
2189 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2190 # Match cases where there is no "]]", which might still be images
2191 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2192 }
2193
2194 $holders = new LinkHolderArray( $this );
2195
2196 # split the entire text string on occurrences of [[
2197 $a = StringUtils::explode( '[[', ' ' . $s );
2198 # get the first element (all text up to first [[), and remove the space we added
2199 $s = $a->current();
2200 $a->next();
2201 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2202 $s = substr( $s, 1 );
2203
2204 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2205 $e2 = null;
2206 if ( $useLinkPrefixExtension ) {
2207 # Match the end of a line for a word that's not followed by whitespace,
2208 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2209 $charset = $this->contLang->linkPrefixCharset();
2210 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2211 }
2212
2213 if ( is_null( $this->mTitle ) ) {
2214 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2215 }
2216 $nottalk = !$this->mTitle->isTalkPage();
2217
2218 if ( $useLinkPrefixExtension ) {
2219 $m = [];
2220 if ( preg_match( $e2, $s, $m ) ) {
2221 $first_prefix = $m[2];
2222 } else {
2223 $first_prefix = false;
2224 }
2225 } else {
2226 $prefix = '';
2227 }
2228
2229 $useSubpages = $this->areSubpagesAllowed();
2230
2231 # Loop for each link
2232 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2233 # Check for excessive memory usage
2234 if ( $holders->isBig() ) {
2235 # Too big
2236 # Do the existence check, replace the link holders and clear the array
2237 $holders->replace( $s );
2238 $holders->clear();
2239 }
2240
2241 if ( $useLinkPrefixExtension ) {
2242 if ( preg_match( $e2, $s, $m ) ) {
2243 $prefix = $m[2];
2244 $s = $m[1];
2245 } else {
2246 $prefix = '';
2247 }
2248 # first link
2249 if ( $first_prefix ) {
2250 $prefix = $first_prefix;
2251 $first_prefix = false;
2252 }
2253 }
2254
2255 $might_be_img = false;
2256
2257 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2258 $text = $m[2];
2259 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2260 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2261 # the real problem is with the $e1 regex
2262 # See T1500.
2263 # Still some problems for cases where the ] is meant to be outside punctuation,
2264 # and no image is in sight. See T4095.
2265 if ( $text !== ''
2266 && substr( $m[3], 0, 1 ) === ']'
2267 && strpos( $text, '[' ) !== false
2268 ) {
2269 $text .= ']'; # so that replaceExternalLinks($text) works later
2270 $m[3] = substr( $m[3], 1 );
2271 }
2272 # fix up urlencoded title texts
2273 if ( strpos( $m[1], '%' ) !== false ) {
2274 # Should anchors '#' also be rejected?
2275 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2276 }
2277 $trail = $m[3];
2278 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2279 # Invalid, but might be an image with a link in its caption
2280 $might_be_img = true;
2281 $text = $m[2];
2282 if ( strpos( $m[1], '%' ) !== false ) {
2283 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2284 }
2285 $trail = "";
2286 } else { # Invalid form; output directly
2287 $s .= $prefix . '[[' . $line;
2288 continue;
2289 }
2290
2291 $origLink = ltrim( $m[1], ' ' );
2292
2293 # Don't allow internal links to pages containing
2294 # PROTO: where PROTO is a valid URL protocol; these
2295 # should be external links.
2296 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) {
2297 $s .= $prefix . '[[' . $line;
2298 continue;
2299 }
2300
2301 # Make subpage if necessary
2302 if ( $useSubpages ) {
2303 $link = $this->maybeDoSubpageLink( $origLink, $text );
2304 } else {
2305 $link = $origLink;
2306 }
2307
2308 // \x7f isn't a default legal title char, so most likely strip
2309 // markers will force us into the "invalid form" path above. But,
2310 // just in case, let's assert that xmlish tags aren't valid in
2311 // the title position.
2312 $unstrip = $this->mStripState->killMarkers( $link );
2313 $noMarkers = ( $unstrip === $link );
2314
2315 $nt = $noMarkers ? Title::newFromText( $link ) : null;
2316 if ( $nt === null ) {
2317 $s .= $prefix . '[[' . $line;
2318 continue;
2319 }
2320
2321 $ns = $nt->getNamespace();
2322 $iw = $nt->getInterwiki();
2323
2324 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2325
2326 if ( $might_be_img ) { # if this is actually an invalid link
2327 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2328 $found = false;
2329 while ( true ) {
2330 # look at the next 'line' to see if we can close it there
2331 $a->next();
2332 $next_line = $a->current();
2333 if ( $next_line === false || $next_line === null ) {
2334 break;
2335 }
2336 $m = explode( ']]', $next_line, 3 );
2337 if ( count( $m ) == 3 ) {
2338 # the first ]] closes the inner link, the second the image
2339 $found = true;
2340 $text .= "[[{$m[0]}]]{$m[1]}";
2341 $trail = $m[2];
2342 break;
2343 } elseif ( count( $m ) == 2 ) {
2344 # if there's exactly one ]] that's fine, we'll keep looking
2345 $text .= "[[{$m[0]}]]{$m[1]}";
2346 } else {
2347 # if $next_line is invalid too, we need look no further
2348 $text .= '[[' . $next_line;
2349 break;
2350 }
2351 }
2352 if ( !$found ) {
2353 # we couldn't find the end of this imageLink, so output it raw
2354 # but don't ignore what might be perfectly normal links in the text we've examined
2355 $holders->merge( $this->replaceInternalLinks2( $text ) );
2356 $s .= "{$prefix}[[$link|$text";
2357 # note: no $trail, because without an end, there *is* no trail
2358 continue;
2359 }
2360 } else { # it's not an image, so output it raw
2361 $s .= "{$prefix}[[$link|$text";
2362 # note: no $trail, because without an end, there *is* no trail
2363 continue;
2364 }
2365 }
2366
2367 $wasblank = ( $text == '' );
2368 if ( $wasblank ) {
2369 $text = $link;
2370 if ( !$noforce ) {
2371 # Strip off leading ':'
2372 $text = substr( $text, 1 );
2373 }
2374 } else {
2375 # T6598 madness. Handle the quotes only if they come from the alternate part
2376 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2377 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2378 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2379 $text = $this->doQuotes( $text );
2380 }
2381
2382 # Link not escaped by : , create the various objects
2383 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2384 # Interwikis
2385 if (
2386 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2387 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2388 in_array( $iw, $this->siteConfig->get( 'ExtraInterlanguageLinkPrefixes' ) )
2389 )
2390 ) {
2391 # T26502: filter duplicates
2392 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2393 $this->mLangLinkLanguages[$iw] = true;
2394 $this->mOutput->addLanguageLink( $nt->getFullText() );
2395 }
2396
2397 /**
2398 * Strip the whitespace interwiki links produce, see T10897
2399 */
2400 $s = rtrim( $s . $prefix ) . $trail; # T175416
2401 continue;
2402 }
2403
2404 if ( $ns == NS_FILE ) {
2405 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2406 if ( $wasblank ) {
2407 # if no parameters were passed, $text
2408 # becomes something like "File:Foo.png",
2409 # which we don't want to pass on to the
2410 # image generator
2411 $text = '';
2412 } else {
2413 # recursively parse links inside the image caption
2414 # actually, this will parse them in any other parameters, too,
2415 # but it might be hard to fix that, and it doesn't matter ATM
2416 $text = $this->replaceExternalLinks( $text );
2417 $holders->merge( $this->replaceInternalLinks2( $text ) );
2418 }
2419 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2420 $s .= $prefix . $this->armorLinks(
2421 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2422 continue;
2423 }
2424 } elseif ( $ns == NS_CATEGORY ) {
2425 /**
2426 * Strip the whitespace Category links produce, see T2087
2427 */
2428 $s = rtrim( $s . $prefix ) . $trail; # T2087, T87753
2429
2430 if ( $wasblank ) {
2431 $sortkey = $this->getDefaultSort();
2432 } else {
2433 $sortkey = $text;
2434 }
2435 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2436 $sortkey = str_replace( "\n", '', $sortkey );
2437 $sortkey = $this->getTargetLanguage()->convertCategoryKey( $sortkey );
2438 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2439
2440 continue;
2441 }
2442 }
2443
2444 # Self-link checking. For some languages, variants of the title are checked in
2445 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2446 # for linking to a different variant.
2447 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2448 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2449 continue;
2450 }
2451
2452 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2453 # @todo FIXME: Should do batch file existence checks, see comment below
2454 if ( $ns == NS_MEDIA ) {
2455 # Give extensions a chance to select the file revision for us
2456 $options = [];
2457 $descQuery = false;
2458 Hooks::run( 'BeforeParserFetchFileAndTitle',
2459 [ $this, $nt, &$options, &$descQuery ] );
2460 # Fetch and register the file (file title may be different via hooks)
2461 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2462 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2463 $s .= $prefix . $this->armorLinks(
2464 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2465 continue;
2466 }
2467
2468 # Some titles, such as valid special pages or files in foreign repos, should
2469 # be shown as bluelinks even though they're not included in the page table
2470 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2471 # batch file existence checks for NS_FILE and NS_MEDIA
2472 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2473 $this->mOutput->addLink( $nt );
2474 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2475 } else {
2476 # Links will be added to the output link list after checking
2477 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2478 }
2479 }
2480 return $holders;
2481 }
2482
2483 /**
2484 * Render a forced-blue link inline; protect against double expansion of
2485 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2486 * Since this little disaster has to split off the trail text to avoid
2487 * breaking URLs in the following text without breaking trails on the
2488 * wiki links, it's been made into a horrible function.
2489 *
2490 * @param Title $nt
2491 * @param string $text
2492 * @param string $trail
2493 * @param string $prefix
2494 * @return string HTML-wikitext mix oh yuck
2495 */
2496 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2497 list( $inside, $trail ) = Linker::splitTrail( $trail );
2498
2499 if ( $text == '' ) {
2500 $text = htmlspecialchars( $nt->getPrefixedText() );
2501 }
2502
2503 $link = $this->getLinkRenderer()->makeKnownLink(
2504 $nt, new HtmlArmor( "$prefix$text$inside" )
2505 );
2506
2507 return $this->armorLinks( $link ) . $trail;
2508 }
2509
2510 /**
2511 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2512 * going to go through further parsing steps before inline URL expansion.
2513 *
2514 * Not needed quite as much as it used to be since free links are a bit
2515 * more sensible these days. But bracketed links are still an issue.
2516 *
2517 * @param string $text More-or-less HTML
2518 * @return string Less-or-more HTML with NOPARSE bits
2519 */
2520 public function armorLinks( $text ) {
2521 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2522 self::MARKER_PREFIX . "NOPARSE$1", $text );
2523 }
2524
2525 /**
2526 * Return true if subpage links should be expanded on this page.
2527 * @return bool
2528 */
2529 public function areSubpagesAllowed() {
2530 # Some namespaces don't allow subpages
2531 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2532 }
2533
2534 /**
2535 * Handle link to subpage if necessary
2536 *
2537 * @param string $target The source of the link
2538 * @param string &$text The link text, modified as necessary
2539 * @return string The full name of the link
2540 * @private
2541 */
2542 public function maybeDoSubpageLink( $target, &$text ) {
2543 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2544 }
2545
2546 /**
2547 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2548 *
2549 * @param string $text
2550 * @param bool $linestart Whether or not this is at the start of a line.
2551 * @private
2552 * @return string The lists rendered as HTML
2553 */
2554 public function doBlockLevels( $text, $linestart ) {
2555 return BlockLevelPass::doBlockLevels( $text, $linestart );
2556 }
2557
2558 /**
2559 * Return value of a magic variable (like PAGENAME)
2560 *
2561 * @private
2562 *
2563 * @param string $index Magic variable identifier as mapped in MagicWordFactory::$mVariableIDs
2564 * @param bool|PPFrame $frame
2565 *
2566 * @throws MWException
2567 * @return string
2568 */
2569 public function getVariableValue( $index, $frame = false ) {
2570 if ( is_null( $this->mTitle ) ) {
2571 // If no title set, bad things are going to happen
2572 // later. Title should always be set since this
2573 // should only be called in the middle of a parse
2574 // operation (but the unit-tests do funky stuff)
2575 throw new MWException( __METHOD__ . ' Should only be '
2576 . ' called while parsing (no title set)' );
2577 }
2578
2579 // Avoid PHP 7.1 warning from passing $this by reference
2580 $parser = $this;
2581
2582 /**
2583 * Some of these require message or data lookups and can be
2584 * expensive to check many times.
2585 */
2586 if ( Hooks::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache ] ) ) {
2587 if ( isset( $this->mVarCache[$index] ) ) {
2588 return $this->mVarCache[$index];
2589 }
2590 }
2591
2592 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2593 Hooks::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2594
2595 // In miser mode, disable words that always cause double-parses on page save (T137900)
2596 static $slowRevWords = [ 'revisionid' => true ]; // @TODO: 'revisiontimestamp'
2597 if (
2598 isset( $slowRevWords[$index] ) &&
2599 $this->siteConfig->get( 'MiserMode' ) &&
2600 !$this->mOptions->getInterfaceMessage() &&
2601 // @TODO: disallow this word on all namespaces
2602 MWNamespace::isContent( $this->mTitle->getNamespace() )
2603 ) {
2604 return $this->mRevisionId ? '-' : '';
2605 };
2606
2607 $pageLang = $this->getFunctionLang();
2608
2609 switch ( $index ) {
2610 case '!':
2611 $value = '|';
2612 break;
2613 case 'currentmonth':
2614 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ), true );
2615 break;
2616 case 'currentmonth1':
2617 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ), true );
2618 break;
2619 case 'currentmonthname':
2620 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2621 break;
2622 case 'currentmonthnamegen':
2623 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2624 break;
2625 case 'currentmonthabbrev':
2626 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2627 break;
2628 case 'currentday':
2629 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ), true );
2630 break;
2631 case 'currentday2':
2632 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ), true );
2633 break;
2634 case 'localmonth':
2635 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ), true );
2636 break;
2637 case 'localmonth1':
2638 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ), true );
2639 break;
2640 case 'localmonthname':
2641 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2642 break;
2643 case 'localmonthnamegen':
2644 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2645 break;
2646 case 'localmonthabbrev':
2647 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2648 break;
2649 case 'localday':
2650 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ), true );
2651 break;
2652 case 'localday2':
2653 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ), true );
2654 break;
2655 case 'pagename':
2656 $value = wfEscapeWikiText( $this->mTitle->getText() );
2657 break;
2658 case 'pagenamee':
2659 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2660 break;
2661 case 'fullpagename':
2662 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2663 break;
2664 case 'fullpagenamee':
2665 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2666 break;
2667 case 'subpagename':
2668 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2669 break;
2670 case 'subpagenamee':
2671 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2672 break;
2673 case 'rootpagename':
2674 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2675 break;
2676 case 'rootpagenamee':
2677 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2678 ' ',
2679 '_',
2680 $this->mTitle->getRootText()
2681 ) ) );
2682 break;
2683 case 'basepagename':
2684 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2685 break;
2686 case 'basepagenamee':
2687 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2688 ' ',
2689 '_',
2690 $this->mTitle->getBaseText()
2691 ) ) );
2692 break;
2693 case 'talkpagename':
2694 if ( $this->mTitle->canHaveTalkPage() ) {
2695 $talkPage = $this->mTitle->getTalkPage();
2696 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2697 } else {
2698 $value = '';
2699 }
2700 break;
2701 case 'talkpagenamee':
2702 if ( $this->mTitle->canHaveTalkPage() ) {
2703 $talkPage = $this->mTitle->getTalkPage();
2704 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2705 } else {
2706 $value = '';
2707 }
2708 break;
2709 case 'subjectpagename':
2710 $subjPage = $this->mTitle->getSubjectPage();
2711 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2712 break;
2713 case 'subjectpagenamee':
2714 $subjPage = $this->mTitle->getSubjectPage();
2715 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2716 break;
2717 case 'pageid': // requested in T25427
2718 $pageid = $this->getTitle()->getArticleID();
2719 if ( $pageid == 0 ) {
2720 # 0 means the page doesn't exist in the database,
2721 # which means the user is previewing a new page.
2722 # The vary-revision flag must be set, because the magic word
2723 # will have a different value once the page is saved.
2724 $this->mOutput->setFlag( 'vary-revision' );
2725 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2726 }
2727 $value = $pageid ?: null;
2728 break;
2729 case 'revisionid':
2730 # Let the edit saving system know we should parse the page
2731 # *after* a revision ID has been assigned.
2732 $this->mOutput->setFlag( 'vary-revision-id' );
2733 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2734 $value = $this->mRevisionId;
2735
2736 if ( !$value ) {
2737 $rev = $this->getRevisionObject();
2738 if ( $rev ) {
2739 $value = $rev->getId();
2740 }
2741 }
2742
2743 if ( !$value ) {
2744 $value = $this->mOptions->getSpeculativeRevId();
2745 if ( $value ) {
2746 $this->mOutput->setSpeculativeRevIdUsed( $value );
2747 }
2748 }
2749 break;
2750 case 'revisionday':
2751 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self::MAX_TTS, $index );
2752 break;
2753 case 'revisionday2':
2754 $value = $this->getRevisionTimestampSubstring( 6, 2, self::MAX_TTS, $index );
2755 break;
2756 case 'revisionmonth':
2757 $value = $this->getRevisionTimestampSubstring( 4, 2, self::MAX_TTS, $index );
2758 break;
2759 case 'revisionmonth1':
2760 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self::MAX_TTS, $index );
2761 break;
2762 case 'revisionyear':
2763 $value = $this->getRevisionTimestampSubstring( 0, 4, self::MAX_TTS, $index );
2764 break;
2765 case 'revisiontimestamp':
2766 # Let the edit saving system know we should parse the page
2767 # *after* a revision ID has been assigned. This is for null edits.
2768 $this->mOutput->setFlag( 'vary-revision' );
2769 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2770 $value = $this->getRevisionTimestamp();
2771 break;
2772 case 'revisionuser':
2773 # Let the edit saving system know we should parse the page
2774 # *after* a revision ID has been assigned for null edits.
2775 $this->mOutput->setFlag( 'vary-user' );
2776 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-user...\n" );
2777 $value = $this->getRevisionUser();
2778 break;
2779 case 'revisionsize':
2780 $value = $this->getRevisionSize();
2781 break;
2782 case 'namespace':
2783 $value = str_replace( '_', ' ',
2784 $this->contLang->getNsText( $this->mTitle->getNamespace() ) );
2785 break;
2786 case 'namespacee':
2787 $value = wfUrlencode( $this->contLang->getNsText( $this->mTitle->getNamespace() ) );
2788 break;
2789 case 'namespacenumber':
2790 $value = $this->mTitle->getNamespace();
2791 break;
2792 case 'talkspace':
2793 $value = $this->mTitle->canHaveTalkPage()
2794 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
2795 : '';
2796 break;
2797 case 'talkspacee':
2798 $value = $this->mTitle->canHaveTalkPage() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2799 break;
2800 case 'subjectspace':
2801 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
2802 break;
2803 case 'subjectspacee':
2804 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2805 break;
2806 case 'currentdayname':
2807 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
2808 break;
2809 case 'currentyear':
2810 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
2811 break;
2812 case 'currenttime':
2813 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2814 break;
2815 case 'currenthour':
2816 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
2817 break;
2818 case 'currentweek':
2819 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2820 # int to remove the padding
2821 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
2822 break;
2823 case 'currentdow':
2824 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
2825 break;
2826 case 'localdayname':
2827 $value = $pageLang->getWeekdayName(
2828 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
2829 );
2830 break;
2831 case 'localyear':
2832 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
2833 break;
2834 case 'localtime':
2835 $value = $pageLang->time(
2836 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
2837 false,
2838 false
2839 );
2840 break;
2841 case 'localhour':
2842 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
2843 break;
2844 case 'localweek':
2845 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2846 # int to remove the padding
2847 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
2848 break;
2849 case 'localdow':
2850 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
2851 break;
2852 case 'numberofarticles':
2853 $value = $pageLang->formatNum( SiteStats::articles() );
2854 break;
2855 case 'numberoffiles':
2856 $value = $pageLang->formatNum( SiteStats::images() );
2857 break;
2858 case 'numberofusers':
2859 $value = $pageLang->formatNum( SiteStats::users() );
2860 break;
2861 case 'numberofactiveusers':
2862 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2863 break;
2864 case 'numberofpages':
2865 $value = $pageLang->formatNum( SiteStats::pages() );
2866 break;
2867 case 'numberofadmins':
2868 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2869 break;
2870 case 'numberofedits':
2871 $value = $pageLang->formatNum( SiteStats::edits() );
2872 break;
2873 case 'currenttimestamp':
2874 $value = wfTimestamp( TS_MW, $ts );
2875 break;
2876 case 'localtimestamp':
2877 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
2878 break;
2879 case 'currentversion':
2880 $value = SpecialVersion::getVersion();
2881 break;
2882 case 'articlepath':
2883 return $this->siteConfig->get( 'ArticlePath' );
2884 case 'sitename':
2885 return $this->siteConfig->get( 'Sitename' );
2886 case 'server':
2887 return $this->siteConfig->get( 'Server' );
2888 case 'servername':
2889 return $this->siteConfig->get( 'ServerName' );
2890 case 'scriptpath':
2891 return $this->siteConfig->get( 'ScriptPath' );
2892 case 'stylepath':
2893 return $this->siteConfig->get( 'StylePath' );
2894 case 'directionmark':
2895 return $pageLang->getDirMark();
2896 case 'contentlanguage':
2897 return $this->siteConfig->get( 'LanguageCode' );
2898 case 'pagelanguage':
2899 $value = $pageLang->getCode();
2900 break;
2901 case 'cascadingsources':
2902 $value = CoreParserFunctions::cascadingsources( $this );
2903 break;
2904 default:
2905 $ret = null;
2906 Hooks::run(
2907 'ParserGetVariableValueSwitch',
2908 [ &$parser, &$this->mVarCache, &$index, &$ret, &$frame ]
2909 );
2910
2911 return $ret;
2912 }
2913
2914 if ( $index ) {
2915 $this->mVarCache[$index] = $value;
2916 }
2917
2918 return $value;
2919 }
2920
2921 /**
2922 * @param int $start
2923 * @param int $len
2924 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2925 * @param string $variable Parser variable name
2926 * @return string
2927 */
2928 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2929 # Get the timezone-adjusted timestamp to be used for this revision
2930 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2931 # Possibly set vary-revision if there is not yet an associated revision
2932 if ( !$this->getRevisionObject() ) {
2933 # Get the timezone-adjusted timestamp $mtts seconds in the future
2934 $resThen = substr(
2935 $this->contLang->userAdjust( wfTimestamp( TS_MW, time() + $mtts ), '' ),
2936 $start,
2937 $len
2938 );
2939
2940 if ( $resNow !== $resThen ) {
2941 # Let the edit saving system know we should parse the page
2942 # *after* a revision ID has been assigned. This is for null edits.
2943 $this->mOutput->setFlag( 'vary-revision' );
2944 wfDebug( __METHOD__ . ": $variable used, setting vary-revision...\n" );
2945 }
2946 }
2947
2948 return $resNow;
2949 }
2950
2951 /**
2952 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2953 *
2954 * @private
2955 */
2956 public function initialiseVariables() {
2957 $variableIDs = $this->magicWordFactory->getVariableIDs();
2958 $substIDs = $this->magicWordFactory->getSubstIDs();
2959
2960 $this->mVariables = $this->magicWordFactory->newArray( $variableIDs );
2961 $this->mSubstWords = $this->magicWordFactory->newArray( $substIDs );
2962 }
2963
2964 /**
2965 * Preprocess some wikitext and return the document tree.
2966 * This is the ghost of replace_variables().
2967 *
2968 * @param string $text The text to parse
2969 * @param int $flags Bitwise combination of:
2970 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2971 * included. Default is to assume a direct page view.
2972 *
2973 * The generated DOM tree must depend only on the input text and the flags.
2974 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2975 *
2976 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2977 * change in the DOM tree for a given text, must be passed through the section identifier
2978 * in the section edit link and thus back to extractSections().
2979 *
2980 * The output of this function is currently only cached in process memory, but a persistent
2981 * cache may be implemented at a later date which takes further advantage of these strict
2982 * dependency requirements.
2983 *
2984 * @return PPNode
2985 */
2986 public function preprocessToDom( $text, $flags = 0 ) {
2987 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2988 return $dom;
2989 }
2990
2991 /**
2992 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2993 *
2994 * @param string $s
2995 *
2996 * @return array
2997 */
2998 public static function splitWhitespace( $s ) {
2999 $ltrimmed = ltrim( $s );
3000 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3001 $trimmed = rtrim( $ltrimmed );
3002 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3003 if ( $diff > 0 ) {
3004 $w2 = substr( $ltrimmed, -$diff );
3005 } else {
3006 $w2 = '';
3007 }
3008 return [ $w1, $trimmed, $w2 ];
3009 }
3010
3011 /**
3012 * Replace magic variables, templates, and template arguments
3013 * with the appropriate text. Templates are substituted recursively,
3014 * taking care to avoid infinite loops.
3015 *
3016 * Note that the substitution depends on value of $mOutputType:
3017 * self::OT_WIKI: only {{subst:}} templates
3018 * self::OT_PREPROCESS: templates but not extension tags
3019 * self::OT_HTML: all templates and extension tags
3020 *
3021 * @param string $text The text to transform
3022 * @param bool|PPFrame $frame Object describing the arguments passed to the
3023 * template. Arguments may also be provided as an associative array, as
3024 * was the usual case before MW1.12. Providing arguments this way may be
3025 * useful for extensions wishing to perform variable replacement
3026 * explicitly.
3027 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3028 * double-brace expansion.
3029 * @return string
3030 */
3031 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3032 # Is there any text? Also, Prevent too big inclusions!
3033 $textSize = strlen( $text );
3034 if ( $textSize < 1 || $textSize > $this->mOptions->getMaxIncludeSize() ) {
3035 return $text;
3036 }
3037
3038 if ( $frame === false ) {
3039 $frame = $this->getPreprocessor()->newFrame();
3040 } elseif ( !( $frame instanceof PPFrame ) ) {
3041 wfDebug( __METHOD__ . " called using plain parameters instead of "
3042 . "a PPFrame instance. Creating custom frame.\n" );
3043 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3044 }
3045
3046 $dom = $this->preprocessToDom( $text );
3047 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3048 $text = $frame->expand( $dom, $flags );
3049
3050 return $text;
3051 }
3052
3053 /**
3054 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3055 *
3056 * @param array $args
3057 *
3058 * @return array
3059 */
3060 public static function createAssocArgs( $args ) {
3061 $assocArgs = [];
3062 $index = 1;
3063 foreach ( $args as $arg ) {
3064 $eqpos = strpos( $arg, '=' );
3065 if ( $eqpos === false ) {
3066 $assocArgs[$index++] = $arg;
3067 } else {
3068 $name = trim( substr( $arg, 0, $eqpos ) );
3069 $value = trim( substr( $arg, $eqpos + 1 ) );
3070 if ( $value === false ) {
3071 $value = '';
3072 }
3073 if ( $name !== false ) {
3074 $assocArgs[$name] = $value;
3075 }
3076 }
3077 }
3078
3079 return $assocArgs;
3080 }
3081
3082 /**
3083 * Warn the user when a parser limitation is reached
3084 * Will warn at most once the user per limitation type
3085 *
3086 * The results are shown during preview and run through the Parser (See EditPage.php)
3087 *
3088 * @param string $limitationType Should be one of:
3089 * 'expensive-parserfunction' (corresponding messages:
3090 * 'expensive-parserfunction-warning',
3091 * 'expensive-parserfunction-category')
3092 * 'post-expand-template-argument' (corresponding messages:
3093 * 'post-expand-template-argument-warning',
3094 * 'post-expand-template-argument-category')
3095 * 'post-expand-template-inclusion' (corresponding messages:
3096 * 'post-expand-template-inclusion-warning',
3097 * 'post-expand-template-inclusion-category')
3098 * 'node-count-exceeded' (corresponding messages:
3099 * 'node-count-exceeded-warning',
3100 * 'node-count-exceeded-category')
3101 * 'expansion-depth-exceeded' (corresponding messages:
3102 * 'expansion-depth-exceeded-warning',
3103 * 'expansion-depth-exceeded-category')
3104 * @param string|int|null $current Current value
3105 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3106 * exceeded, provide the values (optional)
3107 */
3108 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3109 # does no harm if $current and $max are present but are unnecessary for the message
3110 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3111 # only during preview, and that would split the parser cache unnecessarily.
3112 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3113 ->text();
3114 $this->mOutput->addWarning( $warning );
3115 $this->addTrackingCategory( "$limitationType-category" );
3116 }
3117
3118 /**
3119 * Return the text of a template, after recursively
3120 * replacing any variables or templates within the template.
3121 *
3122 * @param array $piece The parts of the template
3123 * $piece['title']: the title, i.e. the part before the |
3124 * $piece['parts']: the parameter array
3125 * $piece['lineStart']: whether the brace was at the start of a line
3126 * @param PPFrame $frame The current frame, contains template arguments
3127 * @throws Exception
3128 * @return string The text of the template
3129 */
3130 public function braceSubstitution( $piece, $frame ) {
3131 // Flags
3132
3133 // $text has been filled
3134 $found = false;
3135 // wiki markup in $text should be escaped
3136 $nowiki = false;
3137 // $text is HTML, armour it against wikitext transformation
3138 $isHTML = false;
3139 // Force interwiki transclusion to be done in raw mode not rendered
3140 $forceRawInterwiki = false;
3141 // $text is a DOM node needing expansion in a child frame
3142 $isChildObj = false;
3143 // $text is a DOM node needing expansion in the current frame
3144 $isLocalObj = false;
3145
3146 # Title object, where $text came from
3147 $title = false;
3148
3149 # $part1 is the bit before the first |, and must contain only title characters.
3150 # Various prefixes will be stripped from it later.
3151 $titleWithSpaces = $frame->expand( $piece['title'] );
3152 $part1 = trim( $titleWithSpaces );
3153 $titleText = false;
3154
3155 # Original title text preserved for various purposes
3156 $originalTitle = $part1;
3157
3158 # $args is a list of argument nodes, starting from index 0, not including $part1
3159 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3160 # below won't work b/c this $args isn't an object
3161 $args = ( $piece['parts'] == null ) ? [] : $piece['parts'];
3162
3163 $profileSection = null; // profile templates
3164
3165 # SUBST
3166 if ( !$found ) {
3167 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3168
3169 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3170 # Decide whether to expand template or keep wikitext as-is.
3171 if ( $this->ot['wiki'] ) {
3172 if ( $substMatch === false ) {
3173 $literal = true; # literal when in PST with no prefix
3174 } else {
3175 $literal = false; # expand when in PST with subst: or safesubst:
3176 }
3177 } else {
3178 if ( $substMatch == 'subst' ) {
3179 $literal = true; # literal when not in PST with plain subst:
3180 } else {
3181 $literal = false; # expand when not in PST with safesubst: or no prefix
3182 }
3183 }
3184 if ( $literal ) {
3185 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3186 $isLocalObj = true;
3187 $found = true;
3188 }
3189 }
3190
3191 # Variables
3192 if ( !$found && $args->getLength() == 0 ) {
3193 $id = $this->mVariables->matchStartToEnd( $part1 );
3194 if ( $id !== false ) {
3195 $text = $this->getVariableValue( $id, $frame );
3196 if ( $this->magicWordFactory->getCacheTTL( $id ) > -1 ) {
3197 $this->mOutput->updateCacheExpiry(
3198 $this->magicWordFactory->getCacheTTL( $id ) );
3199 }
3200 $found = true;
3201 }
3202 }
3203
3204 # MSG, MSGNW and RAW
3205 if ( !$found ) {
3206 # Check for MSGNW:
3207 $mwMsgnw = $this->magicWordFactory->get( 'msgnw' );
3208 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3209 $nowiki = true;
3210 } else {
3211 # Remove obsolete MSG:
3212 $mwMsg = $this->magicWordFactory->get( 'msg' );
3213 $mwMsg->matchStartAndRemove( $part1 );
3214 }
3215
3216 # Check for RAW:
3217 $mwRaw = $this->magicWordFactory->get( 'raw' );
3218 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3219 $forceRawInterwiki = true;
3220 }
3221 }
3222
3223 # Parser functions
3224 if ( !$found ) {
3225 $colonPos = strpos( $part1, ':' );
3226 if ( $colonPos !== false ) {
3227 $func = substr( $part1, 0, $colonPos );
3228 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3229 $argsLength = $args->getLength();
3230 for ( $i = 0; $i < $argsLength; $i++ ) {
3231 $funcArgs[] = $args->item( $i );
3232 }
3233
3234 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3235
3236 // Extract any forwarded flags
3237 if ( isset( $result['title'] ) ) {
3238 $title = $result['title'];
3239 }
3240 if ( isset( $result['found'] ) ) {
3241 $found = $result['found'];
3242 }
3243 if ( array_key_exists( 'text', $result ) ) {
3244 // a string or null
3245 $text = $result['text'];
3246 }
3247 if ( isset( $result['nowiki'] ) ) {
3248 $nowiki = $result['nowiki'];
3249 }
3250 if ( isset( $result['isHTML'] ) ) {
3251 $isHTML = $result['isHTML'];
3252 }
3253 if ( isset( $result['forceRawInterwiki'] ) ) {
3254 $forceRawInterwiki = $result['forceRawInterwiki'];
3255 }
3256 if ( isset( $result['isChildObj'] ) ) {
3257 $isChildObj = $result['isChildObj'];
3258 }
3259 if ( isset( $result['isLocalObj'] ) ) {
3260 $isLocalObj = $result['isLocalObj'];
3261 }
3262 }
3263 }
3264
3265 # Finish mangling title and then check for loops.
3266 # Set $title to a Title object and $titleText to the PDBK
3267 if ( !$found ) {
3268 $ns = NS_TEMPLATE;
3269 # Split the title into page and subpage
3270 $subpage = '';
3271 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3272 if ( $part1 !== $relative ) {
3273 $part1 = $relative;
3274 $ns = $this->mTitle->getNamespace();
3275 }
3276 $title = Title::newFromText( $part1, $ns );
3277 if ( $title ) {
3278 $titleText = $title->getPrefixedText();
3279 # Check for language variants if the template is not found
3280 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3281 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3282 }
3283 # Do recursion depth check
3284 $limit = $this->mOptions->getMaxTemplateDepth();
3285 if ( $frame->depth >= $limit ) {
3286 $found = true;
3287 $text = '<span class="error">'
3288 . wfMessage( 'parser-template-recursion-depth-warning' )
3289 ->numParams( $limit )->inContentLanguage()->text()
3290 . '</span>';
3291 }
3292 }
3293 }
3294
3295 # Load from database
3296 if ( !$found && $title ) {
3297 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3298 if ( !$title->isExternal() ) {
3299 if ( $title->isSpecialPage()
3300 && $this->mOptions->getAllowSpecialInclusion()
3301 && $this->ot['html']
3302 ) {
3303 $specialPage = $this->specialPageFactory->getPage( $title->getDBkey() );
3304 // Pass the template arguments as URL parameters.
3305 // "uselang" will have no effect since the Language object
3306 // is forced to the one defined in ParserOptions.
3307 $pageArgs = [];
3308 $argsLength = $args->getLength();
3309 for ( $i = 0; $i < $argsLength; $i++ ) {
3310 $bits = $args->item( $i )->splitArg();
3311 if ( strval( $bits['index'] ) === '' ) {
3312 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3313 $value = trim( $frame->expand( $bits['value'] ) );
3314 $pageArgs[$name] = $value;
3315 }
3316 }
3317
3318 // Create a new context to execute the special page
3319 $context = new RequestContext;
3320 $context->setTitle( $title );
3321 $context->setRequest( new FauxRequest( $pageArgs ) );
3322 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3323 $context->setUser( $this->getUser() );
3324 } else {
3325 // If this page is cached, then we better not be per user.
3326 $context->setUser( User::newFromName( '127.0.0.1', false ) );
3327 }
3328 $context->setLanguage( $this->mOptions->getUserLangObj() );
3329 $ret = $this->specialPageFactory->capturePath( $title, $context, $this->getLinkRenderer() );
3330 if ( $ret ) {
3331 $text = $context->getOutput()->getHTML();
3332 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3333 $found = true;
3334 $isHTML = true;
3335 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3336 $this->mOutput->updateRuntimeAdaptiveExpiry(
3337 $specialPage->maxIncludeCacheTime()
3338 );
3339 }
3340 }
3341 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3342 $found = false; # access denied
3343 wfDebug( __METHOD__ . ": template inclusion denied for " .
3344 $title->getPrefixedDBkey() . "\n" );
3345 } else {
3346 list( $text, $title ) = $this->getTemplateDom( $title );
3347 if ( $text !== false ) {
3348 $found = true;
3349 $isChildObj = true;
3350 }
3351 }
3352
3353 # If the title is valid but undisplayable, make a link to it
3354 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3355 $text = "[[:$titleText]]";
3356 $found = true;
3357 }
3358 } elseif ( $title->isTrans() ) {
3359 # Interwiki transclusion
3360 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3361 $text = $this->interwikiTransclude( $title, 'render' );
3362 $isHTML = true;
3363 } else {
3364 $text = $this->interwikiTransclude( $title, 'raw' );
3365 # Preprocess it like a template
3366 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3367 $isChildObj = true;
3368 }
3369 $found = true;
3370 }
3371
3372 # Do infinite loop check
3373 # This has to be done after redirect resolution to avoid infinite loops via redirects
3374 if ( !$frame->loopCheck( $title ) ) {
3375 $found = true;
3376 $text = '<span class="error">'
3377 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3378 . '</span>';
3379 $this->addTrackingCategory( 'template-loop-category' );
3380 $this->mOutput->addWarning( wfMessage( 'template-loop-warning',
3381 wfEscapeWikiText( $titleText ) )->text() );
3382 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3383 }
3384 }
3385
3386 # If we haven't found text to substitute by now, we're done
3387 # Recover the source wikitext and return it
3388 if ( !$found ) {
3389 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3390 if ( $profileSection ) {
3391 $this->mProfiler->scopedProfileOut( $profileSection );
3392 }
3393 return [ 'object' => $text ];
3394 }
3395
3396 # Expand DOM-style return values in a child frame
3397 if ( $isChildObj ) {
3398 # Clean up argument array
3399 $newFrame = $frame->newChild( $args, $title );
3400
3401 if ( $nowiki ) {
3402 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3403 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3404 # Expansion is eligible for the empty-frame cache
3405 $text = $newFrame->cachedExpand( $titleText, $text );
3406 } else {
3407 # Uncached expansion
3408 $text = $newFrame->expand( $text );
3409 }
3410 }
3411 if ( $isLocalObj && $nowiki ) {
3412 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3413 $isLocalObj = false;
3414 }
3415
3416 if ( $profileSection ) {
3417 $this->mProfiler->scopedProfileOut( $profileSection );
3418 }
3419
3420 # Replace raw HTML by a placeholder
3421 if ( $isHTML ) {
3422 $text = $this->insertStripItem( $text );
3423 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3424 # Escape nowiki-style return values
3425 $text = wfEscapeWikiText( $text );
3426 } elseif ( is_string( $text )
3427 && !$piece['lineStart']
3428 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3429 ) {
3430 # T2529: if the template begins with a table or block-level
3431 # element, it should be treated as beginning a new line.
3432 # This behavior is somewhat controversial.
3433 $text = "\n" . $text;
3434 }
3435
3436 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3437 # Error, oversize inclusion
3438 if ( $titleText !== false ) {
3439 # Make a working, properly escaped link if possible (T25588)
3440 $text = "[[:$titleText]]";
3441 } else {
3442 # This will probably not be a working link, but at least it may
3443 # provide some hint of where the problem is
3444 preg_replace( '/^:/', '', $originalTitle );
3445 $text = "[[:$originalTitle]]";
3446 }
3447 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3448 . 'post-expand include size too large -->' );
3449 $this->limitationWarn( 'post-expand-template-inclusion' );
3450 }
3451
3452 if ( $isLocalObj ) {
3453 $ret = [ 'object' => $text ];
3454 } else {
3455 $ret = [ 'text' => $text ];
3456 }
3457
3458 return $ret;
3459 }
3460
3461 /**
3462 * Call a parser function and return an array with text and flags.
3463 *
3464 * The returned array will always contain a boolean 'found', indicating
3465 * whether the parser function was found or not. It may also contain the
3466 * following:
3467 * text: string|object, resulting wikitext or PP DOM object
3468 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3469 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3470 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3471 * nowiki: bool, wiki markup in $text should be escaped
3472 *
3473 * @since 1.21
3474 * @param PPFrame $frame The current frame, contains template arguments
3475 * @param string $function Function name
3476 * @param array $args Arguments to the function
3477 * @throws MWException
3478 * @return array
3479 */
3480 public function callParserFunction( $frame, $function, array $args = [] ) {
3481 # Case sensitive functions
3482 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3483 $function = $this->mFunctionSynonyms[1][$function];
3484 } else {
3485 # Case insensitive functions
3486 $function = $this->contLang->lc( $function );
3487 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3488 $function = $this->mFunctionSynonyms[0][$function];
3489 } else {
3490 return [ 'found' => false ];
3491 }
3492 }
3493
3494 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3495
3496 // Avoid PHP 7.1 warning from passing $this by reference
3497 $parser = $this;
3498
3499 $allArgs = [ &$parser ];
3500 if ( $flags & self::SFH_OBJECT_ARGS ) {
3501 # Convert arguments to PPNodes and collect for appending to $allArgs
3502 $funcArgs = [];
3503 foreach ( $args as $k => $v ) {
3504 if ( $v instanceof PPNode || $k === 0 ) {
3505 $funcArgs[] = $v;
3506 } else {
3507 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( [ $k => $v ] )->item( 0 );
3508 }
3509 }
3510
3511 # Add a frame parameter, and pass the arguments as an array
3512 $allArgs[] = $frame;
3513 $allArgs[] = $funcArgs;
3514 } else {
3515 # Convert arguments to plain text and append to $allArgs
3516 foreach ( $args as $k => $v ) {
3517 if ( $v instanceof PPNode ) {
3518 $allArgs[] = trim( $frame->expand( $v ) );
3519 } elseif ( is_int( $k ) && $k >= 0 ) {
3520 $allArgs[] = trim( $v );
3521 } else {
3522 $allArgs[] = trim( "$k=$v" );
3523 }
3524 }
3525 }
3526
3527 $result = $callback( ...$allArgs );
3528
3529 # The interface for function hooks allows them to return a wikitext
3530 # string or an array containing the string and any flags. This mungs
3531 # things around to match what this method should return.
3532 if ( !is_array( $result ) ) {
3533 $result = [
3534 'found' => true,
3535 'text' => $result,
3536 ];
3537 } else {
3538 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3539 $result['text'] = $result[0];
3540 }
3541 unset( $result[0] );
3542 $result += [
3543 'found' => true,
3544 ];
3545 }
3546
3547 $noparse = true;
3548 $preprocessFlags = 0;
3549 if ( isset( $result['noparse'] ) ) {
3550 $noparse = $result['noparse'];
3551 }
3552 if ( isset( $result['preprocessFlags'] ) ) {
3553 $preprocessFlags = $result['preprocessFlags'];
3554 }
3555
3556 if ( !$noparse ) {
3557 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3558 $result['isChildObj'] = true;
3559 }
3560
3561 return $result;
3562 }
3563
3564 /**
3565 * Get the semi-parsed DOM representation of a template with a given title,
3566 * and its redirect destination title. Cached.
3567 *
3568 * @param Title $title
3569 *
3570 * @return array
3571 */
3572 public function getTemplateDom( $title ) {
3573 $cacheTitle = $title;
3574 $titleText = $title->getPrefixedDBkey();
3575
3576 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3577 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3578 $title = Title::makeTitle( $ns, $dbk );
3579 $titleText = $title->getPrefixedDBkey();
3580 }
3581 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3582 return [ $this->mTplDomCache[$titleText], $title ];
3583 }
3584
3585 # Cache miss, go to the database
3586 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3587
3588 if ( $text === false ) {
3589 $this->mTplDomCache[$titleText] = false;
3590 return [ false, $title ];
3591 }
3592
3593 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3594 $this->mTplDomCache[$titleText] = $dom;
3595
3596 if ( !$title->equals( $cacheTitle ) ) {
3597 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3598 [ $title->getNamespace(), $title->getDBkey() ];
3599 }
3600
3601 return [ $dom, $title ];
3602 }
3603
3604 /**
3605 * Fetch the current revision of a given title. Note that the revision
3606 * (and even the title) may not exist in the database, so everything
3607 * contributing to the output of the parser should use this method
3608 * where possible, rather than getting the revisions themselves. This
3609 * method also caches its results, so using it benefits performance.
3610 *
3611 * @since 1.24
3612 * @param Title $title
3613 * @return Revision
3614 */
3615 public function fetchCurrentRevisionOfTitle( $title ) {
3616 $cacheKey = $title->getPrefixedDBkey();
3617 if ( !$this->currentRevisionCache ) {
3618 $this->currentRevisionCache = new MapCacheLRU( 100 );
3619 }
3620 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3621 $this->currentRevisionCache->set( $cacheKey,
3622 // Defaults to Parser::statelessFetchRevision()
3623 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3624 );
3625 }
3626 return $this->currentRevisionCache->get( $cacheKey );
3627 }
3628
3629 /**
3630 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3631 * without passing them on to it.
3632 *
3633 * @since 1.24
3634 * @param Title $title
3635 * @param Parser|bool $parser
3636 * @return Revision|bool False if missing
3637 */
3638 public static function statelessFetchRevision( Title $title, $parser = false ) {
3639 $rev = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
3640
3641 return $rev;
3642 }
3643
3644 /**
3645 * Fetch the unparsed text of a template and register a reference to it.
3646 * @param Title $title
3647 * @return array ( string or false, Title )
3648 */
3649 public function fetchTemplateAndTitle( $title ) {
3650 // Defaults to Parser::statelessFetchTemplate()
3651 $templateCb = $this->mOptions->getTemplateCallback();
3652 $stuff = call_user_func( $templateCb, $title, $this );
3653 // We use U+007F DELETE to distinguish strip markers from regular text.
3654 $text = $stuff['text'];
3655 if ( is_string( $stuff['text'] ) ) {
3656 $text = strtr( $text, "\x7f", "?" );
3657 }
3658 $finalTitle = $stuff['finalTitle'] ?? $title;
3659 if ( isset( $stuff['deps'] ) ) {
3660 foreach ( $stuff['deps'] as $dep ) {
3661 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3662 if ( $dep['title']->equals( $this->getTitle() ) ) {
3663 // If we transclude ourselves, the final result
3664 // will change based on the new version of the page
3665 $this->mOutput->setFlag( 'vary-revision' );
3666 }
3667 }
3668 }
3669 return [ $text, $finalTitle ];
3670 }
3671
3672 /**
3673 * Fetch the unparsed text of a template and register a reference to it.
3674 * @param Title $title
3675 * @return string|bool
3676 */
3677 public function fetchTemplate( $title ) {
3678 return $this->fetchTemplateAndTitle( $title )[0];
3679 }
3680
3681 /**
3682 * Static function to get a template
3683 * Can be overridden via ParserOptions::setTemplateCallback().
3684 *
3685 * @param Title $title
3686 * @param bool|Parser $parser
3687 *
3688 * @return array
3689 */
3690 public static function statelessFetchTemplate( $title, $parser = false ) {
3691 $text = $skip = false;
3692 $finalTitle = $title;
3693 $deps = [];
3694
3695 # Loop to fetch the article, with up to 1 redirect
3696 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3697 # Give extensions a chance to select the revision instead
3698 $id = false; # Assume current
3699 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3700 [ $parser, $title, &$skip, &$id ] );
3701
3702 if ( $skip ) {
3703 $text = false;
3704 $deps[] = [
3705 'title' => $title,
3706 'page_id' => $title->getArticleID(),
3707 'rev_id' => null
3708 ];
3709 break;
3710 }
3711 # Get the revision
3712 if ( $id ) {
3713 $rev = Revision::newFromId( $id );
3714 } elseif ( $parser ) {
3715 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3716 } else {
3717 $rev = Revision::newFromTitle( $title );
3718 }
3719 $rev_id = $rev ? $rev->getId() : 0;
3720 # If there is no current revision, there is no page
3721 if ( $id === false && !$rev ) {
3722 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3723 $linkCache->addBadLinkObj( $title );
3724 }
3725
3726 $deps[] = [
3727 'title' => $title,
3728 'page_id' => $title->getArticleID(),
3729 'rev_id' => $rev_id ];
3730 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3731 # We fetched a rev from a different title; register it too...
3732 $deps[] = [
3733 'title' => $rev->getTitle(),
3734 'page_id' => $rev->getPage(),
3735 'rev_id' => $rev_id ];
3736 }
3737
3738 if ( $rev ) {
3739 $content = $rev->getContent();
3740 $text = $content ? $content->getWikitextForTransclusion() : null;
3741
3742 Hooks::run( 'ParserFetchTemplate',
3743 [ $parser, $title, $rev, &$text, &$deps ] );
3744
3745 if ( $text === false || $text === null ) {
3746 $text = false;
3747 break;
3748 }
3749 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3750 $message = wfMessage( MediaWikiServices::getInstance()->getContentLanguage()->
3751 lcfirst( $title->getText() ) )->inContentLanguage();
3752 if ( !$message->exists() ) {
3753 $text = false;
3754 break;
3755 }
3756 $content = $message->content();
3757 $text = $message->plain();
3758 } else {
3759 break;
3760 }
3761 if ( !$content ) {
3762 break;
3763 }
3764 # Redirect?
3765 $finalTitle = $title;
3766 $title = $content->getRedirectTarget();
3767 }
3768 return [
3769 'text' => $text,
3770 'finalTitle' => $finalTitle,
3771 'deps' => $deps ];
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 File|bool
3780 * @deprecated since 1.32, use fetchFileAndTitle instead
3781 */
3782 public function fetchFile( $title, $options = [] ) {
3783 wfDeprecated( __METHOD__, '1.32' );
3784 return $this->fetchFileAndTitle( $title, $options )[0];
3785 }
3786
3787 /**
3788 * Fetch a file and its title and register a reference to it.
3789 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3790 * @param Title $title
3791 * @param array $options Array of options to RepoGroup::findFile
3792 * @return array ( File or false, Title of file )
3793 */
3794 public function fetchFileAndTitle( $title, $options = [] ) {
3795 $file = $this->fetchFileNoRegister( $title, $options );
3796
3797 $time = $file ? $file->getTimestamp() : false;
3798 $sha1 = $file ? $file->getSha1() : false;
3799 # Register the file as a dependency...
3800 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3801 if ( $file && !$title->equals( $file->getTitle() ) ) {
3802 # Update fetched file title
3803 $title = $file->getTitle();
3804 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3805 }
3806 return [ $file, $title ];
3807 }
3808
3809 /**
3810 * Helper function for fetchFileAndTitle.
3811 *
3812 * Also useful if you need to fetch a file but not use it yet,
3813 * for example to get the file's handler.
3814 *
3815 * @param Title $title
3816 * @param array $options Array of options to RepoGroup::findFile
3817 * @return File|bool
3818 */
3819 protected function fetchFileNoRegister( $title, $options = [] ) {
3820 if ( isset( $options['broken'] ) ) {
3821 $file = false; // broken thumbnail forced by hook
3822 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3823 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3824 } else { // get by (name,timestamp)
3825 $file = wfFindFile( $title, $options );
3826 }
3827 return $file;
3828 }
3829
3830 /**
3831 * Transclude an interwiki link.
3832 *
3833 * @param Title $title
3834 * @param string $action Usually one of (raw, render)
3835 *
3836 * @return string
3837 */
3838 public function interwikiTransclude( $title, $action ) {
3839 if ( !$this->siteConfig->get( 'EnableScaryTranscluding' ) ) {
3840 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3841 }
3842
3843 $url = $title->getFullURL( [ 'action' => $action ] );
3844 if ( strlen( $url ) > 1024 ) {
3845 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3846 }
3847
3848 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3849
3850 $fname = __METHOD__;
3851 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
3852
3853 $data = $cache->getWithSetCallback(
3854 $cache->makeGlobalKey(
3855 'interwiki-transclude',
3856 ( $wikiId !== false ) ? $wikiId : 'external',
3857 sha1( $url )
3858 ),
3859 $this->siteConfig->get( 'TranscludeCacheExpiry' ),
3860 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3861 $req = MWHttpRequest::factory( $url, [], $fname );
3862
3863 $status = $req->execute(); // Status object
3864 if ( !$status->isOK() ) {
3865 $ttl = $cache::TTL_UNCACHEABLE;
3866 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3867 $ttl = min( $cache::TTL_LAGGED, $ttl );
3868 }
3869
3870 return [
3871 'text' => $status->isOK() ? $req->getContent() : null,
3872 'code' => $req->getStatus()
3873 ];
3874 },
3875 [
3876 'checkKeys' => ( $wikiId !== false )
3877 ? [ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
3878 : [],
3879 'pcGroup' => 'interwiki-transclude:5',
3880 'pcTTL' => $cache::TTL_PROC_LONG
3881 ]
3882 );
3883
3884 if ( is_string( $data['text'] ) ) {
3885 $text = $data['text'];
3886 } elseif ( $data['code'] != 200 ) {
3887 // Though we failed to fetch the content, this status is useless.
3888 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
3889 ->params( $url, $data['code'] )->inContentLanguage()->text();
3890 } else {
3891 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3892 }
3893
3894 return $text;
3895 }
3896
3897 /**
3898 * Triple brace replacement -- used for template arguments
3899 * @private
3900 *
3901 * @param array $piece
3902 * @param PPFrame $frame
3903 *
3904 * @return array
3905 */
3906 public function argSubstitution( $piece, $frame ) {
3907 $error = false;
3908 $parts = $piece['parts'];
3909 $nameWithSpaces = $frame->expand( $piece['title'] );
3910 $argName = trim( $nameWithSpaces );
3911 $object = false;
3912 $text = $frame->getArgument( $argName );
3913 if ( $text === false && $parts->getLength() > 0
3914 && ( $this->ot['html']
3915 || $this->ot['pre']
3916 || ( $this->ot['wiki'] && $frame->isTemplate() )
3917 )
3918 ) {
3919 # No match in frame, use the supplied default
3920 $object = $parts->item( 0 )->getChildren();
3921 }
3922 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3923 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3924 $this->limitationWarn( 'post-expand-template-argument' );
3925 }
3926
3927 if ( $text === false && $object === false ) {
3928 # No match anywhere
3929 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3930 }
3931 if ( $error !== false ) {
3932 $text .= $error;
3933 }
3934 if ( $object !== false ) {
3935 $ret = [ 'object' => $object ];
3936 } else {
3937 $ret = [ 'text' => $text ];
3938 }
3939
3940 return $ret;
3941 }
3942
3943 /**
3944 * Return the text to be used for a given extension tag.
3945 * This is the ghost of strip().
3946 *
3947 * @param array $params Associative array of parameters:
3948 * name PPNode for the tag name
3949 * attr PPNode for unparsed text where tag attributes are thought to be
3950 * attributes Optional associative array of parsed attributes
3951 * inner Contents of extension element
3952 * noClose Original text did not have a close tag
3953 * @param PPFrame $frame
3954 *
3955 * @throws MWException
3956 * @return string
3957 */
3958 public function extensionSubstitution( $params, $frame ) {
3959 static $errorStr = '<span class="error">';
3960 static $errorLen = 20;
3961
3962 $name = $frame->expand( $params['name'] );
3963 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3964 // Probably expansion depth or node count exceeded. Just punt the
3965 // error up.
3966 return $name;
3967 }
3968
3969 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3970 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3971 // See above
3972 return $attrText;
3973 }
3974
3975 // We can't safely check if the expansion for $content resulted in an
3976 // error, because the content could happen to be the error string
3977 // (T149622).
3978 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3979
3980 $marker = self::MARKER_PREFIX . "-$name-"
3981 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3982
3983 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3984 ( $this->ot['html'] || $this->ot['pre'] );
3985 if ( $isFunctionTag ) {
3986 $markerType = 'none';
3987 } else {
3988 $markerType = 'general';
3989 }
3990 if ( $this->ot['html'] || $isFunctionTag ) {
3991 $name = strtolower( $name );
3992 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3993 if ( isset( $params['attributes'] ) ) {
3994 $attributes = $attributes + $params['attributes'];
3995 }
3996
3997 if ( isset( $this->mTagHooks[$name] ) ) {
3998 $output = call_user_func_array( $this->mTagHooks[$name],
3999 [ $content, $attributes, $this, $frame ] );
4000 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
4001 list( $callback, ) = $this->mFunctionTagHooks[$name];
4002
4003 // Avoid PHP 7.1 warning from passing $this by reference
4004 $parser = $this;
4005 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
4006 } else {
4007 $output = '<span class="error">Invalid tag extension name: ' .
4008 htmlspecialchars( $name ) . '</span>';
4009 }
4010
4011 if ( is_array( $output ) ) {
4012 // Extract flags
4013 $flags = $output;
4014 $output = $flags[0];
4015 if ( isset( $flags['markerType'] ) ) {
4016 $markerType = $flags['markerType'];
4017 }
4018 }
4019 } else {
4020 if ( is_null( $attrText ) ) {
4021 $attrText = '';
4022 }
4023 if ( isset( $params['attributes'] ) ) {
4024 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4025 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4026 htmlspecialchars( $attrValue ) . '"';
4027 }
4028 }
4029 if ( $content === null ) {
4030 $output = "<$name$attrText/>";
4031 } else {
4032 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4033 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4034 // See above
4035 return $close;
4036 }
4037 $output = "<$name$attrText>$content$close";
4038 }
4039 }
4040
4041 if ( $markerType === 'none' ) {
4042 return $output;
4043 } elseif ( $markerType === 'nowiki' ) {
4044 $this->mStripState->addNoWiki( $marker, $output );
4045 } elseif ( $markerType === 'general' ) {
4046 $this->mStripState->addGeneral( $marker, $output );
4047 } else {
4048 throw new MWException( __METHOD__ . ': invalid marker type' );
4049 }
4050 return $marker;
4051 }
4052
4053 /**
4054 * Increment an include size counter
4055 *
4056 * @param string $type The type of expansion
4057 * @param int $size The size of the text
4058 * @return bool False if this inclusion would take it over the maximum, true otherwise
4059 */
4060 public function incrementIncludeSize( $type, $size ) {
4061 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4062 return false;
4063 } else {
4064 $this->mIncludeSizes[$type] += $size;
4065 return true;
4066 }
4067 }
4068
4069 /**
4070 * Increment the expensive function count
4071 *
4072 * @return bool False if the limit has been exceeded
4073 */
4074 public function incrementExpensiveFunctionCount() {
4075 $this->mExpensiveFunctionCount++;
4076 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4077 }
4078
4079 /**
4080 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4081 * Fills $this->mDoubleUnderscores, returns the modified text
4082 *
4083 * @param string $text
4084 *
4085 * @return string
4086 */
4087 public function doDoubleUnderscore( $text ) {
4088 # The position of __TOC__ needs to be recorded
4089 $mw = $this->magicWordFactory->get( 'toc' );
4090 if ( $mw->match( $text ) ) {
4091 $this->mShowToc = true;
4092 $this->mForceTocPosition = true;
4093
4094 # Set a placeholder. At the end we'll fill it in with the TOC.
4095 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4096
4097 # Only keep the first one.
4098 $text = $mw->replace( '', $text );
4099 }
4100
4101 # Now match and remove the rest of them
4102 $mwa = $this->magicWordFactory->getDoubleUnderscoreArray();
4103 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4104
4105 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4106 $this->mOutput->mNoGallery = true;
4107 }
4108 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4109 $this->mShowToc = false;
4110 }
4111 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4112 && $this->mTitle->getNamespace() == NS_CATEGORY
4113 ) {
4114 $this->addTrackingCategory( 'hidden-category-category' );
4115 }
4116 # (T10068) Allow control over whether robots index a page.
4117 # __INDEX__ always overrides __NOINDEX__, see T16899
4118 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4119 $this->mOutput->setIndexPolicy( 'noindex' );
4120 $this->addTrackingCategory( 'noindex-category' );
4121 }
4122 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4123 $this->mOutput->setIndexPolicy( 'index' );
4124 $this->addTrackingCategory( 'index-category' );
4125 }
4126
4127 # Cache all double underscores in the database
4128 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4129 $this->mOutput->setProperty( $key, '' );
4130 }
4131
4132 return $text;
4133 }
4134
4135 /**
4136 * @see ParserOutput::addTrackingCategory()
4137 * @param string $msg Message key
4138 * @return bool Whether the addition was successful
4139 */
4140 public function addTrackingCategory( $msg ) {
4141 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4142 }
4143
4144 /**
4145 * This function accomplishes several tasks:
4146 * 1) Auto-number headings if that option is enabled
4147 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4148 * 3) Add a Table of contents on the top for users who have enabled the option
4149 * 4) Auto-anchor headings
4150 *
4151 * It loops through all headlines, collects the necessary data, then splits up the
4152 * string and re-inserts the newly formatted headlines.
4153 *
4154 * @param string $text
4155 * @param string $origText Original, untouched wikitext
4156 * @param bool $isMain
4157 * @return mixed|string
4158 * @private
4159 */
4160 public function formatHeadings( $text, $origText, $isMain = true ) {
4161 # Inhibit editsection links if requested in the page
4162 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4163 $maybeShowEditLink = false;
4164 } else {
4165 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4166 }
4167
4168 # Get all headlines for numbering them and adding funky stuff like [edit]
4169 # links - this is for later, but we need the number of headlines right now
4170 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4171 # be trimmed here since whitespace in HTML headings is significant.
4172 $matches = [];
4173 $numMatches = preg_match_all(
4174 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4175 $text,
4176 $matches
4177 );
4178
4179 # if there are fewer than 4 headlines in the article, do not show TOC
4180 # unless it's been explicitly enabled.
4181 $enoughToc = $this->mShowToc &&
4182 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4183
4184 # Allow user to stipulate that a page should have a "new section"
4185 # link added via __NEWSECTIONLINK__
4186 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4187 $this->mOutput->setNewSection( true );
4188 }
4189
4190 # Allow user to remove the "new section"
4191 # link via __NONEWSECTIONLINK__
4192 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4193 $this->mOutput->hideNewSection( true );
4194 }
4195
4196 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4197 # override above conditions and always show TOC above first header
4198 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4199 $this->mShowToc = true;
4200 $enoughToc = true;
4201 }
4202
4203 # headline counter
4204 $headlineCount = 0;
4205 $numVisible = 0;
4206
4207 # Ugh .. the TOC should have neat indentation levels which can be
4208 # passed to the skin functions. These are determined here
4209 $toc = '';
4210 $full = '';
4211 $head = [];
4212 $sublevelCount = [];
4213 $levelCount = [];
4214 $level = 0;
4215 $prevlevel = 0;
4216 $toclevel = 0;
4217 $prevtoclevel = 0;
4218 $markerRegex = self::MARKER_PREFIX . "-h-(\d+)-" . self::MARKER_SUFFIX;
4219 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4220 $oldType = $this->mOutputType;
4221 $this->setOutputType( self::OT_WIKI );
4222 $frame = $this->getPreprocessor()->newFrame();
4223 $root = $this->preprocessToDom( $origText );
4224 $node = $root->getFirstChild();
4225 $byteOffset = 0;
4226 $tocraw = [];
4227 $refers = [];
4228
4229 $headlines = $numMatches !== false ? $matches[3] : [];
4230
4231 $maxTocLevel = $this->siteConfig->get( 'MaxTocLevel' );
4232 foreach ( $headlines as $headline ) {
4233 $isTemplate = false;
4234 $titleText = false;
4235 $sectionIndex = false;
4236 $numbering = '';
4237 $markerMatches = [];
4238 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4239 $serial = $markerMatches[1];
4240 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4241 $isTemplate = ( $titleText != $baseTitleText );
4242 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4243 }
4244
4245 if ( $toclevel ) {
4246 $prevlevel = $level;
4247 }
4248 $level = $matches[1][$headlineCount];
4249
4250 if ( $level > $prevlevel ) {
4251 # Increase TOC level
4252 $toclevel++;
4253 $sublevelCount[$toclevel] = 0;
4254 if ( $toclevel < $maxTocLevel ) {
4255 $prevtoclevel = $toclevel;
4256 $toc .= Linker::tocIndent();
4257 $numVisible++;
4258 }
4259 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4260 # Decrease TOC level, find level to jump to
4261
4262 for ( $i = $toclevel; $i > 0; $i-- ) {
4263 if ( $levelCount[$i] == $level ) {
4264 # Found last matching level
4265 $toclevel = $i;
4266 break;
4267 } elseif ( $levelCount[$i] < $level ) {
4268 # Found first matching level below current level
4269 $toclevel = $i + 1;
4270 break;
4271 }
4272 }
4273 if ( $i == 0 ) {
4274 $toclevel = 1;
4275 }
4276 if ( $toclevel < $maxTocLevel ) {
4277 if ( $prevtoclevel < $maxTocLevel ) {
4278 # Unindent only if the previous toc level was shown :p
4279 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4280 $prevtoclevel = $toclevel;
4281 } else {
4282 $toc .= Linker::tocLineEnd();
4283 }
4284 }
4285 } else {
4286 # No change in level, end TOC line
4287 if ( $toclevel < $maxTocLevel ) {
4288 $toc .= Linker::tocLineEnd();
4289 }
4290 }
4291
4292 $levelCount[$toclevel] = $level;
4293
4294 # count number of headlines for each level
4295 $sublevelCount[$toclevel]++;
4296 $dot = 0;
4297 for ( $i = 1; $i <= $toclevel; $i++ ) {
4298 if ( !empty( $sublevelCount[$i] ) ) {
4299 if ( $dot ) {
4300 $numbering .= '.';
4301 }
4302 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4303 $dot = 1;
4304 }
4305 }
4306
4307 # The safe header is a version of the header text safe to use for links
4308
4309 # Remove link placeholders by the link text.
4310 # <!--LINK number-->
4311 # turns into
4312 # link text with suffix
4313 # Do this before unstrip since link text can contain strip markers
4314 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4315
4316 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4317 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4318
4319 # Remove any <style> or <script> tags (T198618)
4320 $safeHeadline = preg_replace(
4321 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4322 '',
4323 $safeHeadline
4324 );
4325
4326 # Strip out HTML (first regex removes any tag not allowed)
4327 # Allowed tags are:
4328 # * <sup> and <sub> (T10393)
4329 # * <i> (T28375)
4330 # * <b> (r105284)
4331 # * <bdi> (T74884)
4332 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4333 # * <s> and <strike> (T35715)
4334 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4335 # to allow setting directionality in toc items.
4336 $tocline = preg_replace(
4337 [
4338 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4339 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4340 ],
4341 [ '', '<$1>' ],
4342 $safeHeadline
4343 );
4344
4345 # Strip '<span></span>', which is the result from the above if
4346 # <span id="foo"></span> is used to produce an additional anchor
4347 # for a section.
4348 $tocline = str_replace( '<span></span>', '', $tocline );
4349
4350 $tocline = trim( $tocline );
4351
4352 # For the anchor, strip out HTML-y stuff period
4353 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4354 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4355
4356 # Save headline for section edit hint before it's escaped
4357 $headlineHint = $safeHeadline;
4358
4359 # Decode HTML entities
4360 $safeHeadline = Sanitizer::decodeCharReferences( $safeHeadline );
4361
4362 $safeHeadline = self::normalizeSectionName( $safeHeadline );
4363
4364 $fallbackHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_FALLBACK );
4365 $linkAnchor = Sanitizer::escapeIdForLink( $safeHeadline );
4366 $safeHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_PRIMARY );
4367 if ( $fallbackHeadline === $safeHeadline ) {
4368 # No reason to have both (in fact, we can't)
4369 $fallbackHeadline = false;
4370 }
4371
4372 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4373 # @todo FIXME: We may be changing them depending on the current locale.
4374 $arrayKey = strtolower( $safeHeadline );
4375 if ( $fallbackHeadline === false ) {
4376 $fallbackArrayKey = false;
4377 } else {
4378 $fallbackArrayKey = strtolower( $fallbackHeadline );
4379 }
4380
4381 # Create the anchor for linking from the TOC to the section
4382 $anchor = $safeHeadline;
4383 $fallbackAnchor = $fallbackHeadline;
4384 if ( isset( $refers[$arrayKey] ) ) {
4385 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4386 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++$i );
4387 $anchor .= "_$i";
4388 $linkAnchor .= "_$i";
4389 $refers["${arrayKey}_$i"] = true;
4390 } else {
4391 $refers[$arrayKey] = true;
4392 }
4393 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4394 // phpcs:ignore Generic.Formatting.DisallowMultipleStatements
4395 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++$i );
4396 $fallbackAnchor .= "_$i";
4397 $refers["${fallbackArrayKey}_$i"] = true;
4398 } else {
4399 $refers[$fallbackArrayKey] = true;
4400 }
4401
4402 # Don't number the heading if it is the only one (looks silly)
4403 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4404 # the two are different if the line contains a link
4405 $headline = Html::element(
4406 'span',
4407 [ 'class' => 'mw-headline-number' ],
4408 $numbering
4409 ) . ' ' . $headline;
4410 }
4411
4412 if ( $enoughToc && ( !isset( $maxTocLevel ) || $toclevel < $maxTocLevel ) ) {
4413 $toc .= Linker::tocLine( $linkAnchor, $tocline,
4414 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4415 }
4416
4417 # Add the section to the section tree
4418 # Find the DOM node for this header
4419 $noOffset = ( $isTemplate || $sectionIndex === false );
4420 while ( $node && !$noOffset ) {
4421 if ( $node->getName() === 'h' ) {
4422 $bits = $node->splitHeading();
4423 if ( $bits['i'] == $sectionIndex ) {
4424 break;
4425 }
4426 }
4427 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4428 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4429 $node = $node->getNextSibling();
4430 }
4431 $tocraw[] = [
4432 'toclevel' => $toclevel,
4433 'level' => $level,
4434 'line' => $tocline,
4435 'number' => $numbering,
4436 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4437 'fromtitle' => $titleText,
4438 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4439 'anchor' => $anchor,
4440 ];
4441
4442 # give headline the correct <h#> tag
4443 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4444 // Output edit section links as markers with styles that can be customized by skins
4445 if ( $isTemplate ) {
4446 # Put a T flag in the section identifier, to indicate to extractSections()
4447 # that sections inside <includeonly> should be counted.
4448 $editsectionPage = $titleText;
4449 $editsectionSection = "T-$sectionIndex";
4450 $editsectionContent = null;
4451 } else {
4452 $editsectionPage = $this->mTitle->getPrefixedText();
4453 $editsectionSection = $sectionIndex;
4454 $editsectionContent = $headlineHint;
4455 }
4456 // We use a bit of pesudo-xml for editsection markers. The
4457 // language converter is run later on. Using a UNIQ style marker
4458 // leads to the converter screwing up the tokens when it
4459 // converts stuff. And trying to insert strip tags fails too. At
4460 // this point all real inputted tags have already been escaped,
4461 // so we don't have to worry about a user trying to input one of
4462 // these markers directly. We use a page and section attribute
4463 // to stop the language converter from converting these
4464 // important bits of data, but put the headline hint inside a
4465 // content block because the language converter is supposed to
4466 // be able to convert that piece of data.
4467 // Gets replaced with html in ParserOutput::getText
4468 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4469 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4470 if ( $editsectionContent !== null ) {
4471 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4472 } else {
4473 $editlink .= '/>';
4474 }
4475 } else {
4476 $editlink = '';
4477 }
4478 $head[$headlineCount] = Linker::makeHeadline( $level,
4479 $matches['attrib'][$headlineCount], $anchor, $headline,
4480 $editlink, $fallbackAnchor );
4481
4482 $headlineCount++;
4483 }
4484
4485 $this->setOutputType( $oldType );
4486
4487 # Never ever show TOC if no headers
4488 if ( $numVisible < 1 ) {
4489 $enoughToc = false;
4490 }
4491
4492 if ( $enoughToc ) {
4493 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4494 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4495 }
4496 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4497 $this->mOutput->setTOCHTML( $toc );
4498 $toc = self::TOC_START . $toc . self::TOC_END;
4499 }
4500
4501 if ( $isMain ) {
4502 $this->mOutput->setSections( $tocraw );
4503 }
4504
4505 # split up and insert constructed headlines
4506 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4507 $i = 0;
4508
4509 // build an array of document sections
4510 $sections = [];
4511 foreach ( $blocks as $block ) {
4512 // $head is zero-based, sections aren't.
4513 if ( empty( $head[$i - 1] ) ) {
4514 $sections[$i] = $block;
4515 } else {
4516 $sections[$i] = $head[$i - 1] . $block;
4517 }
4518
4519 /**
4520 * Send a hook, one per section.
4521 * The idea here is to be able to make section-level DIVs, but to do so in a
4522 * lower-impact, more correct way than r50769
4523 *
4524 * $this : caller
4525 * $section : the section number
4526 * &$sectionContent : ref to the content of the section
4527 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4528 */
4529 Hooks::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4530
4531 $i++;
4532 }
4533
4534 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4535 // append the TOC at the beginning
4536 // Top anchor now in skin
4537 $sections[0] = $sections[0] . $toc . "\n";
4538 }
4539
4540 $full .= implode( '', $sections );
4541
4542 if ( $this->mForceTocPosition ) {
4543 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4544 } else {
4545 return $full;
4546 }
4547 }
4548
4549 /**
4550 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4551 * conversion, substituting signatures, {{subst:}} templates, etc.
4552 *
4553 * @param string $text The text to transform
4554 * @param Title $title The Title object for the current article
4555 * @param User $user The User object describing the current user
4556 * @param ParserOptions $options Parsing options
4557 * @param bool $clearState Whether to clear the parser state first
4558 * @return string The altered wiki markup
4559 */
4560 public function preSaveTransform( $text, Title $title, User $user,
4561 ParserOptions $options, $clearState = true
4562 ) {
4563 if ( $clearState ) {
4564 $magicScopeVariable = $this->lock();
4565 }
4566 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4567 $this->setUser( $user );
4568
4569 // Strip U+0000 NULL (T159174)
4570 $text = str_replace( "\000", '', $text );
4571
4572 // We still normalize line endings for backwards-compatibility
4573 // with other code that just calls PST, but this should already
4574 // be handled in TextContent subclasses
4575 $text = TextContent::normalizeLineEndings( $text );
4576
4577 if ( $options->getPreSaveTransform() ) {
4578 $text = $this->pstPass2( $text, $user );
4579 }
4580 $text = $this->mStripState->unstripBoth( $text );
4581
4582 $this->setUser( null ); # Reset
4583
4584 return $text;
4585 }
4586
4587 /**
4588 * Pre-save transform helper function
4589 *
4590 * @param string $text
4591 * @param User $user
4592 *
4593 * @return string
4594 */
4595 private function pstPass2( $text, $user ) {
4596 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4597 # $this->contLang here in order to give everyone the same signature and use the default one
4598 # rather than the one selected in each user's preferences. (see also T14815)
4599 $ts = $this->mOptions->getTimestamp();
4600 $timestamp = MWTimestamp::getLocalInstance( $ts );
4601 $ts = $timestamp->format( 'YmdHis' );
4602 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4603
4604 $d = $this->contLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4605
4606 # Variable replacement
4607 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4608 $text = $this->replaceVariables( $text );
4609
4610 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4611 # which may corrupt this parser instance via its wfMessage()->text() call-
4612
4613 # Signatures
4614 if ( strpos( $text, '~~~' ) !== false ) {
4615 $sigText = $this->getUserSig( $user );
4616 $text = strtr( $text, [
4617 '~~~~~' => $d,
4618 '~~~~' => "$sigText $d",
4619 '~~~' => $sigText
4620 ] );
4621 # The main two signature forms used above are time-sensitive
4622 $this->mOutput->setFlag( 'user-signature' );
4623 }
4624
4625 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4626 $tc = '[' . Title::legalChars() . ']';
4627 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4628
4629 // [[ns:page (context)|]]
4630 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4631 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4632 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4633 // [[ns:page (context), context|]] (using either single or double-width comma)
4634 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4635 // [[|page]] (reverse pipe trick: add context from page title)
4636 $p2 = "/\[\[\\|($tc+)]]/";
4637
4638 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4639 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4640 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4641 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4642
4643 $t = $this->mTitle->getText();
4644 $m = [];
4645 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4646 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4647 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4648 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4649 } else {
4650 # if there's no context, don't bother duplicating the title
4651 $text = preg_replace( $p2, '[[\\1]]', $text );
4652 }
4653
4654 return $text;
4655 }
4656
4657 /**
4658 * Fetch the user's signature text, if any, and normalize to
4659 * validated, ready-to-insert wikitext.
4660 * If you have pre-fetched the nickname or the fancySig option, you can
4661 * specify them here to save a database query.
4662 * Do not reuse this parser instance after calling getUserSig(),
4663 * as it may have changed if it's the $wgParser.
4664 *
4665 * @param User &$user
4666 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4667 * @param bool|null $fancySig whether the nicknname is the complete signature
4668 * or null to use default value
4669 * @return string
4670 */
4671 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4672 $username = $user->getName();
4673
4674 # If not given, retrieve from the user object.
4675 if ( $nickname === false ) {
4676 $nickname = $user->getOption( 'nickname' );
4677 }
4678
4679 if ( is_null( $fancySig ) ) {
4680 $fancySig = $user->getBoolOption( 'fancysig' );
4681 }
4682
4683 $nickname = $nickname == null ? $username : $nickname;
4684
4685 if ( mb_strlen( $nickname ) > $this->siteConfig->get( 'MaxSigChars' ) ) {
4686 $nickname = $username;
4687 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4688 } elseif ( $fancySig !== false ) {
4689 # Sig. might contain markup; validate this
4690 if ( $this->validateSig( $nickname ) !== false ) {
4691 # Validated; clean up (if needed) and return it
4692 return $this->cleanSig( $nickname, true );
4693 } else {
4694 # Failed to validate; fall back to the default
4695 $nickname = $username;
4696 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4697 }
4698 }
4699
4700 # Make sure nickname doesnt get a sig in a sig
4701 $nickname = self::cleanSigInSig( $nickname );
4702
4703 # If we're still here, make it a link to the user page
4704 $userText = wfEscapeWikiText( $username );
4705 $nickText = wfEscapeWikiText( $nickname );
4706 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4707
4708 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4709 ->title( $this->getTitle() )->text();
4710 }
4711
4712 /**
4713 * Check that the user's signature contains no bad XML
4714 *
4715 * @param string $text
4716 * @return string|bool An expanded string, or false if invalid.
4717 */
4718 public function validateSig( $text ) {
4719 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4720 }
4721
4722 /**
4723 * Clean up signature text
4724 *
4725 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4726 * 2) Substitute all transclusions
4727 *
4728 * @param string $text
4729 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4730 * @return string Signature text
4731 */
4732 public function cleanSig( $text, $parsing = false ) {
4733 if ( !$parsing ) {
4734 global $wgTitle;
4735 $magicScopeVariable = $this->lock();
4736 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4737 }
4738
4739 # Option to disable this feature
4740 if ( !$this->mOptions->getCleanSignatures() ) {
4741 return $text;
4742 }
4743
4744 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4745 # => Move this logic to braceSubstitution()
4746 $substWord = $this->magicWordFactory->get( 'subst' );
4747 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4748 $substText = '{{' . $substWord->getSynonym( 0 );
4749
4750 $text = preg_replace( $substRegex, $substText, $text );
4751 $text = self::cleanSigInSig( $text );
4752 $dom = $this->preprocessToDom( $text );
4753 $frame = $this->getPreprocessor()->newFrame();
4754 $text = $frame->expand( $dom );
4755
4756 if ( !$parsing ) {
4757 $text = $this->mStripState->unstripBoth( $text );
4758 }
4759
4760 return $text;
4761 }
4762
4763 /**
4764 * Strip 3, 4 or 5 tildes out of signatures.
4765 *
4766 * @param string $text
4767 * @return string Signature text with /~{3,5}/ removed
4768 */
4769 public static function cleanSigInSig( $text ) {
4770 $text = preg_replace( '/~{3,5}/', '', $text );
4771 return $text;
4772 }
4773
4774 /**
4775 * Set up some variables which are usually set up in parse()
4776 * so that an external function can call some class members with confidence
4777 *
4778 * @param Title|null $title
4779 * @param ParserOptions $options
4780 * @param int $outputType
4781 * @param bool $clearState
4782 */
4783 public function startExternalParse( Title $title = null, ParserOptions $options,
4784 $outputType, $clearState = true
4785 ) {
4786 $this->startParse( $title, $options, $outputType, $clearState );
4787 }
4788
4789 /**
4790 * @param Title|null $title
4791 * @param ParserOptions $options
4792 * @param int $outputType
4793 * @param bool $clearState
4794 */
4795 private function startParse( Title $title = null, ParserOptions $options,
4796 $outputType, $clearState = true
4797 ) {
4798 $this->setTitle( $title );
4799 $this->mOptions = $options;
4800 $this->setOutputType( $outputType );
4801 if ( $clearState ) {
4802 $this->clearState();
4803 }
4804 }
4805
4806 /**
4807 * Wrapper for preprocess()
4808 *
4809 * @param string $text The text to preprocess
4810 * @param ParserOptions $options
4811 * @param Title|null $title Title object or null to use $wgTitle
4812 * @return string
4813 */
4814 public function transformMsg( $text, $options, $title = null ) {
4815 static $executing = false;
4816
4817 # Guard against infinite recursion
4818 if ( $executing ) {
4819 return $text;
4820 }
4821 $executing = true;
4822
4823 if ( !$title ) {
4824 global $wgTitle;
4825 $title = $wgTitle;
4826 }
4827
4828 $text = $this->preprocess( $text, $title, $options );
4829
4830 $executing = false;
4831 return $text;
4832 }
4833
4834 /**
4835 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4836 * The callback should have the following form:
4837 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4838 *
4839 * Transform and return $text. Use $parser for any required context, e.g. use
4840 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4841 *
4842 * Hooks may return extended information by returning an array, of which the
4843 * first numbered element (index 0) must be the return string, and all other
4844 * entries are extracted into local variables within an internal function
4845 * in the Parser class.
4846 *
4847 * This interface (introduced r61913) appears to be undocumented, but
4848 * 'markerType' is used by some core tag hooks to override which strip
4849 * array their results are placed in. **Use great caution if attempting
4850 * this interface, as it is not documented and injudicious use could smash
4851 * private variables.**
4852 *
4853 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4854 * @param callable $callback The callback function (and object) to use for the tag
4855 * @throws MWException
4856 * @return callable|null The old value of the mTagHooks array associated with the hook
4857 */
4858 public function setHook( $tag, callable $callback ) {
4859 $tag = strtolower( $tag );
4860 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4861 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4862 }
4863 $oldVal = $this->mTagHooks[$tag] ?? null;
4864 $this->mTagHooks[$tag] = $callback;
4865 if ( !in_array( $tag, $this->mStripList ) ) {
4866 $this->mStripList[] = $tag;
4867 }
4868
4869 return $oldVal;
4870 }
4871
4872 /**
4873 * As setHook(), but letting the contents be parsed.
4874 *
4875 * Transparent tag hooks are like regular XML-style tag hooks, except they
4876 * operate late in the transformation sequence, on HTML instead of wikitext.
4877 *
4878 * This is probably obsoleted by things dealing with parser frames?
4879 * The only extension currently using it is geoserver.
4880 *
4881 * @since 1.10
4882 * @todo better document or deprecate this
4883 *
4884 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4885 * @param callable $callback The callback function (and object) to use for the tag
4886 * @throws MWException
4887 * @return callable|null The old value of the mTagHooks array associated with the hook
4888 */
4889 public function setTransparentTagHook( $tag, callable $callback ) {
4890 $tag = strtolower( $tag );
4891 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4892 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4893 }
4894 $oldVal = $this->mTransparentTagHooks[$tag] ?? null;
4895 $this->mTransparentTagHooks[$tag] = $callback;
4896
4897 return $oldVal;
4898 }
4899
4900 /**
4901 * Remove all tag hooks
4902 */
4903 public function clearTagHooks() {
4904 $this->mTagHooks = [];
4905 $this->mFunctionTagHooks = [];
4906 $this->mStripList = $this->mDefaultStripList;
4907 }
4908
4909 /**
4910 * Create a function, e.g. {{sum:1|2|3}}
4911 * The callback function should have the form:
4912 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4913 *
4914 * Or with Parser::SFH_OBJECT_ARGS:
4915 * function myParserFunction( $parser, $frame, $args ) { ... }
4916 *
4917 * The callback may either return the text result of the function, or an array with the text
4918 * in element 0, and a number of flags in the other elements. The names of the flags are
4919 * specified in the keys. Valid flags are:
4920 * found The text returned is valid, stop processing the template. This
4921 * is on by default.
4922 * nowiki Wiki markup in the return value should be escaped
4923 * isHTML The returned text is HTML, armour it against wikitext transformation
4924 *
4925 * @param string $id The magic word ID
4926 * @param callable $callback The callback function (and object) to use
4927 * @param int $flags A combination of the following flags:
4928 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4929 *
4930 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4931 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4932 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4933 * the arguments, and to control the way they are expanded.
4934 *
4935 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4936 * arguments, for instance:
4937 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4938 *
4939 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4940 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4941 * working if/when this is changed.
4942 *
4943 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4944 * expansion.
4945 *
4946 * Please read the documentation in includes/parser/Preprocessor.php for more information
4947 * about the methods available in PPFrame and PPNode.
4948 *
4949 * @throws MWException
4950 * @return string|callable The old callback function for this name, if any
4951 */
4952 public function setFunctionHook( $id, callable $callback, $flags = 0 ) {
4953 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4954 $this->mFunctionHooks[$id] = [ $callback, $flags ];
4955
4956 # Add to function cache
4957 $mw = $this->magicWordFactory->get( $id );
4958 if ( !$mw ) {
4959 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4960 }
4961
4962 $synonyms = $mw->getSynonyms();
4963 $sensitive = intval( $mw->isCaseSensitive() );
4964
4965 foreach ( $synonyms as $syn ) {
4966 # Case
4967 if ( !$sensitive ) {
4968 $syn = $this->contLang->lc( $syn );
4969 }
4970 # Add leading hash
4971 if ( !( $flags & self::SFH_NO_HASH ) ) {
4972 $syn = '#' . $syn;
4973 }
4974 # Remove trailing colon
4975 if ( substr( $syn, -1, 1 ) === ':' ) {
4976 $syn = substr( $syn, 0, -1 );
4977 }
4978 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4979 }
4980 return $oldVal;
4981 }
4982
4983 /**
4984 * Get all registered function hook identifiers
4985 *
4986 * @return array
4987 */
4988 public function getFunctionHooks() {
4989 $this->firstCallInit();
4990 return array_keys( $this->mFunctionHooks );
4991 }
4992
4993 /**
4994 * Create a tag function, e.g. "<test>some stuff</test>".
4995 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4996 * Unlike parser functions, their content is not preprocessed.
4997 * @param string $tag
4998 * @param callable $callback
4999 * @param int $flags
5000 * @throws MWException
5001 * @return null
5002 */
5003 public function setFunctionTagHook( $tag, callable $callback, $flags ) {
5004 $tag = strtolower( $tag );
5005 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5006 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5007 }
5008 $old = $this->mFunctionTagHooks[$tag] ?? null;
5009 $this->mFunctionTagHooks[$tag] = [ $callback, $flags ];
5010
5011 if ( !in_array( $tag, $this->mStripList ) ) {
5012 $this->mStripList[] = $tag;
5013 }
5014
5015 return $old;
5016 }
5017
5018 /**
5019 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5020 * Placeholders created in Linker::link()
5021 *
5022 * @param string &$text
5023 * @param int $options
5024 */
5025 public function replaceLinkHolders( &$text, $options = 0 ) {
5026 $this->mLinkHolders->replace( $text );
5027 }
5028
5029 /**
5030 * Replace "<!--LINK-->" link placeholders with plain text of links
5031 * (not HTML-formatted).
5032 *
5033 * @param string $text
5034 * @return string
5035 */
5036 public function replaceLinkHoldersText( $text ) {
5037 return $this->mLinkHolders->replaceText( $text );
5038 }
5039
5040 /**
5041 * Renders an image gallery from a text with one line per image.
5042 * text labels may be given by using |-style alternative text. E.g.
5043 * Image:one.jpg|The number "1"
5044 * Image:tree.jpg|A tree
5045 * given as text will return the HTML of a gallery with two images,
5046 * labeled 'The number "1"' and
5047 * 'A tree'.
5048 *
5049 * @param string $text
5050 * @param array $params
5051 * @return string HTML
5052 */
5053 public function renderImageGallery( $text, $params ) {
5054 $mode = false;
5055 if ( isset( $params['mode'] ) ) {
5056 $mode = $params['mode'];
5057 }
5058
5059 try {
5060 $ig = ImageGalleryBase::factory( $mode );
5061 } catch ( Exception $e ) {
5062 // If invalid type set, fallback to default.
5063 $ig = ImageGalleryBase::factory( false );
5064 }
5065
5066 $ig->setContextTitle( $this->mTitle );
5067 $ig->setShowBytes( false );
5068 $ig->setShowDimensions( false );
5069 $ig->setShowFilename( false );
5070 $ig->setParser( $this );
5071 $ig->setHideBadImages();
5072 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'ul' ) );
5073
5074 if ( isset( $params['showfilename'] ) ) {
5075 $ig->setShowFilename( true );
5076 } else {
5077 $ig->setShowFilename( false );
5078 }
5079 if ( isset( $params['caption'] ) ) {
5080 // NOTE: We aren't passing a frame here or below. Frame info
5081 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5082 // See T107332#4030581
5083 $caption = $this->recursiveTagParse( $params['caption'] );
5084 $ig->setCaptionHtml( $caption );
5085 }
5086 if ( isset( $params['perrow'] ) ) {
5087 $ig->setPerRow( $params['perrow'] );
5088 }
5089 if ( isset( $params['widths'] ) ) {
5090 $ig->setWidths( $params['widths'] );
5091 }
5092 if ( isset( $params['heights'] ) ) {
5093 $ig->setHeights( $params['heights'] );
5094 }
5095 $ig->setAdditionalOptions( $params );
5096
5097 // Avoid PHP 7.1 warning from passing $this by reference
5098 $parser = $this;
5099 Hooks::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5100
5101 $lines = StringUtils::explode( "\n", $text );
5102 foreach ( $lines as $line ) {
5103 # match lines like these:
5104 # Image:someimage.jpg|This is some image
5105 $matches = [];
5106 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5107 # Skip empty lines
5108 if ( count( $matches ) == 0 ) {
5109 continue;
5110 }
5111
5112 if ( strpos( $matches[0], '%' ) !== false ) {
5113 $matches[1] = rawurldecode( $matches[1] );
5114 }
5115 $title = Title::newFromText( $matches[1], NS_FILE );
5116 if ( is_null( $title ) ) {
5117 # Bogus title. Ignore these so we don't bomb out later.
5118 continue;
5119 }
5120
5121 # We need to get what handler the file uses, to figure out parameters.
5122 # Note, a hook can overide the file name, and chose an entirely different
5123 # file (which potentially could be of a different type and have different handler).
5124 $options = [];
5125 $descQuery = false;
5126 Hooks::run( 'BeforeParserFetchFileAndTitle',
5127 [ $this, $title, &$options, &$descQuery ] );
5128 # Don't register it now, as TraditionalImageGallery does that later.
5129 $file = $this->fetchFileNoRegister( $title, $options );
5130 $handler = $file ? $file->getHandler() : false;
5131
5132 $paramMap = [
5133 'img_alt' => 'gallery-internal-alt',
5134 'img_link' => 'gallery-internal-link',
5135 ];
5136 if ( $handler ) {
5137 $paramMap = $paramMap + $handler->getParamMap();
5138 // We don't want people to specify per-image widths.
5139 // Additionally the width parameter would need special casing anyhow.
5140 unset( $paramMap['img_width'] );
5141 }
5142
5143 $mwArray = $this->magicWordFactory->newArray( array_keys( $paramMap ) );
5144
5145 $label = '';
5146 $alt = '';
5147 $link = '';
5148 $handlerOptions = [];
5149 if ( isset( $matches[3] ) ) {
5150 // look for an |alt= definition while trying not to break existing
5151 // captions with multiple pipes (|) in it, until a more sensible grammar
5152 // is defined for images in galleries
5153
5154 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5155 // splitting on '|' is a bit odd, and different from makeImage.
5156 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5157 // Protect LanguageConverter markup
5158 $parameterMatches = StringUtils::delimiterExplode(
5159 '-{', '}-', '|', $matches[3], true /* nested */
5160 );
5161
5162 foreach ( $parameterMatches as $parameterMatch ) {
5163 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5164 if ( $magicName ) {
5165 $paramName = $paramMap[$magicName];
5166
5167 switch ( $paramName ) {
5168 case 'gallery-internal-alt':
5169 $alt = $this->stripAltText( $match, false );
5170 break;
5171 case 'gallery-internal-link':
5172 $linkValue = $this->stripAltText( $match, false );
5173 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5174 // Result of LanguageConverter::markNoConversion
5175 // invoked on an external link.
5176 $linkValue = substr( $linkValue, 4, -2 );
5177 }
5178 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5179 if ( $type === 'link-url' ) {
5180 $link = $target;
5181 $this->mOutput->addExternalLink( $target );
5182 } elseif ( $type === 'link-title' ) {
5183 $link = $target->getLinkURL();
5184 $this->mOutput->addLink( $target );
5185 }
5186 break;
5187 default:
5188 // Must be a handler specific parameter.
5189 if ( $handler->validateParam( $paramName, $match ) ) {
5190 $handlerOptions[$paramName] = $match;
5191 } else {
5192 // Guess not, consider it as caption.
5193 wfDebug( "$parameterMatch failed parameter validation\n" );
5194 $label = $parameterMatch;
5195 }
5196 }
5197
5198 } else {
5199 // Last pipe wins.
5200 $label = $parameterMatch;
5201 }
5202 }
5203 }
5204
5205 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5206 }
5207 $html = $ig->toHTML();
5208 Hooks::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5209 return $html;
5210 }
5211
5212 /**
5213 * @param MediaHandler $handler
5214 * @return array
5215 */
5216 public function getImageParams( $handler ) {
5217 if ( $handler ) {
5218 $handlerClass = get_class( $handler );
5219 } else {
5220 $handlerClass = '';
5221 }
5222 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5223 # Initialise static lists
5224 static $internalParamNames = [
5225 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5226 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5227 'bottom', 'text-bottom' ],
5228 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5229 'upright', 'border', 'link', 'alt', 'class' ],
5230 ];
5231 static $internalParamMap;
5232 if ( !$internalParamMap ) {
5233 $internalParamMap = [];
5234 foreach ( $internalParamNames as $type => $names ) {
5235 foreach ( $names as $name ) {
5236 // For grep: img_left, img_right, img_center, img_none,
5237 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5238 // img_bottom, img_text_bottom,
5239 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5240 // img_border, img_link, img_alt, img_class
5241 $magicName = str_replace( '-', '_', "img_$name" );
5242 $internalParamMap[$magicName] = [ $type, $name ];
5243 }
5244 }
5245 }
5246
5247 # Add handler params
5248 $paramMap = $internalParamMap;
5249 if ( $handler ) {
5250 $handlerParamMap = $handler->getParamMap();
5251 foreach ( $handlerParamMap as $magic => $paramName ) {
5252 $paramMap[$magic] = [ 'handler', $paramName ];
5253 }
5254 }
5255 $this->mImageParams[$handlerClass] = $paramMap;
5256 $this->mImageParamsMagicArray[$handlerClass] =
5257 $this->magicWordFactory->newArray( array_keys( $paramMap ) );
5258 }
5259 return [ $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ];
5260 }
5261
5262 /**
5263 * Parse image options text and use it to make an image
5264 *
5265 * @param Title $title
5266 * @param string $options
5267 * @param LinkHolderArray|bool $holders
5268 * @return string HTML
5269 */
5270 public function makeImage( $title, $options, $holders = false ) {
5271 # Check if the options text is of the form "options|alt text"
5272 # Options are:
5273 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5274 # * left no resizing, just left align. label is used for alt= only
5275 # * right same, but right aligned
5276 # * none same, but not aligned
5277 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5278 # * center center the image
5279 # * frame Keep original image size, no magnify-button.
5280 # * framed Same as "frame"
5281 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5282 # * upright reduce width for upright images, rounded to full __0 px
5283 # * border draw a 1px border around the image
5284 # * alt Text for HTML alt attribute (defaults to empty)
5285 # * class Set a class for img node
5286 # * link Set the target of the image link. Can be external, interwiki, or local
5287 # vertical-align values (no % or length right now):
5288 # * baseline
5289 # * sub
5290 # * super
5291 # * top
5292 # * text-top
5293 # * middle
5294 # * bottom
5295 # * text-bottom
5296
5297 global $wgMediaInTargetLanguage;
5298
5299 # Protect LanguageConverter markup when splitting into parts
5300 $parts = StringUtils::delimiterExplode(
5301 '-{', '}-', '|', $options, true /* allow nesting */
5302 );
5303
5304 # Give extensions a chance to select the file revision for us
5305 $options = [];
5306 $descQuery = false;
5307 Hooks::run( 'BeforeParserFetchFileAndTitle',
5308 [ $this, $title, &$options, &$descQuery ] );
5309 # Fetch and register the file (file title may be different via hooks)
5310 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5311
5312 # Get parameter map
5313 $handler = $file ? $file->getHandler() : false;
5314
5315 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5316
5317 if ( !$file ) {
5318 $this->addTrackingCategory( 'broken-file-category' );
5319 }
5320
5321 # Process the input parameters
5322 $caption = '';
5323 $params = [ 'frame' => [], 'handler' => [],
5324 'horizAlign' => [], 'vertAlign' => [] ];
5325 $seenformat = false;
5326 foreach ( $parts as $part ) {
5327 $part = trim( $part );
5328 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5329 $validated = false;
5330 if ( isset( $paramMap[$magicName] ) ) {
5331 list( $type, $paramName ) = $paramMap[$magicName];
5332
5333 # Special case; width and height come in one variable together
5334 if ( $type === 'handler' && $paramName === 'width' ) {
5335 $parsedWidthParam = self::parseWidthParam( $value );
5336 if ( isset( $parsedWidthParam['width'] ) ) {
5337 $width = $parsedWidthParam['width'];
5338 if ( $handler->validateParam( 'width', $width ) ) {
5339 $params[$type]['width'] = $width;
5340 $validated = true;
5341 }
5342 }
5343 if ( isset( $parsedWidthParam['height'] ) ) {
5344 $height = $parsedWidthParam['height'];
5345 if ( $handler->validateParam( 'height', $height ) ) {
5346 $params[$type]['height'] = $height;
5347 $validated = true;
5348 }
5349 }
5350 # else no validation -- T15436
5351 } else {
5352 if ( $type === 'handler' ) {
5353 # Validate handler parameter
5354 $validated = $handler->validateParam( $paramName, $value );
5355 } else {
5356 # Validate internal parameters
5357 switch ( $paramName ) {
5358 case 'manualthumb':
5359 case 'alt':
5360 case 'class':
5361 # @todo FIXME: Possibly check validity here for
5362 # manualthumb? downstream behavior seems odd with
5363 # missing manual thumbs.
5364 $validated = true;
5365 $value = $this->stripAltText( $value, $holders );
5366 break;
5367 case 'link':
5368 list( $paramName, $value ) =
5369 $this->parseLinkParameter(
5370 $this->stripAltText( $value, $holders )
5371 );
5372 if ( $paramName ) {
5373 $validated = true;
5374 if ( $paramName === 'no-link' ) {
5375 $value = true;
5376 }
5377 if ( $paramName === 'link-url' ) {
5378 if ( $this->mOptions->getExternalLinkTarget() ) {
5379 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5380 }
5381 }
5382 }
5383 break;
5384 case 'frameless':
5385 case 'framed':
5386 case 'thumbnail':
5387 // use first appearing option, discard others.
5388 $validated = !$seenformat;
5389 $seenformat = true;
5390 break;
5391 default:
5392 # Most other things appear to be empty or numeric...
5393 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5394 }
5395 }
5396
5397 if ( $validated ) {
5398 $params[$type][$paramName] = $value;
5399 }
5400 }
5401 }
5402 if ( !$validated ) {
5403 $caption = $part;
5404 }
5405 }
5406
5407 # Process alignment parameters
5408 if ( $params['horizAlign'] ) {
5409 $params['frame']['align'] = key( $params['horizAlign'] );
5410 }
5411 if ( $params['vertAlign'] ) {
5412 $params['frame']['valign'] = key( $params['vertAlign'] );
5413 }
5414
5415 $params['frame']['caption'] = $caption;
5416
5417 # Will the image be presented in a frame, with the caption below?
5418 $imageIsFramed = isset( $params['frame']['frame'] )
5419 || isset( $params['frame']['framed'] )
5420 || isset( $params['frame']['thumbnail'] )
5421 || isset( $params['frame']['manualthumb'] );
5422
5423 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5424 # came to also set the caption, ordinary text after the image -- which
5425 # makes no sense, because that just repeats the text multiple times in
5426 # screen readers. It *also* came to set the title attribute.
5427 # Now that we have an alt attribute, we should not set the alt text to
5428 # equal the caption: that's worse than useless, it just repeats the
5429 # text. This is the framed/thumbnail case. If there's no caption, we
5430 # use the unnamed parameter for alt text as well, just for the time be-
5431 # ing, if the unnamed param is set and the alt param is not.
5432 # For the future, we need to figure out if we want to tweak this more,
5433 # e.g., introducing a title= parameter for the title; ignoring the un-
5434 # named parameter entirely for images without a caption; adding an ex-
5435 # plicit caption= parameter and preserving the old magic unnamed para-
5436 # meter for BC; ...
5437 if ( $imageIsFramed ) { # Framed image
5438 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5439 # No caption or alt text, add the filename as the alt text so
5440 # that screen readers at least get some description of the image
5441 $params['frame']['alt'] = $title->getText();
5442 }
5443 # Do not set $params['frame']['title'] because tooltips don't make sense
5444 # for framed images
5445 } else { # Inline image
5446 if ( !isset( $params['frame']['alt'] ) ) {
5447 # No alt text, use the "caption" for the alt text
5448 if ( $caption !== '' ) {
5449 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5450 } else {
5451 # No caption, fall back to using the filename for the
5452 # alt text
5453 $params['frame']['alt'] = $title->getText();
5454 }
5455 }
5456 # Use the "caption" for the tooltip text
5457 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5458 }
5459 if ( $wgMediaInTargetLanguage ) {
5460 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5461 }
5462
5463 Hooks::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5464
5465 # Linker does the rest
5466 $time = $options['time'] ?? false;
5467 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5468 $time, $descQuery, $this->mOptions->getThumbSize() );
5469
5470 # Give the handler a chance to modify the parser object
5471 if ( $handler ) {
5472 $handler->parserTransformHook( $this, $file );
5473 }
5474
5475 return $ret;
5476 }
5477
5478 /**
5479 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5480 *
5481 * Adds an entry to appropriate link tables.
5482 *
5483 * @since 1.32
5484 * @param string $value
5485 * @return array of `[ type, target ]`, where:
5486 * - `type` is one of:
5487 * - `null`: Given value is not a valid link target, use default
5488 * - `'no-link'`: Given value is empty, do not generate a link
5489 * - `'link-url'`: Given value is a valid external link
5490 * - `'link-title'`: Given value is a valid internal link
5491 * - `target` is:
5492 * - When `type` is `null` or `'no-link'`: `false`
5493 * - When `type` is `'link-url'`: URL string corresponding to given value
5494 * - When `type` is `'link-title'`: Title object corresponding to given value
5495 */
5496 public function parseLinkParameter( $value ) {
5497 $chars = self::EXT_LINK_URL_CLASS;
5498 $addr = self::EXT_LINK_ADDR;
5499 $prots = $this->mUrlProtocols;
5500 $type = null;
5501 $target = false;
5502 if ( $value === '' ) {
5503 $type = 'no-link';
5504 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5505 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5506 $this->mOutput->addExternalLink( $value );
5507 $type = 'link-url';
5508 $target = $value;
5509 }
5510 } else {
5511 $linkTitle = Title::newFromText( $value );
5512 if ( $linkTitle ) {
5513 $this->mOutput->addLink( $linkTitle );
5514 $type = 'link-title';
5515 $target = $linkTitle;
5516 }
5517 }
5518 return [ $type, $target ];
5519 }
5520
5521 /**
5522 * @param string $caption
5523 * @param LinkHolderArray|bool $holders
5524 * @return mixed|string
5525 */
5526 protected function stripAltText( $caption, $holders ) {
5527 # Strip bad stuff out of the title (tooltip). We can't just use
5528 # replaceLinkHoldersText() here, because if this function is called
5529 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5530 if ( $holders ) {
5531 $tooltip = $holders->replaceText( $caption );
5532 } else {
5533 $tooltip = $this->replaceLinkHoldersText( $caption );
5534 }
5535
5536 # make sure there are no placeholders in thumbnail attributes
5537 # that are later expanded to html- so expand them now and
5538 # remove the tags
5539 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5540 # Compatibility hack! In HTML certain entity references not terminated
5541 # by a semicolon are decoded (but not if we're in an attribute; that's
5542 # how link URLs get away without properly escaping & in queries).
5543 # But wikitext has always required semicolon-termination of entities,
5544 # so encode & where needed to avoid decode of semicolon-less entities.
5545 # See T209236 and
5546 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5547 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5548 $tooltip = preg_replace( "/
5549 & # 1. entity prefix
5550 (?= # 2. followed by:
5551 (?: # a. one of the legacy semicolon-less named entities
5552 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5553 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5554 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5555 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5556 U(?:acute|circ|grave|uml)|Yacute|
5557 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5558 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5559 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5560 frac(?:1(?:2|4)|34)|
5561 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5562 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5563 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5564 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5565 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5566 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5567 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5568 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5569 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5570 )
5571 (?:[^;]|$)) # b. and not followed by a semicolon
5572 # S = study, for efficiency
5573 /Sx", '&amp;', $tooltip );
5574 $tooltip = Sanitizer::stripAllTags( $tooltip );
5575
5576 return $tooltip;
5577 }
5578
5579 /**
5580 * Set a flag in the output object indicating that the content is dynamic and
5581 * shouldn't be cached.
5582 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5583 */
5584 public function disableCache() {
5585 wfDebug( "Parser output marked as uncacheable.\n" );
5586 if ( !$this->mOutput ) {
5587 throw new MWException( __METHOD__ .
5588 " can only be called when actually parsing something" );
5589 }
5590 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5591 }
5592
5593 /**
5594 * Callback from the Sanitizer for expanding items found in HTML attribute
5595 * values, so they can be safely tested and escaped.
5596 *
5597 * @param string &$text
5598 * @param bool|PPFrame $frame
5599 * @return string
5600 */
5601 public function attributeStripCallback( &$text, $frame = false ) {
5602 $text = $this->replaceVariables( $text, $frame );
5603 $text = $this->mStripState->unstripBoth( $text );
5604 return $text;
5605 }
5606
5607 /**
5608 * Accessor
5609 *
5610 * @return array
5611 */
5612 public function getTags() {
5613 $this->firstCallInit();
5614 return array_merge(
5615 array_keys( $this->mTransparentTagHooks ),
5616 array_keys( $this->mTagHooks ),
5617 array_keys( $this->mFunctionTagHooks )
5618 );
5619 }
5620
5621 /**
5622 * @since 1.32
5623 * @return array
5624 */
5625 public function getFunctionSynonyms() {
5626 $this->firstCallInit();
5627 return $this->mFunctionSynonyms;
5628 }
5629
5630 /**
5631 * @since 1.32
5632 * @return string
5633 */
5634 public function getUrlProtocols() {
5635 return $this->mUrlProtocols;
5636 }
5637
5638 /**
5639 * Replace transparent tags in $text with the values given by the callbacks.
5640 *
5641 * Transparent tag hooks are like regular XML-style tag hooks, except they
5642 * operate late in the transformation sequence, on HTML instead of wikitext.
5643 *
5644 * @param string $text
5645 *
5646 * @return string
5647 */
5648 public function replaceTransparentTags( $text ) {
5649 $matches = [];
5650 $elements = array_keys( $this->mTransparentTagHooks );
5651 $text = self::extractTagsAndParams( $elements, $text, $matches );
5652 $replacements = [];
5653
5654 foreach ( $matches as $marker => $data ) {
5655 list( $element, $content, $params, $tag ) = $data;
5656 $tagName = strtolower( $element );
5657 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5658 $output = call_user_func_array(
5659 $this->mTransparentTagHooks[$tagName],
5660 [ $content, $params, $this ]
5661 );
5662 } else {
5663 $output = $tag;
5664 }
5665 $replacements[$marker] = $output;
5666 }
5667 return strtr( $text, $replacements );
5668 }
5669
5670 /**
5671 * Break wikitext input into sections, and either pull or replace
5672 * some particular section's text.
5673 *
5674 * External callers should use the getSection and replaceSection methods.
5675 *
5676 * @param string $text Page wikitext
5677 * @param string|int $sectionId A section identifier string of the form:
5678 * "<flag1> - <flag2> - ... - <section number>"
5679 *
5680 * Currently the only recognised flag is "T", which means the target section number
5681 * was derived during a template inclusion parse, in other words this is a template
5682 * section edit link. If no flags are given, it was an ordinary section edit link.
5683 * This flag is required to avoid a section numbering mismatch when a section is
5684 * enclosed by "<includeonly>" (T8563).
5685 *
5686 * The section number 0 pulls the text before the first heading; other numbers will
5687 * pull the given section along with its lower-level subsections. If the section is
5688 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5689 *
5690 * Section 0 is always considered to exist, even if it only contains the empty
5691 * string. If $text is the empty string and section 0 is replaced, $newText is
5692 * returned.
5693 *
5694 * @param string $mode One of "get" or "replace"
5695 * @param string $newText Replacement text for section data.
5696 * @return string For "get", the extracted section text.
5697 * for "replace", the whole page with the section replaced.
5698 */
5699 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5700 global $wgTitle; # not generally used but removes an ugly failure mode
5701
5702 $magicScopeVariable = $this->lock();
5703 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5704 $outText = '';
5705 $frame = $this->getPreprocessor()->newFrame();
5706
5707 # Process section extraction flags
5708 $flags = 0;
5709 $sectionParts = explode( '-', $sectionId );
5710 $sectionIndex = array_pop( $sectionParts );
5711 foreach ( $sectionParts as $part ) {
5712 if ( $part === 'T' ) {
5713 $flags |= self::PTD_FOR_INCLUSION;
5714 }
5715 }
5716
5717 # Check for empty input
5718 if ( strval( $text ) === '' ) {
5719 # Only sections 0 and T-0 exist in an empty document
5720 if ( $sectionIndex == 0 ) {
5721 if ( $mode === 'get' ) {
5722 return '';
5723 } else {
5724 return $newText;
5725 }
5726 } else {
5727 if ( $mode === 'get' ) {
5728 return $newText;
5729 } else {
5730 return $text;
5731 }
5732 }
5733 }
5734
5735 # Preprocess the text
5736 $root = $this->preprocessToDom( $text, $flags );
5737
5738 # <h> nodes indicate section breaks
5739 # They can only occur at the top level, so we can find them by iterating the root's children
5740 $node = $root->getFirstChild();
5741
5742 # Find the target section
5743 if ( $sectionIndex == 0 ) {
5744 # Section zero doesn't nest, level=big
5745 $targetLevel = 1000;
5746 } else {
5747 while ( $node ) {
5748 if ( $node->getName() === 'h' ) {
5749 $bits = $node->splitHeading();
5750 if ( $bits['i'] == $sectionIndex ) {
5751 $targetLevel = $bits['level'];
5752 break;
5753 }
5754 }
5755 if ( $mode === 'replace' ) {
5756 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5757 }
5758 $node = $node->getNextSibling();
5759 }
5760 }
5761
5762 if ( !$node ) {
5763 # Not found
5764 if ( $mode === 'get' ) {
5765 return $newText;
5766 } else {
5767 return $text;
5768 }
5769 }
5770
5771 # Find the end of the section, including nested sections
5772 do {
5773 if ( $node->getName() === 'h' ) {
5774 $bits = $node->splitHeading();
5775 $curLevel = $bits['level'];
5776 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5777 break;
5778 }
5779 }
5780 if ( $mode === 'get' ) {
5781 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5782 }
5783 $node = $node->getNextSibling();
5784 } while ( $node );
5785
5786 # Write out the remainder (in replace mode only)
5787 if ( $mode === 'replace' ) {
5788 # Output the replacement text
5789 # Add two newlines on -- trailing whitespace in $newText is conventionally
5790 # stripped by the editor, so we need both newlines to restore the paragraph gap
5791 # Only add trailing whitespace if there is newText
5792 if ( $newText != "" ) {
5793 $outText .= $newText . "\n\n";
5794 }
5795
5796 while ( $node ) {
5797 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5798 $node = $node->getNextSibling();
5799 }
5800 }
5801
5802 if ( is_string( $outText ) ) {
5803 # Re-insert stripped tags
5804 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5805 }
5806
5807 return $outText;
5808 }
5809
5810 /**
5811 * This function returns the text of a section, specified by a number ($section).
5812 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5813 * the first section before any such heading (section 0).
5814 *
5815 * If a section contains subsections, these are also returned.
5816 *
5817 * @param string $text Text to look in
5818 * @param string|int $sectionId Section identifier as a number or string
5819 * (e.g. 0, 1 or 'T-1').
5820 * @param string $defaultText Default to return if section is not found
5821 *
5822 * @return string Text of the requested section
5823 */
5824 public function getSection( $text, $sectionId, $defaultText = '' ) {
5825 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5826 }
5827
5828 /**
5829 * This function returns $oldtext after the content of the section
5830 * specified by $section has been replaced with $text. If the target
5831 * section does not exist, $oldtext is returned unchanged.
5832 *
5833 * @param string $oldText Former text of the article
5834 * @param string|int $sectionId Section identifier as a number or string
5835 * (e.g. 0, 1 or 'T-1').
5836 * @param string $newText Replacing text
5837 *
5838 * @return string Modified text
5839 */
5840 public function replaceSection( $oldText, $sectionId, $newText ) {
5841 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5842 }
5843
5844 /**
5845 * Get the ID of the revision we are parsing
5846 *
5847 * @return int|null
5848 */
5849 public function getRevisionId() {
5850 return $this->mRevisionId;
5851 }
5852
5853 /**
5854 * Get the revision object for $this->mRevisionId
5855 *
5856 * @return Revision|null Either a Revision object or null
5857 * @since 1.23 (public since 1.23)
5858 */
5859 public function getRevisionObject() {
5860 if ( !is_null( $this->mRevisionObject ) ) {
5861 return $this->mRevisionObject;
5862 }
5863
5864 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5865 // This is useful when parsing revision that has not yet been saved.
5866 // However, if we get back a saved revision even though we are in
5867 // preview mode, we'll have to ignore it, see below.
5868 // NOTE: This callback may be used to inject an OLD revision that was
5869 // already loaded, so "current" is a bit of a misnomer. We can't just
5870 // skip it if mRevisionId is set.
5871 $rev = call_user_func(
5872 $this->mOptions->getCurrentRevisionCallback(), $this->getTitle(), $this
5873 );
5874
5875 if ( $this->mRevisionId === null && $rev && $rev->getId() ) {
5876 // We are in preview mode (mRevisionId is null), and the current revision callback
5877 // returned an existing revision. Ignore it and return null, it's probably the page's
5878 // current revision, which is not what we want here. Note that we do want to call the
5879 // callback to allow the unsaved revision to be injected here, e.g. for
5880 // self-transclusion previews.
5881 return null;
5882 }
5883
5884 // If the parse is for a new revision, then the callback should have
5885 // already been set to force the object and should match mRevisionId.
5886 // If not, try to fetch by mRevisionId for sanity.
5887 if ( $this->mRevisionId && $rev && $rev->getId() != $this->mRevisionId ) {
5888 $rev = Revision::newFromId( $this->mRevisionId );
5889 }
5890
5891 $this->mRevisionObject = $rev;
5892
5893 return $this->mRevisionObject;
5894 }
5895
5896 /**
5897 * Get the timestamp associated with the current revision, adjusted for
5898 * the default server-local timestamp
5899 * @return string
5900 */
5901 public function getRevisionTimestamp() {
5902 if ( is_null( $this->mRevisionTimestamp ) ) {
5903 $revObject = $this->getRevisionObject();
5904 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5905
5906 # The cryptic '' timezone parameter tells to use the site-default
5907 # timezone offset instead of the user settings.
5908 # Since this value will be saved into the parser cache, served
5909 # to other users, and potentially even used inside links and such,
5910 # it needs to be consistent for all visitors.
5911 $this->mRevisionTimestamp = $this->contLang->userAdjust( $timestamp, '' );
5912 }
5913 return $this->mRevisionTimestamp;
5914 }
5915
5916 /**
5917 * Get the name of the user that edited the last revision
5918 *
5919 * @return string User name
5920 */
5921 public function getRevisionUser() {
5922 if ( is_null( $this->mRevisionUser ) ) {
5923 $revObject = $this->getRevisionObject();
5924
5925 # if this template is subst: the revision id will be blank,
5926 # so just use the current user's name
5927 if ( $revObject ) {
5928 $this->mRevisionUser = $revObject->getUserText();
5929 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5930 $this->mRevisionUser = $this->getUser()->getName();
5931 }
5932 }
5933 return $this->mRevisionUser;
5934 }
5935
5936 /**
5937 * Get the size of the revision
5938 *
5939 * @return int|null Revision size
5940 */
5941 public function getRevisionSize() {
5942 if ( is_null( $this->mRevisionSize ) ) {
5943 $revObject = $this->getRevisionObject();
5944
5945 # if this variable is subst: the revision id will be blank,
5946 # so just use the parser input size, because the own substituation
5947 # will change the size.
5948 if ( $revObject ) {
5949 $this->mRevisionSize = $revObject->getSize();
5950 } else {
5951 $this->mRevisionSize = $this->mInputSize;
5952 }
5953 }
5954 return $this->mRevisionSize;
5955 }
5956
5957 /**
5958 * Mutator for $mDefaultSort
5959 *
5960 * @param string $sort New value
5961 */
5962 public function setDefaultSort( $sort ) {
5963 $this->mDefaultSort = $sort;
5964 $this->mOutput->setProperty( 'defaultsort', $sort );
5965 }
5966
5967 /**
5968 * Accessor for $mDefaultSort
5969 * Will use the empty string if none is set.
5970 *
5971 * This value is treated as a prefix, so the
5972 * empty string is equivalent to sorting by
5973 * page name.
5974 *
5975 * @return string
5976 */
5977 public function getDefaultSort() {
5978 if ( $this->mDefaultSort !== false ) {
5979 return $this->mDefaultSort;
5980 } else {
5981 return '';
5982 }
5983 }
5984
5985 /**
5986 * Accessor for $mDefaultSort
5987 * Unlike getDefaultSort(), will return false if none is set
5988 *
5989 * @return string|bool
5990 */
5991 public function getCustomDefaultSort() {
5992 return $this->mDefaultSort;
5993 }
5994
5995 private static function getSectionNameFromStrippedText( $text ) {
5996 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5997 $text = Sanitizer::decodeCharReferences( $text );
5998 $text = self::normalizeSectionName( $text );
5999 return $text;
6000 }
6001
6002 private static function makeAnchor( $sectionName ) {
6003 return '#' . Sanitizer::escapeIdForLink( $sectionName );
6004 }
6005
6006 private function makeLegacyAnchor( $sectionName ) {
6007 $fragmentMode = $this->siteConfig->get( 'FragmentMode' );
6008 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
6009 // ForAttribute() and ForLink() are the same for legacy encoding
6010 $id = Sanitizer::escapeIdForAttribute( $sectionName, Sanitizer::ID_FALLBACK );
6011 } else {
6012 $id = Sanitizer::escapeIdForLink( $sectionName );
6013 }
6014
6015 return "#$id";
6016 }
6017
6018 /**
6019 * Try to guess the section anchor name based on a wikitext fragment
6020 * presumably extracted from a heading, for example "Header" from
6021 * "== Header ==".
6022 *
6023 * @param string $text
6024 * @return string Anchor (starting with '#')
6025 */
6026 public function guessSectionNameFromWikiText( $text ) {
6027 # Strip out wikitext links(they break the anchor)
6028 $text = $this->stripSectionName( $text );
6029 $sectionName = self::getSectionNameFromStrippedText( $text );
6030 return self::makeAnchor( $sectionName );
6031 }
6032
6033 /**
6034 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6035 * instead, if possible. For use in redirects, since various versions
6036 * of Microsoft browsers interpret Location: headers as something other
6037 * than UTF-8, resulting in breakage.
6038 *
6039 * @param string $text The section name
6040 * @return string Anchor (starting with '#')
6041 */
6042 public function guessLegacySectionNameFromWikiText( $text ) {
6043 # Strip out wikitext links(they break the anchor)
6044 $text = $this->stripSectionName( $text );
6045 $sectionName = self::getSectionNameFromStrippedText( $text );
6046 return $this->makeLegacyAnchor( $sectionName );
6047 }
6048
6049 /**
6050 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6051 * @param string $text Section name (plain text)
6052 * @return string Anchor (starting with '#')
6053 */
6054 public static function guessSectionNameFromStrippedText( $text ) {
6055 $sectionName = self::getSectionNameFromStrippedText( $text );
6056 return self::makeAnchor( $sectionName );
6057 }
6058
6059 /**
6060 * Apply the same normalization as code making links to this section would
6061 *
6062 * @param string $text
6063 * @return string
6064 */
6065 private static function normalizeSectionName( $text ) {
6066 # T90902: ensure the same normalization is applied for IDs as to links
6067 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
6068 try {
6069
6070 $parts = $titleParser->splitTitleString( "#$text" );
6071 } catch ( MalformedTitleException $ex ) {
6072 return $text;
6073 }
6074 return $parts['fragment'];
6075 }
6076
6077 /**
6078 * Strips a text string of wikitext for use in a section anchor
6079 *
6080 * Accepts a text string and then removes all wikitext from the
6081 * string and leaves only the resultant text (i.e. the result of
6082 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6083 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6084 * to create valid section anchors by mimicing the output of the
6085 * parser when headings are parsed.
6086 *
6087 * @param string $text Text string to be stripped of wikitext
6088 * for use in a Section anchor
6089 * @return string Filtered text string
6090 */
6091 public function stripSectionName( $text ) {
6092 # Strip internal link markup
6093 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6094 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6095
6096 # Strip external link markup
6097 # @todo FIXME: Not tolerant to blank link text
6098 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6099 # on how many empty links there are on the page - need to figure that out.
6100 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6101
6102 # Parse wikitext quotes (italics & bold)
6103 $text = $this->doQuotes( $text );
6104
6105 # Strip HTML tags
6106 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
6107 return $text;
6108 }
6109
6110 /**
6111 * strip/replaceVariables/unstrip for preprocessor regression testing
6112 *
6113 * @param string $text
6114 * @param Title $title
6115 * @param ParserOptions $options
6116 * @param int $outputType
6117 *
6118 * @return string
6119 */
6120 public function testSrvus( $text, Title $title, ParserOptions $options,
6121 $outputType = self::OT_HTML
6122 ) {
6123 $magicScopeVariable = $this->lock();
6124 $this->startParse( $title, $options, $outputType, true );
6125
6126 $text = $this->replaceVariables( $text );
6127 $text = $this->mStripState->unstripBoth( $text );
6128 $text = Sanitizer::removeHTMLtags( $text );
6129 return $text;
6130 }
6131
6132 /**
6133 * @param string $text
6134 * @param Title $title
6135 * @param ParserOptions $options
6136 * @return string
6137 */
6138 public function testPst( $text, Title $title, ParserOptions $options ) {
6139 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6140 }
6141
6142 /**
6143 * @param string $text
6144 * @param Title $title
6145 * @param ParserOptions $options
6146 * @return string
6147 */
6148 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
6149 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
6150 }
6151
6152 /**
6153 * Call a callback function on all regions of the given text that are not
6154 * inside strip markers, and replace those regions with the return value
6155 * of the callback. For example, with input:
6156 *
6157 * aaa<MARKER>bbb
6158 *
6159 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6160 * two strings will be replaced with the value returned by the callback in
6161 * each case.
6162 *
6163 * @param string $s
6164 * @param callable $callback
6165 *
6166 * @return string
6167 */
6168 public function markerSkipCallback( $s, $callback ) {
6169 $i = 0;
6170 $out = '';
6171 while ( $i < strlen( $s ) ) {
6172 $markerStart = strpos( $s, self::MARKER_PREFIX, $i );
6173 if ( $markerStart === false ) {
6174 $out .= call_user_func( $callback, substr( $s, $i ) );
6175 break;
6176 } else {
6177 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6178 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
6179 if ( $markerEnd === false ) {
6180 $out .= substr( $s, $markerStart );
6181 break;
6182 } else {
6183 $markerEnd += strlen( self::MARKER_SUFFIX );
6184 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6185 $i = $markerEnd;
6186 }
6187 }
6188 }
6189 return $out;
6190 }
6191
6192 /**
6193 * Remove any strip markers found in the given text.
6194 *
6195 * @param string $text
6196 * @return string
6197 */
6198 public function killMarkers( $text ) {
6199 return $this->mStripState->killMarkers( $text );
6200 }
6201
6202 /**
6203 * Save the parser state required to convert the given half-parsed text to
6204 * HTML. "Half-parsed" in this context means the output of
6205 * recursiveTagParse() or internalParse(). This output has strip markers
6206 * from replaceVariables (extensionSubstitution() etc.), and link
6207 * placeholders from replaceLinkHolders().
6208 *
6209 * Returns an array which can be serialized and stored persistently. This
6210 * array can later be loaded into another parser instance with
6211 * unserializeHalfParsedText(). The text can then be safely incorporated into
6212 * the return value of a parser hook.
6213 *
6214 * @deprecated since 1.31
6215 * @param string $text
6216 *
6217 * @return array
6218 */
6219 public function serializeHalfParsedText( $text ) {
6220 wfDeprecated( __METHOD__, '1.31' );
6221 $data = [
6222 'text' => $text,
6223 'version' => self::HALF_PARSED_VERSION,
6224 'stripState' => $this->mStripState->getSubState( $text ),
6225 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6226 ];
6227 return $data;
6228 }
6229
6230 /**
6231 * Load the parser state given in the $data array, which is assumed to
6232 * have been generated by serializeHalfParsedText(). The text contents is
6233 * extracted from the array, and its markers are transformed into markers
6234 * appropriate for the current Parser instance. This transformed text is
6235 * returned, and can be safely included in the return value of a parser
6236 * hook.
6237 *
6238 * If the $data array has been stored persistently, the caller should first
6239 * check whether it is still valid, by calling isValidHalfParsedText().
6240 *
6241 * @deprecated since 1.31
6242 * @param array $data Serialized data
6243 * @throws MWException
6244 * @return string
6245 */
6246 public function unserializeHalfParsedText( $data ) {
6247 wfDeprecated( __METHOD__, '1.31' );
6248 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6249 throw new MWException( __METHOD__ . ': invalid version' );
6250 }
6251
6252 # First, extract the strip state.
6253 $texts = [ $data['text'] ];
6254 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6255
6256 # Now renumber links
6257 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6258
6259 # Should be good to go.
6260 return $texts[0];
6261 }
6262
6263 /**
6264 * Returns true if the given array, presumed to be generated by
6265 * serializeHalfParsedText(), is compatible with the current version of the
6266 * parser.
6267 *
6268 * @deprecated since 1.31
6269 * @param array $data
6270 *
6271 * @return bool
6272 */
6273 public function isValidHalfParsedText( $data ) {
6274 wfDeprecated( __METHOD__, '1.31' );
6275 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6276 }
6277
6278 /**
6279 * Parsed a width param of imagelink like 300px or 200x300px
6280 *
6281 * @param string $value
6282 * @param bool $parseHeight
6283 *
6284 * @return array
6285 * @since 1.20
6286 */
6287 public static function parseWidthParam( $value, $parseHeight = true ) {
6288 $parsedWidthParam = [];
6289 if ( $value === '' ) {
6290 return $parsedWidthParam;
6291 }
6292 $m = [];
6293 # (T15500) In both cases (width/height and width only),
6294 # permit trailing "px" for backward compatibility.
6295 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6296 $width = intval( $m[1] );
6297 $height = intval( $m[2] );
6298 $parsedWidthParam['width'] = $width;
6299 $parsedWidthParam['height'] = $height;
6300 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6301 $width = intval( $value );
6302 $parsedWidthParam['width'] = $width;
6303 }
6304 return $parsedWidthParam;
6305 }
6306
6307 /**
6308 * Lock the current instance of the parser.
6309 *
6310 * This is meant to stop someone from calling the parser
6311 * recursively and messing up all the strip state.
6312 *
6313 * @throws MWException If parser is in a parse
6314 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6315 */
6316 protected function lock() {
6317 if ( $this->mInParse ) {
6318 throw new MWException( "Parser state cleared while parsing. "
6319 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse );
6320 }
6321
6322 // Save the backtrace when locking, so that if some code tries locking again,
6323 // we can print the lock owner's backtrace for easier debugging
6324 $e = new Exception;
6325 $this->mInParse = $e->getTraceAsString();
6326
6327 $recursiveCheck = new ScopedCallback( function () {
6328 $this->mInParse = false;
6329 } );
6330
6331 return $recursiveCheck;
6332 }
6333
6334 /**
6335 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6336 *
6337 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6338 * or if there is more than one <p/> tag in the input HTML.
6339 *
6340 * @param string $html
6341 * @return string
6342 * @since 1.24
6343 */
6344 public static function stripOuterParagraph( $html ) {
6345 $m = [];
6346 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6347 if ( strpos( $m[1], '</p>' ) === false ) {
6348 $html = $m[1];
6349 }
6350 }
6351
6352 return $html;
6353 }
6354
6355 /**
6356 * Return this parser if it is not doing anything, otherwise
6357 * get a fresh parser. You can use this method by doing
6358 * $myParser = $wgParser->getFreshParser(), or more simply
6359 * $wgParser->getFreshParser()->parse( ... );
6360 * if you're unsure if $wgParser is safe to use.
6361 *
6362 * @since 1.24
6363 * @return Parser A parser object that is not parsing anything
6364 */
6365 public function getFreshParser() {
6366 if ( $this->mInParse ) {
6367 return $this->factory->create();
6368 } else {
6369 return $this;
6370 }
6371 }
6372
6373 /**
6374 * Set's up the PHP implementation of OOUI for use in this request
6375 * and instructs OutputPage to enable OOUI for itself.
6376 *
6377 * @since 1.26
6378 */
6379 public function enableOOUI() {
6380 OutputPage::setupOOUI();
6381 $this->mOutput->setEnableOOUI( true );
6382 }
6383 }