Merge "Parse wikitext in gallery caption"
[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 $pageLang = $this->getFunctionLang();
2596
2597 switch ( $index ) {
2598 case '!':
2599 $value = '|';
2600 break;
2601 case 'currentmonth':
2602 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ), true );
2603 break;
2604 case 'currentmonth1':
2605 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ), true );
2606 break;
2607 case 'currentmonthname':
2608 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2609 break;
2610 case 'currentmonthnamegen':
2611 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2612 break;
2613 case 'currentmonthabbrev':
2614 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2615 break;
2616 case 'currentday':
2617 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ), true );
2618 break;
2619 case 'currentday2':
2620 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ), true );
2621 break;
2622 case 'localmonth':
2623 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ), true );
2624 break;
2625 case 'localmonth1':
2626 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ), true );
2627 break;
2628 case 'localmonthname':
2629 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2630 break;
2631 case 'localmonthnamegen':
2632 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2633 break;
2634 case 'localmonthabbrev':
2635 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2636 break;
2637 case 'localday':
2638 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ), true );
2639 break;
2640 case 'localday2':
2641 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ), true );
2642 break;
2643 case 'pagename':
2644 $value = wfEscapeWikiText( $this->mTitle->getText() );
2645 break;
2646 case 'pagenamee':
2647 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2648 break;
2649 case 'fullpagename':
2650 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2651 break;
2652 case 'fullpagenamee':
2653 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2654 break;
2655 case 'subpagename':
2656 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2657 break;
2658 case 'subpagenamee':
2659 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2660 break;
2661 case 'rootpagename':
2662 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2663 break;
2664 case 'rootpagenamee':
2665 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2666 ' ',
2667 '_',
2668 $this->mTitle->getRootText()
2669 ) ) );
2670 break;
2671 case 'basepagename':
2672 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2673 break;
2674 case 'basepagenamee':
2675 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2676 ' ',
2677 '_',
2678 $this->mTitle->getBaseText()
2679 ) ) );
2680 break;
2681 case 'talkpagename':
2682 if ( $this->mTitle->canHaveTalkPage() ) {
2683 $talkPage = $this->mTitle->getTalkPage();
2684 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2685 } else {
2686 $value = '';
2687 }
2688 break;
2689 case 'talkpagenamee':
2690 if ( $this->mTitle->canHaveTalkPage() ) {
2691 $talkPage = $this->mTitle->getTalkPage();
2692 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2693 } else {
2694 $value = '';
2695 }
2696 break;
2697 case 'subjectpagename':
2698 $subjPage = $this->mTitle->getSubjectPage();
2699 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2700 break;
2701 case 'subjectpagenamee':
2702 $subjPage = $this->mTitle->getSubjectPage();
2703 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2704 break;
2705 case 'pageid': // requested in T25427
2706 $pageid = $this->getTitle()->getArticleID();
2707 if ( $pageid == 0 ) {
2708 # 0 means the page doesn't exist in the database,
2709 # which means the user is previewing a new page.
2710 # The vary-revision flag must be set, because the magic word
2711 # will have a different value once the page is saved.
2712 $this->mOutput->setFlag( 'vary-revision' );
2713 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2714 }
2715 $value = $pageid ?: null;
2716 break;
2717 case 'revisionid':
2718 # Let the edit saving system know we should parse the page
2719 # *after* a revision ID has been assigned.
2720 $this->mOutput->setFlag( 'vary-revision-id' );
2721 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2722 $value = $this->mRevisionId;
2723
2724 if ( !$value ) {
2725 $rev = $this->getRevisionObject();
2726 if ( $rev ) {
2727 $value = $rev->getId();
2728 }
2729 }
2730
2731 if ( !$value ) {
2732 $value = $this->mOptions->getSpeculativeRevId();
2733 if ( $value ) {
2734 $this->mOutput->setSpeculativeRevIdUsed( $value );
2735 }
2736 }
2737 break;
2738 case 'revisionday':
2739 $value = (int)$this->getRevisionTimestampSubstring( 6, 2, self::MAX_TTS, $index );
2740 break;
2741 case 'revisionday2':
2742 $value = $this->getRevisionTimestampSubstring( 6, 2, self::MAX_TTS, $index );
2743 break;
2744 case 'revisionmonth':
2745 $value = $this->getRevisionTimestampSubstring( 4, 2, self::MAX_TTS, $index );
2746 break;
2747 case 'revisionmonth1':
2748 $value = (int)$this->getRevisionTimestampSubstring( 4, 2, self::MAX_TTS, $index );
2749 break;
2750 case 'revisionyear':
2751 $value = $this->getRevisionTimestampSubstring( 0, 4, self::MAX_TTS, $index );
2752 break;
2753 case 'revisiontimestamp':
2754 # Let the edit saving system know we should parse the page
2755 # *after* a revision ID has been assigned. This is for null edits.
2756 $this->mOutput->setFlag( 'vary-revision' );
2757 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2758 $value = $this->getRevisionTimestamp();
2759 break;
2760 case 'revisionuser':
2761 # Let the edit saving system know we should parse the page
2762 # *after* a revision ID has been assigned for null edits.
2763 $this->mOutput->setFlag( 'vary-user' );
2764 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-user...\n" );
2765 $value = $this->getRevisionUser();
2766 break;
2767 case 'revisionsize':
2768 $value = $this->getRevisionSize();
2769 break;
2770 case 'namespace':
2771 $value = str_replace( '_', ' ',
2772 $this->contLang->getNsText( $this->mTitle->getNamespace() ) );
2773 break;
2774 case 'namespacee':
2775 $value = wfUrlencode( $this->contLang->getNsText( $this->mTitle->getNamespace() ) );
2776 break;
2777 case 'namespacenumber':
2778 $value = $this->mTitle->getNamespace();
2779 break;
2780 case 'talkspace':
2781 $value = $this->mTitle->canHaveTalkPage()
2782 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
2783 : '';
2784 break;
2785 case 'talkspacee':
2786 $value = $this->mTitle->canHaveTalkPage() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2787 break;
2788 case 'subjectspace':
2789 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
2790 break;
2791 case 'subjectspacee':
2792 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2793 break;
2794 case 'currentdayname':
2795 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
2796 break;
2797 case 'currentyear':
2798 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
2799 break;
2800 case 'currenttime':
2801 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2802 break;
2803 case 'currenthour':
2804 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
2805 break;
2806 case 'currentweek':
2807 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2808 # int to remove the padding
2809 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
2810 break;
2811 case 'currentdow':
2812 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
2813 break;
2814 case 'localdayname':
2815 $value = $pageLang->getWeekdayName(
2816 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
2817 );
2818 break;
2819 case 'localyear':
2820 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
2821 break;
2822 case 'localtime':
2823 $value = $pageLang->time(
2824 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
2825 false,
2826 false
2827 );
2828 break;
2829 case 'localhour':
2830 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
2831 break;
2832 case 'localweek':
2833 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2834 # int to remove the padding
2835 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
2836 break;
2837 case 'localdow':
2838 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
2839 break;
2840 case 'numberofarticles':
2841 $value = $pageLang->formatNum( SiteStats::articles() );
2842 break;
2843 case 'numberoffiles':
2844 $value = $pageLang->formatNum( SiteStats::images() );
2845 break;
2846 case 'numberofusers':
2847 $value = $pageLang->formatNum( SiteStats::users() );
2848 break;
2849 case 'numberofactiveusers':
2850 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2851 break;
2852 case 'numberofpages':
2853 $value = $pageLang->formatNum( SiteStats::pages() );
2854 break;
2855 case 'numberofadmins':
2856 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2857 break;
2858 case 'numberofedits':
2859 $value = $pageLang->formatNum( SiteStats::edits() );
2860 break;
2861 case 'currenttimestamp':
2862 $value = wfTimestamp( TS_MW, $ts );
2863 break;
2864 case 'localtimestamp':
2865 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
2866 break;
2867 case 'currentversion':
2868 $value = SpecialVersion::getVersion();
2869 break;
2870 case 'articlepath':
2871 return $this->siteConfig->get( 'ArticlePath' );
2872 case 'sitename':
2873 return $this->siteConfig->get( 'Sitename' );
2874 case 'server':
2875 return $this->siteConfig->get( 'Server' );
2876 case 'servername':
2877 return $this->siteConfig->get( 'ServerName' );
2878 case 'scriptpath':
2879 return $this->siteConfig->get( 'ScriptPath' );
2880 case 'stylepath':
2881 return $this->siteConfig->get( 'StylePath' );
2882 case 'directionmark':
2883 return $pageLang->getDirMark();
2884 case 'contentlanguage':
2885 return $this->siteConfig->get( 'LanguageCode' );
2886 case 'pagelanguage':
2887 $value = $pageLang->getCode();
2888 break;
2889 case 'cascadingsources':
2890 $value = CoreParserFunctions::cascadingsources( $this );
2891 break;
2892 default:
2893 $ret = null;
2894 Hooks::run(
2895 'ParserGetVariableValueSwitch',
2896 [ &$parser, &$this->mVarCache, &$index, &$ret, &$frame ]
2897 );
2898
2899 return $ret;
2900 }
2901
2902 if ( $index ) {
2903 $this->mVarCache[$index] = $value;
2904 }
2905
2906 return $value;
2907 }
2908
2909 /**
2910 * @param int $start
2911 * @param int $len
2912 * @param int $mtts Max time-till-save; sets vary-revision if result might change by then
2913 * @param string $variable Parser variable name
2914 * @return string
2915 */
2916 private function getRevisionTimestampSubstring( $start, $len, $mtts, $variable ) {
2917 # Get the timezone-adjusted timestamp to be used for this revision
2918 $resNow = substr( $this->getRevisionTimestamp(), $start, $len );
2919 # Possibly set vary-revision if there is not yet an associated revision
2920 if ( !$this->getRevisionObject() ) {
2921 # Get the timezone-adjusted timestamp $mtts seconds in the future
2922 $resThen = substr(
2923 $this->contLang->userAdjust( wfTimestamp( TS_MW, time() + $mtts ), '' ),
2924 $start,
2925 $len
2926 );
2927
2928 if ( $resNow !== $resThen ) {
2929 # Let the edit saving system know we should parse the page
2930 # *after* a revision ID has been assigned. This is for null edits.
2931 $this->mOutput->setFlag( 'vary-revision' );
2932 wfDebug( __METHOD__ . ": $variable used, setting vary-revision...\n" );
2933 }
2934 }
2935
2936 return $resNow;
2937 }
2938
2939 /**
2940 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2941 *
2942 * @private
2943 */
2944 public function initialiseVariables() {
2945 $variableIDs = $this->magicWordFactory->getVariableIDs();
2946 $substIDs = $this->magicWordFactory->getSubstIDs();
2947
2948 $this->mVariables = $this->magicWordFactory->newArray( $variableIDs );
2949 $this->mSubstWords = $this->magicWordFactory->newArray( $substIDs );
2950 }
2951
2952 /**
2953 * Preprocess some wikitext and return the document tree.
2954 * This is the ghost of replace_variables().
2955 *
2956 * @param string $text The text to parse
2957 * @param int $flags Bitwise combination of:
2958 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2959 * included. Default is to assume a direct page view.
2960 *
2961 * The generated DOM tree must depend only on the input text and the flags.
2962 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2963 *
2964 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2965 * change in the DOM tree for a given text, must be passed through the section identifier
2966 * in the section edit link and thus back to extractSections().
2967 *
2968 * The output of this function is currently only cached in process memory, but a persistent
2969 * cache may be implemented at a later date which takes further advantage of these strict
2970 * dependency requirements.
2971 *
2972 * @return PPNode
2973 */
2974 public function preprocessToDom( $text, $flags = 0 ) {
2975 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2976 return $dom;
2977 }
2978
2979 /**
2980 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2981 *
2982 * @param string $s
2983 *
2984 * @return array
2985 */
2986 public static function splitWhitespace( $s ) {
2987 $ltrimmed = ltrim( $s );
2988 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2989 $trimmed = rtrim( $ltrimmed );
2990 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2991 if ( $diff > 0 ) {
2992 $w2 = substr( $ltrimmed, -$diff );
2993 } else {
2994 $w2 = '';
2995 }
2996 return [ $w1, $trimmed, $w2 ];
2997 }
2998
2999 /**
3000 * Replace magic variables, templates, and template arguments
3001 * with the appropriate text. Templates are substituted recursively,
3002 * taking care to avoid infinite loops.
3003 *
3004 * Note that the substitution depends on value of $mOutputType:
3005 * self::OT_WIKI: only {{subst:}} templates
3006 * self::OT_PREPROCESS: templates but not extension tags
3007 * self::OT_HTML: all templates and extension tags
3008 *
3009 * @param string $text The text to transform
3010 * @param bool|PPFrame $frame Object describing the arguments passed to the
3011 * template. Arguments may also be provided as an associative array, as
3012 * was the usual case before MW1.12. Providing arguments this way may be
3013 * useful for extensions wishing to perform variable replacement
3014 * explicitly.
3015 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3016 * double-brace expansion.
3017 * @return string
3018 */
3019 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3020 # Is there any text? Also, Prevent too big inclusions!
3021 $textSize = strlen( $text );
3022 if ( $textSize < 1 || $textSize > $this->mOptions->getMaxIncludeSize() ) {
3023 return $text;
3024 }
3025
3026 if ( $frame === false ) {
3027 $frame = $this->getPreprocessor()->newFrame();
3028 } elseif ( !( $frame instanceof PPFrame ) ) {
3029 wfDebug( __METHOD__ . " called using plain parameters instead of "
3030 . "a PPFrame instance. Creating custom frame.\n" );
3031 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3032 }
3033
3034 $dom = $this->preprocessToDom( $text );
3035 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3036 $text = $frame->expand( $dom, $flags );
3037
3038 return $text;
3039 }
3040
3041 /**
3042 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3043 *
3044 * @param array $args
3045 *
3046 * @return array
3047 */
3048 public static function createAssocArgs( $args ) {
3049 $assocArgs = [];
3050 $index = 1;
3051 foreach ( $args as $arg ) {
3052 $eqpos = strpos( $arg, '=' );
3053 if ( $eqpos === false ) {
3054 $assocArgs[$index++] = $arg;
3055 } else {
3056 $name = trim( substr( $arg, 0, $eqpos ) );
3057 $value = trim( substr( $arg, $eqpos + 1 ) );
3058 if ( $value === false ) {
3059 $value = '';
3060 }
3061 if ( $name !== false ) {
3062 $assocArgs[$name] = $value;
3063 }
3064 }
3065 }
3066
3067 return $assocArgs;
3068 }
3069
3070 /**
3071 * Warn the user when a parser limitation is reached
3072 * Will warn at most once the user per limitation type
3073 *
3074 * The results are shown during preview and run through the Parser (See EditPage.php)
3075 *
3076 * @param string $limitationType Should be one of:
3077 * 'expensive-parserfunction' (corresponding messages:
3078 * 'expensive-parserfunction-warning',
3079 * 'expensive-parserfunction-category')
3080 * 'post-expand-template-argument' (corresponding messages:
3081 * 'post-expand-template-argument-warning',
3082 * 'post-expand-template-argument-category')
3083 * 'post-expand-template-inclusion' (corresponding messages:
3084 * 'post-expand-template-inclusion-warning',
3085 * 'post-expand-template-inclusion-category')
3086 * 'node-count-exceeded' (corresponding messages:
3087 * 'node-count-exceeded-warning',
3088 * 'node-count-exceeded-category')
3089 * 'expansion-depth-exceeded' (corresponding messages:
3090 * 'expansion-depth-exceeded-warning',
3091 * 'expansion-depth-exceeded-category')
3092 * @param string|int|null $current Current value
3093 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3094 * exceeded, provide the values (optional)
3095 */
3096 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3097 # does no harm if $current and $max are present but are unnecessary for the message
3098 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3099 # only during preview, and that would split the parser cache unnecessarily.
3100 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3101 ->text();
3102 $this->mOutput->addWarning( $warning );
3103 $this->addTrackingCategory( "$limitationType-category" );
3104 }
3105
3106 /**
3107 * Return the text of a template, after recursively
3108 * replacing any variables or templates within the template.
3109 *
3110 * @param array $piece The parts of the template
3111 * $piece['title']: the title, i.e. the part before the |
3112 * $piece['parts']: the parameter array
3113 * $piece['lineStart']: whether the brace was at the start of a line
3114 * @param PPFrame $frame The current frame, contains template arguments
3115 * @throws Exception
3116 * @return string The text of the template
3117 */
3118 public function braceSubstitution( $piece, $frame ) {
3119 // Flags
3120
3121 // $text has been filled
3122 $found = false;
3123 // wiki markup in $text should be escaped
3124 $nowiki = false;
3125 // $text is HTML, armour it against wikitext transformation
3126 $isHTML = false;
3127 // Force interwiki transclusion to be done in raw mode not rendered
3128 $forceRawInterwiki = false;
3129 // $text is a DOM node needing expansion in a child frame
3130 $isChildObj = false;
3131 // $text is a DOM node needing expansion in the current frame
3132 $isLocalObj = false;
3133
3134 # Title object, where $text came from
3135 $title = false;
3136
3137 # $part1 is the bit before the first |, and must contain only title characters.
3138 # Various prefixes will be stripped from it later.
3139 $titleWithSpaces = $frame->expand( $piece['title'] );
3140 $part1 = trim( $titleWithSpaces );
3141 $titleText = false;
3142
3143 # Original title text preserved for various purposes
3144 $originalTitle = $part1;
3145
3146 # $args is a list of argument nodes, starting from index 0, not including $part1
3147 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3148 # below won't work b/c this $args isn't an object
3149 $args = ( null == $piece['parts'] ) ? [] : $piece['parts'];
3150
3151 $profileSection = null; // profile templates
3152
3153 # SUBST
3154 if ( !$found ) {
3155 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3156
3157 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3158 # Decide whether to expand template or keep wikitext as-is.
3159 if ( $this->ot['wiki'] ) {
3160 if ( $substMatch === false ) {
3161 $literal = true; # literal when in PST with no prefix
3162 } else {
3163 $literal = false; # expand when in PST with subst: or safesubst:
3164 }
3165 } else {
3166 if ( $substMatch == 'subst' ) {
3167 $literal = true; # literal when not in PST with plain subst:
3168 } else {
3169 $literal = false; # expand when not in PST with safesubst: or no prefix
3170 }
3171 }
3172 if ( $literal ) {
3173 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3174 $isLocalObj = true;
3175 $found = true;
3176 }
3177 }
3178
3179 # Variables
3180 if ( !$found && $args->getLength() == 0 ) {
3181 $id = $this->mVariables->matchStartToEnd( $part1 );
3182 if ( $id !== false ) {
3183 $text = $this->getVariableValue( $id, $frame );
3184 if ( $this->magicWordFactory->getCacheTTL( $id ) > -1 ) {
3185 $this->mOutput->updateCacheExpiry(
3186 $this->magicWordFactory->getCacheTTL( $id ) );
3187 }
3188 $found = true;
3189 }
3190 }
3191
3192 # MSG, MSGNW and RAW
3193 if ( !$found ) {
3194 # Check for MSGNW:
3195 $mwMsgnw = $this->magicWordFactory->get( 'msgnw' );
3196 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3197 $nowiki = true;
3198 } else {
3199 # Remove obsolete MSG:
3200 $mwMsg = $this->magicWordFactory->get( 'msg' );
3201 $mwMsg->matchStartAndRemove( $part1 );
3202 }
3203
3204 # Check for RAW:
3205 $mwRaw = $this->magicWordFactory->get( 'raw' );
3206 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3207 $forceRawInterwiki = true;
3208 }
3209 }
3210
3211 # Parser functions
3212 if ( !$found ) {
3213 $colonPos = strpos( $part1, ':' );
3214 if ( $colonPos !== false ) {
3215 $func = substr( $part1, 0, $colonPos );
3216 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3217 $argsLength = $args->getLength();
3218 for ( $i = 0; $i < $argsLength; $i++ ) {
3219 $funcArgs[] = $args->item( $i );
3220 }
3221
3222 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3223
3224 // Extract any forwarded flags
3225 if ( isset( $result['title'] ) ) {
3226 $title = $result['title'];
3227 }
3228 if ( isset( $result['found'] ) ) {
3229 $found = $result['found'];
3230 }
3231 if ( array_key_exists( 'text', $result ) ) {
3232 // a string or null
3233 $text = $result['text'];
3234 }
3235 if ( isset( $result['nowiki'] ) ) {
3236 $nowiki = $result['nowiki'];
3237 }
3238 if ( isset( $result['isHTML'] ) ) {
3239 $isHTML = $result['isHTML'];
3240 }
3241 if ( isset( $result['forceRawInterwiki'] ) ) {
3242 $forceRawInterwiki = $result['forceRawInterwiki'];
3243 }
3244 if ( isset( $result['isChildObj'] ) ) {
3245 $isChildObj = $result['isChildObj'];
3246 }
3247 if ( isset( $result['isLocalObj'] ) ) {
3248 $isLocalObj = $result['isLocalObj'];
3249 }
3250 }
3251 }
3252
3253 # Finish mangling title and then check for loops.
3254 # Set $title to a Title object and $titleText to the PDBK
3255 if ( !$found ) {
3256 $ns = NS_TEMPLATE;
3257 # Split the title into page and subpage
3258 $subpage = '';
3259 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3260 if ( $part1 !== $relative ) {
3261 $part1 = $relative;
3262 $ns = $this->mTitle->getNamespace();
3263 }
3264 $title = Title::newFromText( $part1, $ns );
3265 if ( $title ) {
3266 $titleText = $title->getPrefixedText();
3267 # Check for language variants if the template is not found
3268 if ( $this->getTargetLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3269 $this->getTargetLanguage()->findVariantLink( $part1, $title, true );
3270 }
3271 # Do recursion depth check
3272 $limit = $this->mOptions->getMaxTemplateDepth();
3273 if ( $frame->depth >= $limit ) {
3274 $found = true;
3275 $text = '<span class="error">'
3276 . wfMessage( 'parser-template-recursion-depth-warning' )
3277 ->numParams( $limit )->inContentLanguage()->text()
3278 . '</span>';
3279 }
3280 }
3281 }
3282
3283 # Load from database
3284 if ( !$found && $title ) {
3285 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3286 if ( !$title->isExternal() ) {
3287 if ( $title->isSpecialPage()
3288 && $this->mOptions->getAllowSpecialInclusion()
3289 && $this->ot['html']
3290 ) {
3291 $specialPage = $this->specialPageFactory->getPage( $title->getDBkey() );
3292 // Pass the template arguments as URL parameters.
3293 // "uselang" will have no effect since the Language object
3294 // is forced to the one defined in ParserOptions.
3295 $pageArgs = [];
3296 $argsLength = $args->getLength();
3297 for ( $i = 0; $i < $argsLength; $i++ ) {
3298 $bits = $args->item( $i )->splitArg();
3299 if ( strval( $bits['index'] ) === '' ) {
3300 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3301 $value = trim( $frame->expand( $bits['value'] ) );
3302 $pageArgs[$name] = $value;
3303 }
3304 }
3305
3306 // Create a new context to execute the special page
3307 $context = new RequestContext;
3308 $context->setTitle( $title );
3309 $context->setRequest( new FauxRequest( $pageArgs ) );
3310 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3311 $context->setUser( $this->getUser() );
3312 } else {
3313 // If this page is cached, then we better not be per user.
3314 $context->setUser( User::newFromName( '127.0.0.1', false ) );
3315 }
3316 $context->setLanguage( $this->mOptions->getUserLangObj() );
3317 $ret = $this->specialPageFactory->capturePath( $title, $context, $this->getLinkRenderer() );
3318 if ( $ret ) {
3319 $text = $context->getOutput()->getHTML();
3320 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3321 $found = true;
3322 $isHTML = true;
3323 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3324 $this->mOutput->updateRuntimeAdaptiveExpiry(
3325 $specialPage->maxIncludeCacheTime()
3326 );
3327 }
3328 }
3329 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3330 $found = false; # access denied
3331 wfDebug( __METHOD__ . ": template inclusion denied for " .
3332 $title->getPrefixedDBkey() . "\n" );
3333 } else {
3334 list( $text, $title ) = $this->getTemplateDom( $title );
3335 if ( $text !== false ) {
3336 $found = true;
3337 $isChildObj = true;
3338 }
3339 }
3340
3341 # If the title is valid but undisplayable, make a link to it
3342 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3343 $text = "[[:$titleText]]";
3344 $found = true;
3345 }
3346 } elseif ( $title->isTrans() ) {
3347 # Interwiki transclusion
3348 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3349 $text = $this->interwikiTransclude( $title, 'render' );
3350 $isHTML = true;
3351 } else {
3352 $text = $this->interwikiTransclude( $title, 'raw' );
3353 # Preprocess it like a template
3354 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3355 $isChildObj = true;
3356 }
3357 $found = true;
3358 }
3359
3360 # Do infinite loop check
3361 # This has to be done after redirect resolution to avoid infinite loops via redirects
3362 if ( !$frame->loopCheck( $title ) ) {
3363 $found = true;
3364 $text = '<span class="error">'
3365 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3366 . '</span>';
3367 $this->addTrackingCategory( 'template-loop-category' );
3368 $this->mOutput->addWarning( wfMessage( 'template-loop-warning',
3369 wfEscapeWikiText( $titleText ) )->text() );
3370 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3371 }
3372 }
3373
3374 # If we haven't found text to substitute by now, we're done
3375 # Recover the source wikitext and return it
3376 if ( !$found ) {
3377 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3378 if ( $profileSection ) {
3379 $this->mProfiler->scopedProfileOut( $profileSection );
3380 }
3381 return [ 'object' => $text ];
3382 }
3383
3384 # Expand DOM-style return values in a child frame
3385 if ( $isChildObj ) {
3386 # Clean up argument array
3387 $newFrame = $frame->newChild( $args, $title );
3388
3389 if ( $nowiki ) {
3390 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3391 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3392 # Expansion is eligible for the empty-frame cache
3393 $text = $newFrame->cachedExpand( $titleText, $text );
3394 } else {
3395 # Uncached expansion
3396 $text = $newFrame->expand( $text );
3397 }
3398 }
3399 if ( $isLocalObj && $nowiki ) {
3400 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3401 $isLocalObj = false;
3402 }
3403
3404 if ( $profileSection ) {
3405 $this->mProfiler->scopedProfileOut( $profileSection );
3406 }
3407
3408 # Replace raw HTML by a placeholder
3409 if ( $isHTML ) {
3410 $text = $this->insertStripItem( $text );
3411 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3412 # Escape nowiki-style return values
3413 $text = wfEscapeWikiText( $text );
3414 } elseif ( is_string( $text )
3415 && !$piece['lineStart']
3416 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3417 ) {
3418 # T2529: if the template begins with a table or block-level
3419 # element, it should be treated as beginning a new line.
3420 # This behavior is somewhat controversial.
3421 $text = "\n" . $text;
3422 }
3423
3424 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3425 # Error, oversize inclusion
3426 if ( $titleText !== false ) {
3427 # Make a working, properly escaped link if possible (T25588)
3428 $text = "[[:$titleText]]";
3429 } else {
3430 # This will probably not be a working link, but at least it may
3431 # provide some hint of where the problem is
3432 preg_replace( '/^:/', '', $originalTitle );
3433 $text = "[[:$originalTitle]]";
3434 }
3435 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3436 . 'post-expand include size too large -->' );
3437 $this->limitationWarn( 'post-expand-template-inclusion' );
3438 }
3439
3440 if ( $isLocalObj ) {
3441 $ret = [ 'object' => $text ];
3442 } else {
3443 $ret = [ 'text' => $text ];
3444 }
3445
3446 return $ret;
3447 }
3448
3449 /**
3450 * Call a parser function and return an array with text and flags.
3451 *
3452 * The returned array will always contain a boolean 'found', indicating
3453 * whether the parser function was found or not. It may also contain the
3454 * following:
3455 * text: string|object, resulting wikitext or PP DOM object
3456 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3457 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3458 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3459 * nowiki: bool, wiki markup in $text should be escaped
3460 *
3461 * @since 1.21
3462 * @param PPFrame $frame The current frame, contains template arguments
3463 * @param string $function Function name
3464 * @param array $args Arguments to the function
3465 * @throws MWException
3466 * @return array
3467 */
3468 public function callParserFunction( $frame, $function, array $args = [] ) {
3469 # Case sensitive functions
3470 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3471 $function = $this->mFunctionSynonyms[1][$function];
3472 } else {
3473 # Case insensitive functions
3474 $function = $this->contLang->lc( $function );
3475 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3476 $function = $this->mFunctionSynonyms[0][$function];
3477 } else {
3478 return [ 'found' => false ];
3479 }
3480 }
3481
3482 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3483
3484 // Avoid PHP 7.1 warning from passing $this by reference
3485 $parser = $this;
3486
3487 $allArgs = [ &$parser ];
3488 if ( $flags & self::SFH_OBJECT_ARGS ) {
3489 # Convert arguments to PPNodes and collect for appending to $allArgs
3490 $funcArgs = [];
3491 foreach ( $args as $k => $v ) {
3492 if ( $v instanceof PPNode || $k === 0 ) {
3493 $funcArgs[] = $v;
3494 } else {
3495 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( [ $k => $v ] )->item( 0 );
3496 }
3497 }
3498
3499 # Add a frame parameter, and pass the arguments as an array
3500 $allArgs[] = $frame;
3501 $allArgs[] = $funcArgs;
3502 } else {
3503 # Convert arguments to plain text and append to $allArgs
3504 foreach ( $args as $k => $v ) {
3505 if ( $v instanceof PPNode ) {
3506 $allArgs[] = trim( $frame->expand( $v ) );
3507 } elseif ( is_int( $k ) && $k >= 0 ) {
3508 $allArgs[] = trim( $v );
3509 } else {
3510 $allArgs[] = trim( "$k=$v" );
3511 }
3512 }
3513 }
3514
3515 $result = $callback( ...$allArgs );
3516
3517 # The interface for function hooks allows them to return a wikitext
3518 # string or an array containing the string and any flags. This mungs
3519 # things around to match what this method should return.
3520 if ( !is_array( $result ) ) {
3521 $result = [
3522 'found' => true,
3523 'text' => $result,
3524 ];
3525 } else {
3526 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3527 $result['text'] = $result[0];
3528 }
3529 unset( $result[0] );
3530 $result += [
3531 'found' => true,
3532 ];
3533 }
3534
3535 $noparse = true;
3536 $preprocessFlags = 0;
3537 if ( isset( $result['noparse'] ) ) {
3538 $noparse = $result['noparse'];
3539 }
3540 if ( isset( $result['preprocessFlags'] ) ) {
3541 $preprocessFlags = $result['preprocessFlags'];
3542 }
3543
3544 if ( !$noparse ) {
3545 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3546 $result['isChildObj'] = true;
3547 }
3548
3549 return $result;
3550 }
3551
3552 /**
3553 * Get the semi-parsed DOM representation of a template with a given title,
3554 * and its redirect destination title. Cached.
3555 *
3556 * @param Title $title
3557 *
3558 * @return array
3559 */
3560 public function getTemplateDom( $title ) {
3561 $cacheTitle = $title;
3562 $titleText = $title->getPrefixedDBkey();
3563
3564 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3565 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3566 $title = Title::makeTitle( $ns, $dbk );
3567 $titleText = $title->getPrefixedDBkey();
3568 }
3569 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3570 return [ $this->mTplDomCache[$titleText], $title ];
3571 }
3572
3573 # Cache miss, go to the database
3574 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3575
3576 if ( $text === false ) {
3577 $this->mTplDomCache[$titleText] = false;
3578 return [ false, $title ];
3579 }
3580
3581 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3582 $this->mTplDomCache[$titleText] = $dom;
3583
3584 if ( !$title->equals( $cacheTitle ) ) {
3585 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3586 [ $title->getNamespace(), $title->getDBkey() ];
3587 }
3588
3589 return [ $dom, $title ];
3590 }
3591
3592 /**
3593 * Fetch the current revision of a given title. Note that the revision
3594 * (and even the title) may not exist in the database, so everything
3595 * contributing to the output of the parser should use this method
3596 * where possible, rather than getting the revisions themselves. This
3597 * method also caches its results, so using it benefits performance.
3598 *
3599 * @since 1.24
3600 * @param Title $title
3601 * @return Revision
3602 */
3603 public function fetchCurrentRevisionOfTitle( $title ) {
3604 $cacheKey = $title->getPrefixedDBkey();
3605 if ( !$this->currentRevisionCache ) {
3606 $this->currentRevisionCache = new MapCacheLRU( 100 );
3607 }
3608 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3609 $this->currentRevisionCache->set( $cacheKey,
3610 // Defaults to Parser::statelessFetchRevision()
3611 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3612 );
3613 }
3614 return $this->currentRevisionCache->get( $cacheKey );
3615 }
3616
3617 /**
3618 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3619 * without passing them on to it.
3620 *
3621 * @since 1.24
3622 * @param Title $title
3623 * @param Parser|bool $parser
3624 * @return Revision|bool False if missing
3625 */
3626 public static function statelessFetchRevision( Title $title, $parser = false ) {
3627 $rev = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
3628
3629 return $rev;
3630 }
3631
3632 /**
3633 * Fetch the unparsed text of a template and register a reference to it.
3634 * @param Title $title
3635 * @return array ( string or false, Title )
3636 */
3637 public function fetchTemplateAndTitle( $title ) {
3638 // Defaults to Parser::statelessFetchTemplate()
3639 $templateCb = $this->mOptions->getTemplateCallback();
3640 $stuff = call_user_func( $templateCb, $title, $this );
3641 // We use U+007F DELETE to distinguish strip markers from regular text.
3642 $text = $stuff['text'];
3643 if ( is_string( $stuff['text'] ) ) {
3644 $text = strtr( $text, "\x7f", "?" );
3645 }
3646 $finalTitle = $stuff['finalTitle'] ?? $title;
3647 if ( isset( $stuff['deps'] ) ) {
3648 foreach ( $stuff['deps'] as $dep ) {
3649 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3650 if ( $dep['title']->equals( $this->getTitle() ) ) {
3651 // If we transclude ourselves, the final result
3652 // will change based on the new version of the page
3653 $this->mOutput->setFlag( 'vary-revision' );
3654 }
3655 }
3656 }
3657 return [ $text, $finalTitle ];
3658 }
3659
3660 /**
3661 * Fetch the unparsed text of a template and register a reference to it.
3662 * @param Title $title
3663 * @return string|bool
3664 */
3665 public function fetchTemplate( $title ) {
3666 return $this->fetchTemplateAndTitle( $title )[0];
3667 }
3668
3669 /**
3670 * Static function to get a template
3671 * Can be overridden via ParserOptions::setTemplateCallback().
3672 *
3673 * @param Title $title
3674 * @param bool|Parser $parser
3675 *
3676 * @return array
3677 */
3678 public static function statelessFetchTemplate( $title, $parser = false ) {
3679 $text = $skip = false;
3680 $finalTitle = $title;
3681 $deps = [];
3682
3683 # Loop to fetch the article, with up to 1 redirect
3684 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
3685 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3686 # Give extensions a chance to select the revision instead
3687 $id = false; # Assume current
3688 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3689 [ $parser, $title, &$skip, &$id ] );
3690
3691 if ( $skip ) {
3692 $text = false;
3693 $deps[] = [
3694 'title' => $title,
3695 'page_id' => $title->getArticleID(),
3696 'rev_id' => null
3697 ];
3698 break;
3699 }
3700 # Get the revision
3701 if ( $id ) {
3702 $rev = Revision::newFromId( $id );
3703 } elseif ( $parser ) {
3704 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3705 } else {
3706 $rev = Revision::newFromTitle( $title );
3707 }
3708 $rev_id = $rev ? $rev->getId() : 0;
3709 # If there is no current revision, there is no page
3710 if ( $id === false && !$rev ) {
3711 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3712 $linkCache->addBadLinkObj( $title );
3713 }
3714
3715 $deps[] = [
3716 'title' => $title,
3717 'page_id' => $title->getArticleID(),
3718 'rev_id' => $rev_id ];
3719 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3720 # We fetched a rev from a different title; register it too...
3721 $deps[] = [
3722 'title' => $rev->getTitle(),
3723 'page_id' => $rev->getPage(),
3724 'rev_id' => $rev_id ];
3725 }
3726
3727 if ( $rev ) {
3728 $content = $rev->getContent();
3729 $text = $content ? $content->getWikitextForTransclusion() : null;
3730
3731 Hooks::run( 'ParserFetchTemplate',
3732 [ $parser, $title, $rev, &$text, &$deps ] );
3733
3734 if ( $text === false || $text === null ) {
3735 $text = false;
3736 break;
3737 }
3738 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3739 $message = wfMessage( MediaWikiServices::getInstance()->getContentLanguage()->
3740 lcfirst( $title->getText() ) )->inContentLanguage();
3741 if ( !$message->exists() ) {
3742 $text = false;
3743 break;
3744 }
3745 $content = $message->content();
3746 $text = $message->plain();
3747 } else {
3748 break;
3749 }
3750 if ( !$content ) {
3751 break;
3752 }
3753 # Redirect?
3754 $finalTitle = $title;
3755 $title = $content->getRedirectTarget();
3756 }
3757 return [
3758 'text' => $text,
3759 'finalTitle' => $finalTitle,
3760 'deps' => $deps ];
3761 }
3762
3763 /**
3764 * Fetch a file and its title and register a reference to it.
3765 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3766 * @param Title $title
3767 * @param array $options Array of options to RepoGroup::findFile
3768 * @return File|bool
3769 * @deprecated since 1.32, use fetchFileAndTitle instead
3770 */
3771 public function fetchFile( $title, $options = [] ) {
3772 wfDeprecated( __METHOD__, '1.32' );
3773 return $this->fetchFileAndTitle( $title, $options )[0];
3774 }
3775
3776 /**
3777 * Fetch a file and its title and register a reference to it.
3778 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3779 * @param Title $title
3780 * @param array $options Array of options to RepoGroup::findFile
3781 * @return array ( File or false, Title of file )
3782 */
3783 public function fetchFileAndTitle( $title, $options = [] ) {
3784 $file = $this->fetchFileNoRegister( $title, $options );
3785
3786 $time = $file ? $file->getTimestamp() : false;
3787 $sha1 = $file ? $file->getSha1() : false;
3788 # Register the file as a dependency...
3789 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3790 if ( $file && !$title->equals( $file->getTitle() ) ) {
3791 # Update fetched file title
3792 $title = $file->getTitle();
3793 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3794 }
3795 return [ $file, $title ];
3796 }
3797
3798 /**
3799 * Helper function for fetchFileAndTitle.
3800 *
3801 * Also useful if you need to fetch a file but not use it yet,
3802 * for example to get the file's handler.
3803 *
3804 * @param Title $title
3805 * @param array $options Array of options to RepoGroup::findFile
3806 * @return File|bool
3807 */
3808 protected function fetchFileNoRegister( $title, $options = [] ) {
3809 if ( isset( $options['broken'] ) ) {
3810 $file = false; // broken thumbnail forced by hook
3811 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3812 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3813 } else { // get by (name,timestamp)
3814 $file = wfFindFile( $title, $options );
3815 }
3816 return $file;
3817 }
3818
3819 /**
3820 * Transclude an interwiki link.
3821 *
3822 * @param Title $title
3823 * @param string $action Usually one of (raw, render)
3824 *
3825 * @return string
3826 */
3827 public function interwikiTransclude( $title, $action ) {
3828 if ( !$this->siteConfig->get( 'EnableScaryTranscluding' ) ) {
3829 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3830 }
3831
3832 $url = $title->getFullURL( [ 'action' => $action ] );
3833 if ( strlen( $url ) > 1024 ) {
3834 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3835 }
3836
3837 $wikiId = $title->getTransWikiID(); // remote wiki ID or false
3838
3839 $fname = __METHOD__;
3840 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
3841
3842 $data = $cache->getWithSetCallback(
3843 $cache->makeGlobalKey(
3844 'interwiki-transclude',
3845 ( $wikiId !== false ) ? $wikiId : 'external',
3846 sha1( $url )
3847 ),
3848 $this->siteConfig->get( 'TranscludeCacheExpiry' ),
3849 function ( $oldValue, &$ttl ) use ( $url, $fname, $cache ) {
3850 $req = MWHttpRequest::factory( $url, [], $fname );
3851
3852 $status = $req->execute(); // Status object
3853 if ( !$status->isOK() ) {
3854 $ttl = $cache::TTL_UNCACHEABLE;
3855 } elseif ( $req->getResponseHeader( 'X-Database-Lagged' ) !== null ) {
3856 $ttl = min( $cache::TTL_LAGGED, $ttl );
3857 }
3858
3859 return [
3860 'text' => $status->isOK() ? $req->getContent() : null,
3861 'code' => $req->getStatus()
3862 ];
3863 },
3864 [
3865 'checkKeys' => ( $wikiId !== false )
3866 ? [ $cache->makeGlobalKey( 'interwiki-page', $wikiId, $title->getDBkey() ) ]
3867 : [],
3868 'pcGroup' => 'interwiki-transclude:5',
3869 'pcTTL' => $cache::TTL_PROC_LONG
3870 ]
3871 );
3872
3873 if ( is_string( $data['text'] ) ) {
3874 $text = $data['text'];
3875 } elseif ( $data['code'] != 200 ) {
3876 // Though we failed to fetch the content, this status is useless.
3877 $text = wfMessage( 'scarytranscludefailed-httpstatus' )
3878 ->params( $url, $data['code'] )->inContentLanguage()->text();
3879 } else {
3880 $text = wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3881 }
3882
3883 return $text;
3884 }
3885
3886 /**
3887 * Triple brace replacement -- used for template arguments
3888 * @private
3889 *
3890 * @param array $piece
3891 * @param PPFrame $frame
3892 *
3893 * @return array
3894 */
3895 public function argSubstitution( $piece, $frame ) {
3896 $error = false;
3897 $parts = $piece['parts'];
3898 $nameWithSpaces = $frame->expand( $piece['title'] );
3899 $argName = trim( $nameWithSpaces );
3900 $object = false;
3901 $text = $frame->getArgument( $argName );
3902 if ( $text === false && $parts->getLength() > 0
3903 && ( $this->ot['html']
3904 || $this->ot['pre']
3905 || ( $this->ot['wiki'] && $frame->isTemplate() )
3906 )
3907 ) {
3908 # No match in frame, use the supplied default
3909 $object = $parts->item( 0 )->getChildren();
3910 }
3911 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3912 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3913 $this->limitationWarn( 'post-expand-template-argument' );
3914 }
3915
3916 if ( $text === false && $object === false ) {
3917 # No match anywhere
3918 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3919 }
3920 if ( $error !== false ) {
3921 $text .= $error;
3922 }
3923 if ( $object !== false ) {
3924 $ret = [ 'object' => $object ];
3925 } else {
3926 $ret = [ 'text' => $text ];
3927 }
3928
3929 return $ret;
3930 }
3931
3932 /**
3933 * Return the text to be used for a given extension tag.
3934 * This is the ghost of strip().
3935 *
3936 * @param array $params Associative array of parameters:
3937 * name PPNode for the tag name
3938 * attr PPNode for unparsed text where tag attributes are thought to be
3939 * attributes Optional associative array of parsed attributes
3940 * inner Contents of extension element
3941 * noClose Original text did not have a close tag
3942 * @param PPFrame $frame
3943 *
3944 * @throws MWException
3945 * @return string
3946 */
3947 public function extensionSubstitution( $params, $frame ) {
3948 static $errorStr = '<span class="error">';
3949 static $errorLen = 20;
3950
3951 $name = $frame->expand( $params['name'] );
3952 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3953 // Probably expansion depth or node count exceeded. Just punt the
3954 // error up.
3955 return $name;
3956 }
3957
3958 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3959 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3960 // See above
3961 return $attrText;
3962 }
3963
3964 // We can't safely check if the expansion for $content resulted in an
3965 // error, because the content could happen to be the error string
3966 // (T149622).
3967 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3968
3969 $marker = self::MARKER_PREFIX . "-$name-"
3970 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3971
3972 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3973 ( $this->ot['html'] || $this->ot['pre'] );
3974 if ( $isFunctionTag ) {
3975 $markerType = 'none';
3976 } else {
3977 $markerType = 'general';
3978 }
3979 if ( $this->ot['html'] || $isFunctionTag ) {
3980 $name = strtolower( $name );
3981 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3982 if ( isset( $params['attributes'] ) ) {
3983 $attributes = $attributes + $params['attributes'];
3984 }
3985
3986 if ( isset( $this->mTagHooks[$name] ) ) {
3987 $output = call_user_func_array( $this->mTagHooks[$name],
3988 [ $content, $attributes, $this, $frame ] );
3989 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3990 list( $callback, ) = $this->mFunctionTagHooks[$name];
3991
3992 // Avoid PHP 7.1 warning from passing $this by reference
3993 $parser = $this;
3994 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3995 } else {
3996 $output = '<span class="error">Invalid tag extension name: ' .
3997 htmlspecialchars( $name ) . '</span>';
3998 }
3999
4000 if ( is_array( $output ) ) {
4001 // Extract flags
4002 $flags = $output;
4003 $output = $flags[0];
4004 if ( isset( $flags['markerType'] ) ) {
4005 $markerType = $flags['markerType'];
4006 }
4007 }
4008 } else {
4009 if ( is_null( $attrText ) ) {
4010 $attrText = '';
4011 }
4012 if ( isset( $params['attributes'] ) ) {
4013 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4014 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4015 htmlspecialchars( $attrValue ) . '"';
4016 }
4017 }
4018 if ( $content === null ) {
4019 $output = "<$name$attrText/>";
4020 } else {
4021 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4022 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
4023 // See above
4024 return $close;
4025 }
4026 $output = "<$name$attrText>$content$close";
4027 }
4028 }
4029
4030 if ( $markerType === 'none' ) {
4031 return $output;
4032 } elseif ( $markerType === 'nowiki' ) {
4033 $this->mStripState->addNoWiki( $marker, $output );
4034 } elseif ( $markerType === 'general' ) {
4035 $this->mStripState->addGeneral( $marker, $output );
4036 } else {
4037 throw new MWException( __METHOD__ . ': invalid marker type' );
4038 }
4039 return $marker;
4040 }
4041
4042 /**
4043 * Increment an include size counter
4044 *
4045 * @param string $type The type of expansion
4046 * @param int $size The size of the text
4047 * @return bool False if this inclusion would take it over the maximum, true otherwise
4048 */
4049 public function incrementIncludeSize( $type, $size ) {
4050 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4051 return false;
4052 } else {
4053 $this->mIncludeSizes[$type] += $size;
4054 return true;
4055 }
4056 }
4057
4058 /**
4059 * Increment the expensive function count
4060 *
4061 * @return bool False if the limit has been exceeded
4062 */
4063 public function incrementExpensiveFunctionCount() {
4064 $this->mExpensiveFunctionCount++;
4065 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4066 }
4067
4068 /**
4069 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4070 * Fills $this->mDoubleUnderscores, returns the modified text
4071 *
4072 * @param string $text
4073 *
4074 * @return string
4075 */
4076 public function doDoubleUnderscore( $text ) {
4077 # The position of __TOC__ needs to be recorded
4078 $mw = $this->magicWordFactory->get( 'toc' );
4079 if ( $mw->match( $text ) ) {
4080 $this->mShowToc = true;
4081 $this->mForceTocPosition = true;
4082
4083 # Set a placeholder. At the end we'll fill it in with the TOC.
4084 $text = $mw->replace( '<!--MWTOC\'"-->', $text, 1 );
4085
4086 # Only keep the first one.
4087 $text = $mw->replace( '', $text );
4088 }
4089
4090 # Now match and remove the rest of them
4091 $mwa = $this->magicWordFactory->getDoubleUnderscoreArray();
4092 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4093
4094 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4095 $this->mOutput->mNoGallery = true;
4096 }
4097 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4098 $this->mShowToc = false;
4099 }
4100 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4101 && $this->mTitle->getNamespace() == NS_CATEGORY
4102 ) {
4103 $this->addTrackingCategory( 'hidden-category-category' );
4104 }
4105 # (T10068) Allow control over whether robots index a page.
4106 # __INDEX__ always overrides __NOINDEX__, see T16899
4107 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4108 $this->mOutput->setIndexPolicy( 'noindex' );
4109 $this->addTrackingCategory( 'noindex-category' );
4110 }
4111 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4112 $this->mOutput->setIndexPolicy( 'index' );
4113 $this->addTrackingCategory( 'index-category' );
4114 }
4115
4116 # Cache all double underscores in the database
4117 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4118 $this->mOutput->setProperty( $key, '' );
4119 }
4120
4121 return $text;
4122 }
4123
4124 /**
4125 * @see ParserOutput::addTrackingCategory()
4126 * @param string $msg Message key
4127 * @return bool Whether the addition was successful
4128 */
4129 public function addTrackingCategory( $msg ) {
4130 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4131 }
4132
4133 /**
4134 * This function accomplishes several tasks:
4135 * 1) Auto-number headings if that option is enabled
4136 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4137 * 3) Add a Table of contents on the top for users who have enabled the option
4138 * 4) Auto-anchor headings
4139 *
4140 * It loops through all headlines, collects the necessary data, then splits up the
4141 * string and re-inserts the newly formatted headlines.
4142 *
4143 * @param string $text
4144 * @param string $origText Original, untouched wikitext
4145 * @param bool $isMain
4146 * @return mixed|string
4147 * @private
4148 */
4149 public function formatHeadings( $text, $origText, $isMain = true ) {
4150 # Inhibit editsection links if requested in the page
4151 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4152 $maybeShowEditLink = false;
4153 } else {
4154 $maybeShowEditLink = true; /* Actual presence will depend on post-cache transforms */
4155 }
4156
4157 # Get all headlines for numbering them and adding funky stuff like [edit]
4158 # links - this is for later, but we need the number of headlines right now
4159 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4160 # be trimmed here since whitespace in HTML headings is significant.
4161 $matches = [];
4162 $numMatches = preg_match_all(
4163 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4164 $text,
4165 $matches
4166 );
4167
4168 # if there are fewer than 4 headlines in the article, do not show TOC
4169 # unless it's been explicitly enabled.
4170 $enoughToc = $this->mShowToc &&
4171 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4172
4173 # Allow user to stipulate that a page should have a "new section"
4174 # link added via __NEWSECTIONLINK__
4175 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4176 $this->mOutput->setNewSection( true );
4177 }
4178
4179 # Allow user to remove the "new section"
4180 # link via __NONEWSECTIONLINK__
4181 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4182 $this->mOutput->hideNewSection( true );
4183 }
4184
4185 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4186 # override above conditions and always show TOC above first header
4187 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4188 $this->mShowToc = true;
4189 $enoughToc = true;
4190 }
4191
4192 # headline counter
4193 $headlineCount = 0;
4194 $numVisible = 0;
4195
4196 # Ugh .. the TOC should have neat indentation levels which can be
4197 # passed to the skin functions. These are determined here
4198 $toc = '';
4199 $full = '';
4200 $head = [];
4201 $sublevelCount = [];
4202 $levelCount = [];
4203 $level = 0;
4204 $prevlevel = 0;
4205 $toclevel = 0;
4206 $prevtoclevel = 0;
4207 $markerRegex = self::MARKER_PREFIX . "-h-(\d+)-" . self::MARKER_SUFFIX;
4208 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4209 $oldType = $this->mOutputType;
4210 $this->setOutputType( self::OT_WIKI );
4211 $frame = $this->getPreprocessor()->newFrame();
4212 $root = $this->preprocessToDom( $origText );
4213 $node = $root->getFirstChild();
4214 $byteOffset = 0;
4215 $tocraw = [];
4216 $refers = [];
4217
4218 $headlines = $numMatches !== false ? $matches[3] : [];
4219
4220 $maxTocLevel = $this->siteConfig->get( 'MaxTocLevel' );
4221 foreach ( $headlines as $headline ) {
4222 $isTemplate = false;
4223 $titleText = false;
4224 $sectionIndex = false;
4225 $numbering = '';
4226 $markerMatches = [];
4227 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4228 $serial = $markerMatches[1];
4229 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4230 $isTemplate = ( $titleText != $baseTitleText );
4231 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4232 }
4233
4234 if ( $toclevel ) {
4235 $prevlevel = $level;
4236 }
4237 $level = $matches[1][$headlineCount];
4238
4239 if ( $level > $prevlevel ) {
4240 # Increase TOC level
4241 $toclevel++;
4242 $sublevelCount[$toclevel] = 0;
4243 if ( $toclevel < $maxTocLevel ) {
4244 $prevtoclevel = $toclevel;
4245 $toc .= Linker::tocIndent();
4246 $numVisible++;
4247 }
4248 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4249 # Decrease TOC level, find level to jump to
4250
4251 for ( $i = $toclevel; $i > 0; $i-- ) {
4252 if ( $levelCount[$i] == $level ) {
4253 # Found last matching level
4254 $toclevel = $i;
4255 break;
4256 } elseif ( $levelCount[$i] < $level ) {
4257 # Found first matching level below current level
4258 $toclevel = $i + 1;
4259 break;
4260 }
4261 }
4262 if ( $i == 0 ) {
4263 $toclevel = 1;
4264 }
4265 if ( $toclevel < $maxTocLevel ) {
4266 if ( $prevtoclevel < $maxTocLevel ) {
4267 # Unindent only if the previous toc level was shown :p
4268 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4269 $prevtoclevel = $toclevel;
4270 } else {
4271 $toc .= Linker::tocLineEnd();
4272 }
4273 }
4274 } else {
4275 # No change in level, end TOC line
4276 if ( $toclevel < $maxTocLevel ) {
4277 $toc .= Linker::tocLineEnd();
4278 }
4279 }
4280
4281 $levelCount[$toclevel] = $level;
4282
4283 # count number of headlines for each level
4284 $sublevelCount[$toclevel]++;
4285 $dot = 0;
4286 for ( $i = 1; $i <= $toclevel; $i++ ) {
4287 if ( !empty( $sublevelCount[$i] ) ) {
4288 if ( $dot ) {
4289 $numbering .= '.';
4290 }
4291 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4292 $dot = 1;
4293 }
4294 }
4295
4296 # The safe header is a version of the header text safe to use for links
4297
4298 # Remove link placeholders by the link text.
4299 # <!--LINK number-->
4300 # turns into
4301 # link text with suffix
4302 # Do this before unstrip since link text can contain strip markers
4303 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4304
4305 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4306 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4307
4308 # Remove any <style> or <script> tags (T198618)
4309 $safeHeadline = preg_replace(
4310 '#<(style|script)(?: [^>]*[^>/])?>.*?</\1>#is',
4311 '',
4312 $safeHeadline
4313 );
4314
4315 # Strip out HTML (first regex removes any tag not allowed)
4316 # Allowed tags are:
4317 # * <sup> and <sub> (T10393)
4318 # * <i> (T28375)
4319 # * <b> (r105284)
4320 # * <bdi> (T74884)
4321 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4322 # * <s> and <strike> (T35715)
4323 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4324 # to allow setting directionality in toc items.
4325 $tocline = preg_replace(
4326 [
4327 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4328 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4329 ],
4330 [ '', '<$1>' ],
4331 $safeHeadline
4332 );
4333
4334 # Strip '<span></span>', which is the result from the above if
4335 # <span id="foo"></span> is used to produce an additional anchor
4336 # for a section.
4337 $tocline = str_replace( '<span></span>', '', $tocline );
4338
4339 $tocline = trim( $tocline );
4340
4341 # For the anchor, strip out HTML-y stuff period
4342 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4343 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4344
4345 # Save headline for section edit hint before it's escaped
4346 $headlineHint = $safeHeadline;
4347
4348 # Decode HTML entities
4349 $safeHeadline = Sanitizer::decodeCharReferences( $safeHeadline );
4350
4351 $safeHeadline = self::normalizeSectionName( $safeHeadline );
4352
4353 $fallbackHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_FALLBACK );
4354 $linkAnchor = Sanitizer::escapeIdForLink( $safeHeadline );
4355 $safeHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_PRIMARY );
4356 if ( $fallbackHeadline === $safeHeadline ) {
4357 # No reason to have both (in fact, we can't)
4358 $fallbackHeadline = false;
4359 }
4360
4361 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4362 # @todo FIXME: We may be changing them depending on the current locale.
4363 $arrayKey = strtolower( $safeHeadline );
4364 if ( $fallbackHeadline === false ) {
4365 $fallbackArrayKey = false;
4366 } else {
4367 $fallbackArrayKey = strtolower( $fallbackHeadline );
4368 }
4369
4370 # Create the anchor for linking from the TOC to the section
4371 $anchor = $safeHeadline;
4372 $fallbackAnchor = $fallbackHeadline;
4373 if ( isset( $refers[$arrayKey] ) ) {
4374 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4375 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++$i );
4376 $anchor .= "_$i";
4377 $linkAnchor .= "_$i";
4378 $refers["${arrayKey}_$i"] = true;
4379 } else {
4380 $refers[$arrayKey] = true;
4381 }
4382 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4383 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.Formatting.DisallowMultipleStatements
4384 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++$i );
4385 $fallbackAnchor .= "_$i";
4386 $refers["${fallbackArrayKey}_$i"] = true;
4387 } else {
4388 $refers[$fallbackArrayKey] = true;
4389 }
4390
4391 # Don't number the heading if it is the only one (looks silly)
4392 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4393 # the two are different if the line contains a link
4394 $headline = Html::element(
4395 'span',
4396 [ 'class' => 'mw-headline-number' ],
4397 $numbering
4398 ) . ' ' . $headline;
4399 }
4400
4401 if ( $enoughToc && ( !isset( $maxTocLevel ) || $toclevel < $maxTocLevel ) ) {
4402 $toc .= Linker::tocLine( $linkAnchor, $tocline,
4403 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4404 }
4405
4406 # Add the section to the section tree
4407 # Find the DOM node for this header
4408 $noOffset = ( $isTemplate || $sectionIndex === false );
4409 while ( $node && !$noOffset ) {
4410 if ( $node->getName() === 'h' ) {
4411 $bits = $node->splitHeading();
4412 if ( $bits['i'] == $sectionIndex ) {
4413 break;
4414 }
4415 }
4416 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4417 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4418 $node = $node->getNextSibling();
4419 }
4420 $tocraw[] = [
4421 'toclevel' => $toclevel,
4422 'level' => $level,
4423 'line' => $tocline,
4424 'number' => $numbering,
4425 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4426 'fromtitle' => $titleText,
4427 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4428 'anchor' => $anchor,
4429 ];
4430
4431 # give headline the correct <h#> tag
4432 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4433 // Output edit section links as markers with styles that can be customized by skins
4434 if ( $isTemplate ) {
4435 # Put a T flag in the section identifier, to indicate to extractSections()
4436 # that sections inside <includeonly> should be counted.
4437 $editsectionPage = $titleText;
4438 $editsectionSection = "T-$sectionIndex";
4439 $editsectionContent = null;
4440 } else {
4441 $editsectionPage = $this->mTitle->getPrefixedText();
4442 $editsectionSection = $sectionIndex;
4443 $editsectionContent = $headlineHint;
4444 }
4445 // We use a bit of pesudo-xml for editsection markers. The
4446 // language converter is run later on. Using a UNIQ style marker
4447 // leads to the converter screwing up the tokens when it
4448 // converts stuff. And trying to insert strip tags fails too. At
4449 // this point all real inputted tags have already been escaped,
4450 // so we don't have to worry about a user trying to input one of
4451 // these markers directly. We use a page and section attribute
4452 // to stop the language converter from converting these
4453 // important bits of data, but put the headline hint inside a
4454 // content block because the language converter is supposed to
4455 // be able to convert that piece of data.
4456 // Gets replaced with html in ParserOutput::getText
4457 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4458 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4459 if ( $editsectionContent !== null ) {
4460 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4461 } else {
4462 $editlink .= '/>';
4463 }
4464 } else {
4465 $editlink = '';
4466 }
4467 $head[$headlineCount] = Linker::makeHeadline( $level,
4468 $matches['attrib'][$headlineCount], $anchor, $headline,
4469 $editlink, $fallbackAnchor );
4470
4471 $headlineCount++;
4472 }
4473
4474 $this->setOutputType( $oldType );
4475
4476 # Never ever show TOC if no headers
4477 if ( $numVisible < 1 ) {
4478 $enoughToc = false;
4479 }
4480
4481 if ( $enoughToc ) {
4482 if ( $prevtoclevel > 0 && $prevtoclevel < $maxTocLevel ) {
4483 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4484 }
4485 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4486 $this->mOutput->setTOCHTML( $toc );
4487 $toc = self::TOC_START . $toc . self::TOC_END;
4488 }
4489
4490 if ( $isMain ) {
4491 $this->mOutput->setSections( $tocraw );
4492 }
4493
4494 # split up and insert constructed headlines
4495 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4496 $i = 0;
4497
4498 // build an array of document sections
4499 $sections = [];
4500 foreach ( $blocks as $block ) {
4501 // $head is zero-based, sections aren't.
4502 if ( empty( $head[$i - 1] ) ) {
4503 $sections[$i] = $block;
4504 } else {
4505 $sections[$i] = $head[$i - 1] . $block;
4506 }
4507
4508 /**
4509 * Send a hook, one per section.
4510 * The idea here is to be able to make section-level DIVs, but to do so in a
4511 * lower-impact, more correct way than r50769
4512 *
4513 * $this : caller
4514 * $section : the section number
4515 * &$sectionContent : ref to the content of the section
4516 * $maybeShowEditLinks : boolean describing whether this section has an edit link
4517 */
4518 Hooks::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4519
4520 $i++;
4521 }
4522
4523 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4524 // append the TOC at the beginning
4525 // Top anchor now in skin
4526 $sections[0] = $sections[0] . $toc . "\n";
4527 }
4528
4529 $full .= implode( '', $sections );
4530
4531 if ( $this->mForceTocPosition ) {
4532 return str_replace( '<!--MWTOC\'"-->', $toc, $full );
4533 } else {
4534 return $full;
4535 }
4536 }
4537
4538 /**
4539 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4540 * conversion, substituting signatures, {{subst:}} templates, etc.
4541 *
4542 * @param string $text The text to transform
4543 * @param Title $title The Title object for the current article
4544 * @param User $user The User object describing the current user
4545 * @param ParserOptions $options Parsing options
4546 * @param bool $clearState Whether to clear the parser state first
4547 * @return string The altered wiki markup
4548 */
4549 public function preSaveTransform( $text, Title $title, User $user,
4550 ParserOptions $options, $clearState = true
4551 ) {
4552 if ( $clearState ) {
4553 $magicScopeVariable = $this->lock();
4554 }
4555 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4556 $this->setUser( $user );
4557
4558 // Strip U+0000 NULL (T159174)
4559 $text = str_replace( "\000", '', $text );
4560
4561 // We still normalize line endings for backwards-compatibility
4562 // with other code that just calls PST, but this should already
4563 // be handled in TextContent subclasses
4564 $text = TextContent::normalizeLineEndings( $text );
4565
4566 if ( $options->getPreSaveTransform() ) {
4567 $text = $this->pstPass2( $text, $user );
4568 }
4569 $text = $this->mStripState->unstripBoth( $text );
4570
4571 $this->setUser( null ); # Reset
4572
4573 return $text;
4574 }
4575
4576 /**
4577 * Pre-save transform helper function
4578 *
4579 * @param string $text
4580 * @param User $user
4581 *
4582 * @return string
4583 */
4584 private function pstPass2( $text, $user ) {
4585 # Note: This is the timestamp saved as hardcoded wikitext to the database, we use
4586 # $this->contLang here in order to give everyone the same signature and use the default one
4587 # rather than the one selected in each user's preferences. (see also T14815)
4588 $ts = $this->mOptions->getTimestamp();
4589 $timestamp = MWTimestamp::getLocalInstance( $ts );
4590 $ts = $timestamp->format( 'YmdHis' );
4591 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4592
4593 $d = $this->contLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4594
4595 # Variable replacement
4596 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4597 $text = $this->replaceVariables( $text );
4598
4599 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4600 # which may corrupt this parser instance via its wfMessage()->text() call-
4601
4602 # Signatures
4603 if ( strpos( $text, '~~~' ) !== false ) {
4604 $sigText = $this->getUserSig( $user );
4605 $text = strtr( $text, [
4606 '~~~~~' => $d,
4607 '~~~~' => "$sigText $d",
4608 '~~~' => $sigText
4609 ] );
4610 # The main two signature forms used above are time-sensitive
4611 $this->mOutput->setFlag( 'user-signature' );
4612 }
4613
4614 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4615 $tc = '[' . Title::legalChars() . ']';
4616 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4617
4618 // [[ns:page (context)|]]
4619 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4620 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4621 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4622 // [[ns:page (context), context|]] (using either single or double-width comma)
4623 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4624 // [[|page]] (reverse pipe trick: add context from page title)
4625 $p2 = "/\[\[\\|($tc+)]]/";
4626
4627 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4628 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4629 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4630 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4631
4632 $t = $this->mTitle->getText();
4633 $m = [];
4634 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4635 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4636 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4637 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4638 } else {
4639 # if there's no context, don't bother duplicating the title
4640 $text = preg_replace( $p2, '[[\\1]]', $text );
4641 }
4642
4643 return $text;
4644 }
4645
4646 /**
4647 * Fetch the user's signature text, if any, and normalize to
4648 * validated, ready-to-insert wikitext.
4649 * If you have pre-fetched the nickname or the fancySig option, you can
4650 * specify them here to save a database query.
4651 * Do not reuse this parser instance after calling getUserSig(),
4652 * as it may have changed if it's the $wgParser.
4653 *
4654 * @param User &$user
4655 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4656 * @param bool|null $fancySig whether the nicknname is the complete signature
4657 * or null to use default value
4658 * @return string
4659 */
4660 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4661 $username = $user->getName();
4662
4663 # If not given, retrieve from the user object.
4664 if ( $nickname === false ) {
4665 $nickname = $user->getOption( 'nickname' );
4666 }
4667
4668 if ( is_null( $fancySig ) ) {
4669 $fancySig = $user->getBoolOption( 'fancysig' );
4670 }
4671
4672 $nickname = $nickname == null ? $username : $nickname;
4673
4674 if ( mb_strlen( $nickname ) > $this->siteConfig->get( 'MaxSigChars' ) ) {
4675 $nickname = $username;
4676 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4677 } elseif ( $fancySig !== false ) {
4678 # Sig. might contain markup; validate this
4679 if ( $this->validateSig( $nickname ) !== false ) {
4680 # Validated; clean up (if needed) and return it
4681 return $this->cleanSig( $nickname, true );
4682 } else {
4683 # Failed to validate; fall back to the default
4684 $nickname = $username;
4685 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4686 }
4687 }
4688
4689 # Make sure nickname doesnt get a sig in a sig
4690 $nickname = self::cleanSigInSig( $nickname );
4691
4692 # If we're still here, make it a link to the user page
4693 $userText = wfEscapeWikiText( $username );
4694 $nickText = wfEscapeWikiText( $nickname );
4695 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4696
4697 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4698 ->title( $this->getTitle() )->text();
4699 }
4700
4701 /**
4702 * Check that the user's signature contains no bad XML
4703 *
4704 * @param string $text
4705 * @return string|bool An expanded string, or false if invalid.
4706 */
4707 public function validateSig( $text ) {
4708 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4709 }
4710
4711 /**
4712 * Clean up signature text
4713 *
4714 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4715 * 2) Substitute all transclusions
4716 *
4717 * @param string $text
4718 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4719 * @return string Signature text
4720 */
4721 public function cleanSig( $text, $parsing = false ) {
4722 if ( !$parsing ) {
4723 global $wgTitle;
4724 $magicScopeVariable = $this->lock();
4725 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4726 }
4727
4728 # Option to disable this feature
4729 if ( !$this->mOptions->getCleanSignatures() ) {
4730 return $text;
4731 }
4732
4733 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4734 # => Move this logic to braceSubstitution()
4735 $substWord = $this->magicWordFactory->get( 'subst' );
4736 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4737 $substText = '{{' . $substWord->getSynonym( 0 );
4738
4739 $text = preg_replace( $substRegex, $substText, $text );
4740 $text = self::cleanSigInSig( $text );
4741 $dom = $this->preprocessToDom( $text );
4742 $frame = $this->getPreprocessor()->newFrame();
4743 $text = $frame->expand( $dom );
4744
4745 if ( !$parsing ) {
4746 $text = $this->mStripState->unstripBoth( $text );
4747 }
4748
4749 return $text;
4750 }
4751
4752 /**
4753 * Strip 3, 4 or 5 tildes out of signatures.
4754 *
4755 * @param string $text
4756 * @return string Signature text with /~{3,5}/ removed
4757 */
4758 public static function cleanSigInSig( $text ) {
4759 $text = preg_replace( '/~{3,5}/', '', $text );
4760 return $text;
4761 }
4762
4763 /**
4764 * Set up some variables which are usually set up in parse()
4765 * so that an external function can call some class members with confidence
4766 *
4767 * @param Title|null $title
4768 * @param ParserOptions $options
4769 * @param int $outputType
4770 * @param bool $clearState
4771 */
4772 public function startExternalParse( Title $title = null, ParserOptions $options,
4773 $outputType, $clearState = true
4774 ) {
4775 $this->startParse( $title, $options, $outputType, $clearState );
4776 }
4777
4778 /**
4779 * @param Title|null $title
4780 * @param ParserOptions $options
4781 * @param int $outputType
4782 * @param bool $clearState
4783 */
4784 private function startParse( Title $title = null, ParserOptions $options,
4785 $outputType, $clearState = true
4786 ) {
4787 $this->setTitle( $title );
4788 $this->mOptions = $options;
4789 $this->setOutputType( $outputType );
4790 if ( $clearState ) {
4791 $this->clearState();
4792 }
4793 }
4794
4795 /**
4796 * Wrapper for preprocess()
4797 *
4798 * @param string $text The text to preprocess
4799 * @param ParserOptions $options
4800 * @param Title|null $title Title object or null to use $wgTitle
4801 * @return string
4802 */
4803 public function transformMsg( $text, $options, $title = null ) {
4804 static $executing = false;
4805
4806 # Guard against infinite recursion
4807 if ( $executing ) {
4808 return $text;
4809 }
4810 $executing = true;
4811
4812 if ( !$title ) {
4813 global $wgTitle;
4814 $title = $wgTitle;
4815 }
4816
4817 $text = $this->preprocess( $text, $title, $options );
4818
4819 $executing = false;
4820 return $text;
4821 }
4822
4823 /**
4824 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4825 * The callback should have the following form:
4826 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4827 *
4828 * Transform and return $text. Use $parser for any required context, e.g. use
4829 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4830 *
4831 * Hooks may return extended information by returning an array, of which the
4832 * first numbered element (index 0) must be the return string, and all other
4833 * entries are extracted into local variables within an internal function
4834 * in the Parser class.
4835 *
4836 * This interface (introduced r61913) appears to be undocumented, but
4837 * 'markerType' is used by some core tag hooks to override which strip
4838 * array their results are placed in. **Use great caution if attempting
4839 * this interface, as it is not documented and injudicious use could smash
4840 * private variables.**
4841 *
4842 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4843 * @param callable $callback The callback function (and object) to use for the tag
4844 * @throws MWException
4845 * @return callable|null The old value of the mTagHooks array associated with the hook
4846 */
4847 public function setHook( $tag, callable $callback ) {
4848 $tag = strtolower( $tag );
4849 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4850 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4851 }
4852 $oldVal = $this->mTagHooks[$tag] ?? null;
4853 $this->mTagHooks[$tag] = $callback;
4854 if ( !in_array( $tag, $this->mStripList ) ) {
4855 $this->mStripList[] = $tag;
4856 }
4857
4858 return $oldVal;
4859 }
4860
4861 /**
4862 * As setHook(), but letting the contents be parsed.
4863 *
4864 * Transparent tag hooks are like regular XML-style tag hooks, except they
4865 * operate late in the transformation sequence, on HTML instead of wikitext.
4866 *
4867 * This is probably obsoleted by things dealing with parser frames?
4868 * The only extension currently using it is geoserver.
4869 *
4870 * @since 1.10
4871 * @todo better document or deprecate this
4872 *
4873 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4874 * @param callable $callback The callback function (and object) to use for the tag
4875 * @throws MWException
4876 * @return callable|null The old value of the mTagHooks array associated with the hook
4877 */
4878 public function setTransparentTagHook( $tag, callable $callback ) {
4879 $tag = strtolower( $tag );
4880 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4881 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4882 }
4883 $oldVal = $this->mTransparentTagHooks[$tag] ?? null;
4884 $this->mTransparentTagHooks[$tag] = $callback;
4885
4886 return $oldVal;
4887 }
4888
4889 /**
4890 * Remove all tag hooks
4891 */
4892 public function clearTagHooks() {
4893 $this->mTagHooks = [];
4894 $this->mFunctionTagHooks = [];
4895 $this->mStripList = $this->mDefaultStripList;
4896 }
4897
4898 /**
4899 * Create a function, e.g. {{sum:1|2|3}}
4900 * The callback function should have the form:
4901 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4902 *
4903 * Or with Parser::SFH_OBJECT_ARGS:
4904 * function myParserFunction( $parser, $frame, $args ) { ... }
4905 *
4906 * The callback may either return the text result of the function, or an array with the text
4907 * in element 0, and a number of flags in the other elements. The names of the flags are
4908 * specified in the keys. Valid flags are:
4909 * found The text returned is valid, stop processing the template. This
4910 * is on by default.
4911 * nowiki Wiki markup in the return value should be escaped
4912 * isHTML The returned text is HTML, armour it against wikitext transformation
4913 *
4914 * @param string $id The magic word ID
4915 * @param callable $callback The callback function (and object) to use
4916 * @param int $flags A combination of the following flags:
4917 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4918 *
4919 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4920 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4921 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4922 * the arguments, and to control the way they are expanded.
4923 *
4924 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4925 * arguments, for instance:
4926 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4927 *
4928 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4929 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4930 * working if/when this is changed.
4931 *
4932 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4933 * expansion.
4934 *
4935 * Please read the documentation in includes/parser/Preprocessor.php for more information
4936 * about the methods available in PPFrame and PPNode.
4937 *
4938 * @throws MWException
4939 * @return string|callable The old callback function for this name, if any
4940 */
4941 public function setFunctionHook( $id, callable $callback, $flags = 0 ) {
4942 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4943 $this->mFunctionHooks[$id] = [ $callback, $flags ];
4944
4945 # Add to function cache
4946 $mw = $this->magicWordFactory->get( $id );
4947 if ( !$mw ) {
4948 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4949 }
4950
4951 $synonyms = $mw->getSynonyms();
4952 $sensitive = intval( $mw->isCaseSensitive() );
4953
4954 foreach ( $synonyms as $syn ) {
4955 # Case
4956 if ( !$sensitive ) {
4957 $syn = $this->contLang->lc( $syn );
4958 }
4959 # Add leading hash
4960 if ( !( $flags & self::SFH_NO_HASH ) ) {
4961 $syn = '#' . $syn;
4962 }
4963 # Remove trailing colon
4964 if ( substr( $syn, -1, 1 ) === ':' ) {
4965 $syn = substr( $syn, 0, -1 );
4966 }
4967 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4968 }
4969 return $oldVal;
4970 }
4971
4972 /**
4973 * Get all registered function hook identifiers
4974 *
4975 * @return array
4976 */
4977 public function getFunctionHooks() {
4978 $this->firstCallInit();
4979 return array_keys( $this->mFunctionHooks );
4980 }
4981
4982 /**
4983 * Create a tag function, e.g. "<test>some stuff</test>".
4984 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4985 * Unlike parser functions, their content is not preprocessed.
4986 * @param string $tag
4987 * @param callable $callback
4988 * @param int $flags
4989 * @throws MWException
4990 * @return null
4991 */
4992 public function setFunctionTagHook( $tag, callable $callback, $flags ) {
4993 $tag = strtolower( $tag );
4994 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4995 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4996 }
4997 $old = $this->mFunctionTagHooks[$tag] ?? null;
4998 $this->mFunctionTagHooks[$tag] = [ $callback, $flags ];
4999
5000 if ( !in_array( $tag, $this->mStripList ) ) {
5001 $this->mStripList[] = $tag;
5002 }
5003
5004 return $old;
5005 }
5006
5007 /**
5008 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5009 * Placeholders created in Linker::link()
5010 *
5011 * @param string &$text
5012 * @param int $options
5013 */
5014 public function replaceLinkHolders( &$text, $options = 0 ) {
5015 $this->mLinkHolders->replace( $text );
5016 }
5017
5018 /**
5019 * Replace "<!--LINK-->" link placeholders with plain text of links
5020 * (not HTML-formatted).
5021 *
5022 * @param string $text
5023 * @return string
5024 */
5025 public function replaceLinkHoldersText( $text ) {
5026 return $this->mLinkHolders->replaceText( $text );
5027 }
5028
5029 /**
5030 * Renders an image gallery from a text with one line per image.
5031 * text labels may be given by using |-style alternative text. E.g.
5032 * Image:one.jpg|The number "1"
5033 * Image:tree.jpg|A tree
5034 * given as text will return the HTML of a gallery with two images,
5035 * labeled 'The number "1"' and
5036 * 'A tree'.
5037 *
5038 * @param string $text
5039 * @param array $params
5040 * @return string HTML
5041 */
5042 public function renderImageGallery( $text, $params ) {
5043 $mode = false;
5044 if ( isset( $params['mode'] ) ) {
5045 $mode = $params['mode'];
5046 }
5047
5048 try {
5049 $ig = ImageGalleryBase::factory( $mode );
5050 } catch ( Exception $e ) {
5051 // If invalid type set, fallback to default.
5052 $ig = ImageGalleryBase::factory( false );
5053 }
5054
5055 $ig->setContextTitle( $this->mTitle );
5056 $ig->setShowBytes( false );
5057 $ig->setShowDimensions( false );
5058 $ig->setShowFilename( false );
5059 $ig->setParser( $this );
5060 $ig->setHideBadImages();
5061 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'ul' ) );
5062
5063 if ( isset( $params['showfilename'] ) ) {
5064 $ig->setShowFilename( true );
5065 } else {
5066 $ig->setShowFilename( false );
5067 }
5068 if ( isset( $params['caption'] ) ) {
5069 // NOTE: We aren't passing a frame here or below. Frame info
5070 // is currently opaque to Parsoid, which acts on OT_PREPROCESS.
5071 // See T107332#4030581
5072 $caption = $this->recursiveTagParse( $params['caption'] );
5073 $ig->setCaptionHtml( $caption );
5074 }
5075 if ( isset( $params['perrow'] ) ) {
5076 $ig->setPerRow( $params['perrow'] );
5077 }
5078 if ( isset( $params['widths'] ) ) {
5079 $ig->setWidths( $params['widths'] );
5080 }
5081 if ( isset( $params['heights'] ) ) {
5082 $ig->setHeights( $params['heights'] );
5083 }
5084 $ig->setAdditionalOptions( $params );
5085
5086 // Avoid PHP 7.1 warning from passing $this by reference
5087 $parser = $this;
5088 Hooks::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5089
5090 $lines = StringUtils::explode( "\n", $text );
5091 foreach ( $lines as $line ) {
5092 # match lines like these:
5093 # Image:someimage.jpg|This is some image
5094 $matches = [];
5095 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5096 # Skip empty lines
5097 if ( count( $matches ) == 0 ) {
5098 continue;
5099 }
5100
5101 if ( strpos( $matches[0], '%' ) !== false ) {
5102 $matches[1] = rawurldecode( $matches[1] );
5103 }
5104 $title = Title::newFromText( $matches[1], NS_FILE );
5105 if ( is_null( $title ) ) {
5106 # Bogus title. Ignore these so we don't bomb out later.
5107 continue;
5108 }
5109
5110 # We need to get what handler the file uses, to figure out parameters.
5111 # Note, a hook can overide the file name, and chose an entirely different
5112 # file (which potentially could be of a different type and have different handler).
5113 $options = [];
5114 $descQuery = false;
5115 Hooks::run( 'BeforeParserFetchFileAndTitle',
5116 [ $this, $title, &$options, &$descQuery ] );
5117 # Don't register it now, as TraditionalImageGallery does that later.
5118 $file = $this->fetchFileNoRegister( $title, $options );
5119 $handler = $file ? $file->getHandler() : false;
5120
5121 $paramMap = [
5122 'img_alt' => 'gallery-internal-alt',
5123 'img_link' => 'gallery-internal-link',
5124 ];
5125 if ( $handler ) {
5126 $paramMap = $paramMap + $handler->getParamMap();
5127 // We don't want people to specify per-image widths.
5128 // Additionally the width parameter would need special casing anyhow.
5129 unset( $paramMap['img_width'] );
5130 }
5131
5132 $mwArray = $this->magicWordFactory->newArray( array_keys( $paramMap ) );
5133
5134 $label = '';
5135 $alt = '';
5136 $link = '';
5137 $handlerOptions = [];
5138 if ( isset( $matches[3] ) ) {
5139 // look for an |alt= definition while trying not to break existing
5140 // captions with multiple pipes (|) in it, until a more sensible grammar
5141 // is defined for images in galleries
5142
5143 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5144 // splitting on '|' is a bit odd, and different from makeImage.
5145 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5146 // Protect LanguageConverter markup
5147 $parameterMatches = StringUtils::delimiterExplode(
5148 '-{', '}-', '|', $matches[3], true /* nested */
5149 );
5150
5151 foreach ( $parameterMatches as $parameterMatch ) {
5152 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5153 if ( $magicName ) {
5154 $paramName = $paramMap[$magicName];
5155
5156 switch ( $paramName ) {
5157 case 'gallery-internal-alt':
5158 $alt = $this->stripAltText( $match, false );
5159 break;
5160 case 'gallery-internal-link':
5161 $linkValue = $this->stripAltText( $match, false );
5162 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5163 // Result of LanguageConverter::markNoConversion
5164 // invoked on an external link.
5165 $linkValue = substr( $linkValue, 4, -2 );
5166 }
5167 list( $type, $target ) = $this->parseLinkParameter( $linkValue );
5168 if ( $type === 'link-url' ) {
5169 $link = $target;
5170 $this->mOutput->addExternalLink( $target );
5171 } elseif ( $type === 'link-title' ) {
5172 $link = $target->getLinkURL();
5173 $this->mOutput->addLink( $target );
5174 }
5175 break;
5176 default:
5177 // Must be a handler specific parameter.
5178 if ( $handler->validateParam( $paramName, $match ) ) {
5179 $handlerOptions[$paramName] = $match;
5180 } else {
5181 // Guess not, consider it as caption.
5182 wfDebug( "$parameterMatch failed parameter validation\n" );
5183 $label = $parameterMatch;
5184 }
5185 }
5186
5187 } else {
5188 // Last pipe wins.
5189 $label = $parameterMatch;
5190 }
5191 }
5192 }
5193
5194 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5195 }
5196 $html = $ig->toHTML();
5197 Hooks::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5198 return $html;
5199 }
5200
5201 /**
5202 * @param MediaHandler $handler
5203 * @return array
5204 */
5205 public function getImageParams( $handler ) {
5206 if ( $handler ) {
5207 $handlerClass = get_class( $handler );
5208 } else {
5209 $handlerClass = '';
5210 }
5211 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5212 # Initialise static lists
5213 static $internalParamNames = [
5214 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5215 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5216 'bottom', 'text-bottom' ],
5217 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5218 'upright', 'border', 'link', 'alt', 'class' ],
5219 ];
5220 static $internalParamMap;
5221 if ( !$internalParamMap ) {
5222 $internalParamMap = [];
5223 foreach ( $internalParamNames as $type => $names ) {
5224 foreach ( $names as $name ) {
5225 // For grep: img_left, img_right, img_center, img_none,
5226 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5227 // img_bottom, img_text_bottom,
5228 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5229 // img_border, img_link, img_alt, img_class
5230 $magicName = str_replace( '-', '_', "img_$name" );
5231 $internalParamMap[$magicName] = [ $type, $name ];
5232 }
5233 }
5234 }
5235
5236 # Add handler params
5237 $paramMap = $internalParamMap;
5238 if ( $handler ) {
5239 $handlerParamMap = $handler->getParamMap();
5240 foreach ( $handlerParamMap as $magic => $paramName ) {
5241 $paramMap[$magic] = [ 'handler', $paramName ];
5242 }
5243 }
5244 $this->mImageParams[$handlerClass] = $paramMap;
5245 $this->mImageParamsMagicArray[$handlerClass] =
5246 $this->magicWordFactory->newArray( array_keys( $paramMap ) );
5247 }
5248 return [ $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ];
5249 }
5250
5251 /**
5252 * Parse image options text and use it to make an image
5253 *
5254 * @param Title $title
5255 * @param string $options
5256 * @param LinkHolderArray|bool $holders
5257 * @return string HTML
5258 */
5259 public function makeImage( $title, $options, $holders = false ) {
5260 # Check if the options text is of the form "options|alt text"
5261 # Options are:
5262 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5263 # * left no resizing, just left align. label is used for alt= only
5264 # * right same, but right aligned
5265 # * none same, but not aligned
5266 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5267 # * center center the image
5268 # * frame Keep original image size, no magnify-button.
5269 # * framed Same as "frame"
5270 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5271 # * upright reduce width for upright images, rounded to full __0 px
5272 # * border draw a 1px border around the image
5273 # * alt Text for HTML alt attribute (defaults to empty)
5274 # * class Set a class for img node
5275 # * link Set the target of the image link. Can be external, interwiki, or local
5276 # vertical-align values (no % or length right now):
5277 # * baseline
5278 # * sub
5279 # * super
5280 # * top
5281 # * text-top
5282 # * middle
5283 # * bottom
5284 # * text-bottom
5285
5286 global $wgMediaInTargetLanguage;
5287
5288 # Protect LanguageConverter markup when splitting into parts
5289 $parts = StringUtils::delimiterExplode(
5290 '-{', '}-', '|', $options, true /* allow nesting */
5291 );
5292
5293 # Give extensions a chance to select the file revision for us
5294 $options = [];
5295 $descQuery = false;
5296 Hooks::run( 'BeforeParserFetchFileAndTitle',
5297 [ $this, $title, &$options, &$descQuery ] );
5298 # Fetch and register the file (file title may be different via hooks)
5299 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5300
5301 # Get parameter map
5302 $handler = $file ? $file->getHandler() : false;
5303
5304 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5305
5306 if ( !$file ) {
5307 $this->addTrackingCategory( 'broken-file-category' );
5308 }
5309
5310 # Process the input parameters
5311 $caption = '';
5312 $params = [ 'frame' => [], 'handler' => [],
5313 'horizAlign' => [], 'vertAlign' => [] ];
5314 $seenformat = false;
5315 foreach ( $parts as $part ) {
5316 $part = trim( $part );
5317 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5318 $validated = false;
5319 if ( isset( $paramMap[$magicName] ) ) {
5320 list( $type, $paramName ) = $paramMap[$magicName];
5321
5322 # Special case; width and height come in one variable together
5323 if ( $type === 'handler' && $paramName === 'width' ) {
5324 $parsedWidthParam = self::parseWidthParam( $value );
5325 if ( isset( $parsedWidthParam['width'] ) ) {
5326 $width = $parsedWidthParam['width'];
5327 if ( $handler->validateParam( 'width', $width ) ) {
5328 $params[$type]['width'] = $width;
5329 $validated = true;
5330 }
5331 }
5332 if ( isset( $parsedWidthParam['height'] ) ) {
5333 $height = $parsedWidthParam['height'];
5334 if ( $handler->validateParam( 'height', $height ) ) {
5335 $params[$type]['height'] = $height;
5336 $validated = true;
5337 }
5338 }
5339 # else no validation -- T15436
5340 } else {
5341 if ( $type === 'handler' ) {
5342 # Validate handler parameter
5343 $validated = $handler->validateParam( $paramName, $value );
5344 } else {
5345 # Validate internal parameters
5346 switch ( $paramName ) {
5347 case 'manualthumb':
5348 case 'alt':
5349 case 'class':
5350 # @todo FIXME: Possibly check validity here for
5351 # manualthumb? downstream behavior seems odd with
5352 # missing manual thumbs.
5353 $validated = true;
5354 $value = $this->stripAltText( $value, $holders );
5355 break;
5356 case 'link':
5357 list( $paramName, $value ) =
5358 $this->parseLinkParameter(
5359 $this->stripAltText( $value, $holders )
5360 );
5361 if ( $paramName ) {
5362 $validated = true;
5363 if ( $paramName === 'no-link' ) {
5364 $value = true;
5365 }
5366 if ( $paramName === 'link-url' ) {
5367 if ( $this->mOptions->getExternalLinkTarget() ) {
5368 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5369 }
5370 }
5371 }
5372 break;
5373 case 'frameless':
5374 case 'framed':
5375 case 'thumbnail':
5376 // use first appearing option, discard others.
5377 $validated = !$seenformat;
5378 $seenformat = true;
5379 break;
5380 default:
5381 # Most other things appear to be empty or numeric...
5382 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5383 }
5384 }
5385
5386 if ( $validated ) {
5387 $params[$type][$paramName] = $value;
5388 }
5389 }
5390 }
5391 if ( !$validated ) {
5392 $caption = $part;
5393 }
5394 }
5395
5396 # Process alignment parameters
5397 if ( $params['horizAlign'] ) {
5398 $params['frame']['align'] = key( $params['horizAlign'] );
5399 }
5400 if ( $params['vertAlign'] ) {
5401 $params['frame']['valign'] = key( $params['vertAlign'] );
5402 }
5403
5404 $params['frame']['caption'] = $caption;
5405
5406 # Will the image be presented in a frame, with the caption below?
5407 $imageIsFramed = isset( $params['frame']['frame'] )
5408 || isset( $params['frame']['framed'] )
5409 || isset( $params['frame']['thumbnail'] )
5410 || isset( $params['frame']['manualthumb'] );
5411
5412 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5413 # came to also set the caption, ordinary text after the image -- which
5414 # makes no sense, because that just repeats the text multiple times in
5415 # screen readers. It *also* came to set the title attribute.
5416 # Now that we have an alt attribute, we should not set the alt text to
5417 # equal the caption: that's worse than useless, it just repeats the
5418 # text. This is the framed/thumbnail case. If there's no caption, we
5419 # use the unnamed parameter for alt text as well, just for the time be-
5420 # ing, if the unnamed param is set and the alt param is not.
5421 # For the future, we need to figure out if we want to tweak this more,
5422 # e.g., introducing a title= parameter for the title; ignoring the un-
5423 # named parameter entirely for images without a caption; adding an ex-
5424 # plicit caption= parameter and preserving the old magic unnamed para-
5425 # meter for BC; ...
5426 if ( $imageIsFramed ) { # Framed image
5427 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5428 # No caption or alt text, add the filename as the alt text so
5429 # that screen readers at least get some description of the image
5430 $params['frame']['alt'] = $title->getText();
5431 }
5432 # Do not set $params['frame']['title'] because tooltips don't make sense
5433 # for framed images
5434 } else { # Inline image
5435 if ( !isset( $params['frame']['alt'] ) ) {
5436 # No alt text, use the "caption" for the alt text
5437 if ( $caption !== '' ) {
5438 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5439 } else {
5440 # No caption, fall back to using the filename for the
5441 # alt text
5442 $params['frame']['alt'] = $title->getText();
5443 }
5444 }
5445 # Use the "caption" for the tooltip text
5446 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5447 }
5448 if ( $wgMediaInTargetLanguage ) {
5449 $params['handler']['targetlang'] = $this->getTargetLanguage()->getCode();
5450 }
5451
5452 Hooks::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5453
5454 # Linker does the rest
5455 $time = $options['time'] ?? false;
5456 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5457 $time, $descQuery, $this->mOptions->getThumbSize() );
5458
5459 # Give the handler a chance to modify the parser object
5460 if ( $handler ) {
5461 $handler->parserTransformHook( $this, $file );
5462 }
5463
5464 return $ret;
5465 }
5466
5467 /**
5468 * Parse the value of 'link' parameter in image syntax (`[[File:Foo.jpg|link=<value>]]`).
5469 *
5470 * Adds an entry to appropriate link tables.
5471 *
5472 * @since 1.32
5473 * @return array of `[ type, target ]`, where:
5474 * - `type` is one of:
5475 * - `null`: Given value is not a valid link target, use default
5476 * - `'no-link'`: Given value is empty, do not generate a link
5477 * - `'link-url'`: Given value is a valid external link
5478 * - `'link-title'`: Given value is a valid internal link
5479 * - `target` is:
5480 * - When `type` is `null` or `'no-link'`: `false`
5481 * - When `type` is `'link-url'`: URL string corresponding to given value
5482 * - When `type` is `'link-title'`: Title object corresponding to given value
5483 */
5484 public function parseLinkParameter( $value ) {
5485 $chars = self::EXT_LINK_URL_CLASS;
5486 $addr = self::EXT_LINK_ADDR;
5487 $prots = $this->mUrlProtocols;
5488 $type = null;
5489 $target = false;
5490 if ( $value === '' ) {
5491 $type = 'no-link';
5492 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5493 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5494 $this->mOutput->addExternalLink( $value );
5495 $type = 'link-url';
5496 $target = $value;
5497 }
5498 } else {
5499 $linkTitle = Title::newFromText( $value );
5500 if ( $linkTitle ) {
5501 $this->mOutput->addLink( $linkTitle );
5502 $type = 'link-title';
5503 $target = $linkTitle;
5504 }
5505 }
5506 return [ $type, $target ];
5507 }
5508
5509 /**
5510 * @param string $caption
5511 * @param LinkHolderArray|bool $holders
5512 * @return mixed|string
5513 */
5514 protected function stripAltText( $caption, $holders ) {
5515 # Strip bad stuff out of the title (tooltip). We can't just use
5516 # replaceLinkHoldersText() here, because if this function is called
5517 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5518 if ( $holders ) {
5519 $tooltip = $holders->replaceText( $caption );
5520 } else {
5521 $tooltip = $this->replaceLinkHoldersText( $caption );
5522 }
5523
5524 # make sure there are no placeholders in thumbnail attributes
5525 # that are later expanded to html- so expand them now and
5526 # remove the tags
5527 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5528 # Compatibility hack! In HTML certain entity references not terminated
5529 # by a semicolon are decoded (but not if we're in an attribute; that's
5530 # how link URLs get away without properly escaping & in queries).
5531 # But wikitext has always required semicolon-termination of entities,
5532 # so encode & where needed to avoid decode of semicolon-less entities.
5533 # See T209236 and
5534 # https://www.w3.org/TR/html5/syntax.html#named-character-references
5535 # T210437 discusses moving this workaround to Sanitizer::stripAllTags.
5536 $tooltip = preg_replace( "/
5537 & # 1. entity prefix
5538 (?= # 2. followed by:
5539 (?: # a. one of the legacy semicolon-less named entities
5540 A(?:Elig|MP|acute|circ|grave|ring|tilde|uml)|
5541 C(?:OPY|cedil)|E(?:TH|acute|circ|grave|uml)|
5542 GT|I(?:acute|circ|grave|uml)|LT|Ntilde|
5543 O(?:acute|circ|grave|slash|tilde|uml)|QUOT|REG|THORN|
5544 U(?:acute|circ|grave|uml)|Yacute|
5545 a(?:acute|c(?:irc|ute)|elig|grave|mp|ring|tilde|uml)|brvbar|
5546 c(?:cedil|edil|urren)|cent(?!erdot;)|copy(?!sr;)|deg|
5547 divide(?!ontimes;)|e(?:acute|circ|grave|th|uml)|
5548 frac(?:1(?:2|4)|34)|
5549 gt(?!c(?:c|ir)|dot|lPar|quest|r(?:a(?:pprox|rr)|dot|eq(?:less|qless)|less|sim);)|
5550 i(?:acute|circ|excl|grave|quest|uml)|laquo|
5551 lt(?!c(?:c|ir)|dot|hree|imes|larr|quest|r(?:Par|i(?:e|f|));)|
5552 m(?:acr|i(?:cro|ddot))|n(?:bsp|tilde)|
5553 not(?!in(?:E|dot|v(?:a|b|c)|)|ni(?:v(?:a|b|c)|);)|
5554 o(?:acute|circ|grave|rd(?:f|m)|slash|tilde|uml)|
5555 p(?:lusmn|ound)|para(?!llel;)|quot|r(?:aquo|eg)|
5556 s(?:ect|hy|up(?:1|2|3)|zlig)|thorn|times(?!b(?:ar|)|d;)|
5557 u(?:acute|circ|grave|ml|uml)|y(?:acute|en|uml)
5558 )
5559 (?:[^;]|$)) # b. and not followed by a semicolon
5560 # S = study, for efficiency
5561 /Sx", '&amp;', $tooltip );
5562 $tooltip = Sanitizer::stripAllTags( $tooltip );
5563
5564 return $tooltip;
5565 }
5566
5567 /**
5568 * Set a flag in the output object indicating that the content is dynamic and
5569 * shouldn't be cached.
5570 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5571 */
5572 public function disableCache() {
5573 wfDebug( "Parser output marked as uncacheable.\n" );
5574 if ( !$this->mOutput ) {
5575 throw new MWException( __METHOD__ .
5576 " can only be called when actually parsing something" );
5577 }
5578 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5579 }
5580
5581 /**
5582 * Callback from the Sanitizer for expanding items found in HTML attribute
5583 * values, so they can be safely tested and escaped.
5584 *
5585 * @param string &$text
5586 * @param bool|PPFrame $frame
5587 * @return string
5588 */
5589 public function attributeStripCallback( &$text, $frame = false ) {
5590 $text = $this->replaceVariables( $text, $frame );
5591 $text = $this->mStripState->unstripBoth( $text );
5592 return $text;
5593 }
5594
5595 /**
5596 * Accessor
5597 *
5598 * @return array
5599 */
5600 public function getTags() {
5601 $this->firstCallInit();
5602 return array_merge(
5603 array_keys( $this->mTransparentTagHooks ),
5604 array_keys( $this->mTagHooks ),
5605 array_keys( $this->mFunctionTagHooks )
5606 );
5607 }
5608
5609 /**
5610 * @since 1.32
5611 * @return array
5612 */
5613 public function getFunctionSynonyms() {
5614 $this->firstCallInit();
5615 return $this->mFunctionSynonyms;
5616 }
5617
5618 /**
5619 * @since 1.32
5620 * @return string
5621 */
5622 public function getUrlProtocols() {
5623 return $this->mUrlProtocols;
5624 }
5625
5626 /**
5627 * Replace transparent tags in $text with the values given by the callbacks.
5628 *
5629 * Transparent tag hooks are like regular XML-style tag hooks, except they
5630 * operate late in the transformation sequence, on HTML instead of wikitext.
5631 *
5632 * @param string $text
5633 *
5634 * @return string
5635 */
5636 public function replaceTransparentTags( $text ) {
5637 $matches = [];
5638 $elements = array_keys( $this->mTransparentTagHooks );
5639 $text = self::extractTagsAndParams( $elements, $text, $matches );
5640 $replacements = [];
5641
5642 foreach ( $matches as $marker => $data ) {
5643 list( $element, $content, $params, $tag ) = $data;
5644 $tagName = strtolower( $element );
5645 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5646 $output = call_user_func_array(
5647 $this->mTransparentTagHooks[$tagName],
5648 [ $content, $params, $this ]
5649 );
5650 } else {
5651 $output = $tag;
5652 }
5653 $replacements[$marker] = $output;
5654 }
5655 return strtr( $text, $replacements );
5656 }
5657
5658 /**
5659 * Break wikitext input into sections, and either pull or replace
5660 * some particular section's text.
5661 *
5662 * External callers should use the getSection and replaceSection methods.
5663 *
5664 * @param string $text Page wikitext
5665 * @param string|int $sectionId A section identifier string of the form:
5666 * "<flag1> - <flag2> - ... - <section number>"
5667 *
5668 * Currently the only recognised flag is "T", which means the target section number
5669 * was derived during a template inclusion parse, in other words this is a template
5670 * section edit link. If no flags are given, it was an ordinary section edit link.
5671 * This flag is required to avoid a section numbering mismatch when a section is
5672 * enclosed by "<includeonly>" (T8563).
5673 *
5674 * The section number 0 pulls the text before the first heading; other numbers will
5675 * pull the given section along with its lower-level subsections. If the section is
5676 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5677 *
5678 * Section 0 is always considered to exist, even if it only contains the empty
5679 * string. If $text is the empty string and section 0 is replaced, $newText is
5680 * returned.
5681 *
5682 * @param string $mode One of "get" or "replace"
5683 * @param string $newText Replacement text for section data.
5684 * @return string For "get", the extracted section text.
5685 * for "replace", the whole page with the section replaced.
5686 */
5687 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5688 global $wgTitle; # not generally used but removes an ugly failure mode
5689
5690 $magicScopeVariable = $this->lock();
5691 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5692 $outText = '';
5693 $frame = $this->getPreprocessor()->newFrame();
5694
5695 # Process section extraction flags
5696 $flags = 0;
5697 $sectionParts = explode( '-', $sectionId );
5698 $sectionIndex = array_pop( $sectionParts );
5699 foreach ( $sectionParts as $part ) {
5700 if ( $part === 'T' ) {
5701 $flags |= self::PTD_FOR_INCLUSION;
5702 }
5703 }
5704
5705 # Check for empty input
5706 if ( strval( $text ) === '' ) {
5707 # Only sections 0 and T-0 exist in an empty document
5708 if ( $sectionIndex == 0 ) {
5709 if ( $mode === 'get' ) {
5710 return '';
5711 } else {
5712 return $newText;
5713 }
5714 } else {
5715 if ( $mode === 'get' ) {
5716 return $newText;
5717 } else {
5718 return $text;
5719 }
5720 }
5721 }
5722
5723 # Preprocess the text
5724 $root = $this->preprocessToDom( $text, $flags );
5725
5726 # <h> nodes indicate section breaks
5727 # They can only occur at the top level, so we can find them by iterating the root's children
5728 $node = $root->getFirstChild();
5729
5730 # Find the target section
5731 if ( $sectionIndex == 0 ) {
5732 # Section zero doesn't nest, level=big
5733 $targetLevel = 1000;
5734 } else {
5735 while ( $node ) {
5736 if ( $node->getName() === 'h' ) {
5737 $bits = $node->splitHeading();
5738 if ( $bits['i'] == $sectionIndex ) {
5739 $targetLevel = $bits['level'];
5740 break;
5741 }
5742 }
5743 if ( $mode === 'replace' ) {
5744 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5745 }
5746 $node = $node->getNextSibling();
5747 }
5748 }
5749
5750 if ( !$node ) {
5751 # Not found
5752 if ( $mode === 'get' ) {
5753 return $newText;
5754 } else {
5755 return $text;
5756 }
5757 }
5758
5759 # Find the end of the section, including nested sections
5760 do {
5761 if ( $node->getName() === 'h' ) {
5762 $bits = $node->splitHeading();
5763 $curLevel = $bits['level'];
5764 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5765 break;
5766 }
5767 }
5768 if ( $mode === 'get' ) {
5769 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5770 }
5771 $node = $node->getNextSibling();
5772 } while ( $node );
5773
5774 # Write out the remainder (in replace mode only)
5775 if ( $mode === 'replace' ) {
5776 # Output the replacement text
5777 # Add two newlines on -- trailing whitespace in $newText is conventionally
5778 # stripped by the editor, so we need both newlines to restore the paragraph gap
5779 # Only add trailing whitespace if there is newText
5780 if ( $newText != "" ) {
5781 $outText .= $newText . "\n\n";
5782 }
5783
5784 while ( $node ) {
5785 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5786 $node = $node->getNextSibling();
5787 }
5788 }
5789
5790 if ( is_string( $outText ) ) {
5791 # Re-insert stripped tags
5792 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5793 }
5794
5795 return $outText;
5796 }
5797
5798 /**
5799 * This function returns the text of a section, specified by a number ($section).
5800 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5801 * the first section before any such heading (section 0).
5802 *
5803 * If a section contains subsections, these are also returned.
5804 *
5805 * @param string $text Text to look in
5806 * @param string|int $sectionId Section identifier as a number or string
5807 * (e.g. 0, 1 or 'T-1').
5808 * @param string $defaultText Default to return if section is not found
5809 *
5810 * @return string Text of the requested section
5811 */
5812 public function getSection( $text, $sectionId, $defaultText = '' ) {
5813 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5814 }
5815
5816 /**
5817 * This function returns $oldtext after the content of the section
5818 * specified by $section has been replaced with $text. If the target
5819 * section does not exist, $oldtext is returned unchanged.
5820 *
5821 * @param string $oldText Former text of the article
5822 * @param string|int $sectionId Section identifier as a number or string
5823 * (e.g. 0, 1 or 'T-1').
5824 * @param string $newText Replacing text
5825 *
5826 * @return string Modified text
5827 */
5828 public function replaceSection( $oldText, $sectionId, $newText ) {
5829 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5830 }
5831
5832 /**
5833 * Get the ID of the revision we are parsing
5834 *
5835 * @return int|null
5836 */
5837 public function getRevisionId() {
5838 return $this->mRevisionId;
5839 }
5840
5841 /**
5842 * Get the revision object for $this->mRevisionId
5843 *
5844 * @return Revision|null Either a Revision object or null
5845 * @since 1.23 (public since 1.23)
5846 */
5847 public function getRevisionObject() {
5848 if ( !is_null( $this->mRevisionObject ) ) {
5849 return $this->mRevisionObject;
5850 }
5851
5852 // NOTE: try to get the RevisionObject even if mRevisionId is null.
5853 // This is useful when parsing revision that has not yet been saved.
5854 // However, if we get back a saved revision even though we are in
5855 // preview mode, we'll have to ignore it, see below.
5856 // NOTE: This callback may be used to inject an OLD revision that was
5857 // already loaded, so "current" is a bit of a misnomer. We can't just
5858 // skip it if mRevisionId is set.
5859 $rev = call_user_func(
5860 $this->mOptions->getCurrentRevisionCallback(), $this->getTitle(), $this
5861 );
5862
5863 if ( $this->mRevisionId === null && $rev && $rev->getId() ) {
5864 // We are in preview mode (mRevisionId is null), and the current revision callback
5865 // returned an existing revision. Ignore it and return null, it's probably the page's
5866 // current revision, which is not what we want here. Note that we do want to call the
5867 // callback to allow the unsaved revision to be injected here, e.g. for
5868 // self-transclusion previews.
5869 return null;
5870 }
5871
5872 // If the parse is for a new revision, then the callback should have
5873 // already been set to force the object and should match mRevisionId.
5874 // If not, try to fetch by mRevisionId for sanity.
5875 if ( $this->mRevisionId && $rev && $rev->getId() != $this->mRevisionId ) {
5876 $rev = Revision::newFromId( $this->mRevisionId );
5877 }
5878
5879 $this->mRevisionObject = $rev;
5880
5881 return $this->mRevisionObject;
5882 }
5883
5884 /**
5885 * Get the timestamp associated with the current revision, adjusted for
5886 * the default server-local timestamp
5887 * @return string
5888 */
5889 public function getRevisionTimestamp() {
5890 if ( is_null( $this->mRevisionTimestamp ) ) {
5891 $revObject = $this->getRevisionObject();
5892 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5893
5894 # The cryptic '' timezone parameter tells to use the site-default
5895 # timezone offset instead of the user settings.
5896 # Since this value will be saved into the parser cache, served
5897 # to other users, and potentially even used inside links and such,
5898 # it needs to be consistent for all visitors.
5899 $this->mRevisionTimestamp = $this->contLang->userAdjust( $timestamp, '' );
5900 }
5901 return $this->mRevisionTimestamp;
5902 }
5903
5904 /**
5905 * Get the name of the user that edited the last revision
5906 *
5907 * @return string User name
5908 */
5909 public function getRevisionUser() {
5910 if ( is_null( $this->mRevisionUser ) ) {
5911 $revObject = $this->getRevisionObject();
5912
5913 # if this template is subst: the revision id will be blank,
5914 # so just use the current user's name
5915 if ( $revObject ) {
5916 $this->mRevisionUser = $revObject->getUserText();
5917 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5918 $this->mRevisionUser = $this->getUser()->getName();
5919 }
5920 }
5921 return $this->mRevisionUser;
5922 }
5923
5924 /**
5925 * Get the size of the revision
5926 *
5927 * @return int|null Revision size
5928 */
5929 public function getRevisionSize() {
5930 if ( is_null( $this->mRevisionSize ) ) {
5931 $revObject = $this->getRevisionObject();
5932
5933 # if this variable is subst: the revision id will be blank,
5934 # so just use the parser input size, because the own substituation
5935 # will change the size.
5936 if ( $revObject ) {
5937 $this->mRevisionSize = $revObject->getSize();
5938 } else {
5939 $this->mRevisionSize = $this->mInputSize;
5940 }
5941 }
5942 return $this->mRevisionSize;
5943 }
5944
5945 /**
5946 * Mutator for $mDefaultSort
5947 *
5948 * @param string $sort New value
5949 */
5950 public function setDefaultSort( $sort ) {
5951 $this->mDefaultSort = $sort;
5952 $this->mOutput->setProperty( 'defaultsort', $sort );
5953 }
5954
5955 /**
5956 * Accessor for $mDefaultSort
5957 * Will use the empty string if none is set.
5958 *
5959 * This value is treated as a prefix, so the
5960 * empty string is equivalent to sorting by
5961 * page name.
5962 *
5963 * @return string
5964 */
5965 public function getDefaultSort() {
5966 if ( $this->mDefaultSort !== false ) {
5967 return $this->mDefaultSort;
5968 } else {
5969 return '';
5970 }
5971 }
5972
5973 /**
5974 * Accessor for $mDefaultSort
5975 * Unlike getDefaultSort(), will return false if none is set
5976 *
5977 * @return string|bool
5978 */
5979 public function getCustomDefaultSort() {
5980 return $this->mDefaultSort;
5981 }
5982
5983 private static function getSectionNameFromStrippedText( $text ) {
5984 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5985 $text = Sanitizer::decodeCharReferences( $text );
5986 $text = self::normalizeSectionName( $text );
5987 return $text;
5988 }
5989
5990 private static function makeAnchor( $sectionName ) {
5991 return '#' . Sanitizer::escapeIdForLink( $sectionName );
5992 }
5993
5994 private function makeLegacyAnchor( $sectionName ) {
5995 $fragmentMode = $this->siteConfig->get( 'FragmentMode' );
5996 if ( isset( $fragmentMode[1] ) && $fragmentMode[1] === 'legacy' ) {
5997 // ForAttribute() and ForLink() are the same for legacy encoding
5998 $id = Sanitizer::escapeIdForAttribute( $sectionName, Sanitizer::ID_FALLBACK );
5999 } else {
6000 $id = Sanitizer::escapeIdForLink( $sectionName );
6001 }
6002
6003 return "#$id";
6004 }
6005
6006 /**
6007 * Try to guess the section anchor name based on a wikitext fragment
6008 * presumably extracted from a heading, for example "Header" from
6009 * "== Header ==".
6010 *
6011 * @param string $text
6012 * @return string Anchor (starting with '#')
6013 */
6014 public function guessSectionNameFromWikiText( $text ) {
6015 # Strip out wikitext links(they break the anchor)
6016 $text = $this->stripSectionName( $text );
6017 $sectionName = self::getSectionNameFromStrippedText( $text );
6018 return self::makeAnchor( $sectionName );
6019 }
6020
6021 /**
6022 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6023 * instead, if possible. For use in redirects, since various versions
6024 * of Microsoft browsers interpret Location: headers as something other
6025 * than UTF-8, resulting in breakage.
6026 *
6027 * @param string $text The section name
6028 * @return string Anchor (starting with '#')
6029 */
6030 public function guessLegacySectionNameFromWikiText( $text ) {
6031 # Strip out wikitext links(they break the anchor)
6032 $text = $this->stripSectionName( $text );
6033 $sectionName = self::getSectionNameFromStrippedText( $text );
6034 return $this->makeLegacyAnchor( $sectionName );
6035 }
6036
6037 /**
6038 * Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
6039 * @param string $text Section name (plain text)
6040 * @return string Anchor (starting with '#')
6041 */
6042 public static function guessSectionNameFromStrippedText( $text ) {
6043 $sectionName = self::getSectionNameFromStrippedText( $text );
6044 return self::makeAnchor( $sectionName );
6045 }
6046
6047 /**
6048 * Apply the same normalization as code making links to this section would
6049 *
6050 * @param string $text
6051 * @return string
6052 */
6053 private static function normalizeSectionName( $text ) {
6054 # T90902: ensure the same normalization is applied for IDs as to links
6055 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
6056 try {
6057
6058 $parts = $titleParser->splitTitleString( "#$text" );
6059 } catch ( MalformedTitleException $ex ) {
6060 return $text;
6061 }
6062 return $parts['fragment'];
6063 }
6064
6065 /**
6066 * Strips a text string of wikitext for use in a section anchor
6067 *
6068 * Accepts a text string and then removes all wikitext from the
6069 * string and leaves only the resultant text (i.e. the result of
6070 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6071 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6072 * to create valid section anchors by mimicing the output of the
6073 * parser when headings are parsed.
6074 *
6075 * @param string $text Text string to be stripped of wikitext
6076 * for use in a Section anchor
6077 * @return string Filtered text string
6078 */
6079 public function stripSectionName( $text ) {
6080 # Strip internal link markup
6081 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6082 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6083
6084 # Strip external link markup
6085 # @todo FIXME: Not tolerant to blank link text
6086 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6087 # on how many empty links there are on the page - need to figure that out.
6088 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6089
6090 # Parse wikitext quotes (italics & bold)
6091 $text = $this->doQuotes( $text );
6092
6093 # Strip HTML tags
6094 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
6095 return $text;
6096 }
6097
6098 /**
6099 * strip/replaceVariables/unstrip for preprocessor regression testing
6100 *
6101 * @param string $text
6102 * @param Title $title
6103 * @param ParserOptions $options
6104 * @param int $outputType
6105 *
6106 * @return string
6107 */
6108 public function testSrvus( $text, Title $title, ParserOptions $options,
6109 $outputType = self::OT_HTML
6110 ) {
6111 $magicScopeVariable = $this->lock();
6112 $this->startParse( $title, $options, $outputType, true );
6113
6114 $text = $this->replaceVariables( $text );
6115 $text = $this->mStripState->unstripBoth( $text );
6116 $text = Sanitizer::removeHTMLtags( $text );
6117 return $text;
6118 }
6119
6120 /**
6121 * @param string $text
6122 * @param Title $title
6123 * @param ParserOptions $options
6124 * @return string
6125 */
6126 public function testPst( $text, Title $title, ParserOptions $options ) {
6127 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6128 }
6129
6130 /**
6131 * @param string $text
6132 * @param Title $title
6133 * @param ParserOptions $options
6134 * @return string
6135 */
6136 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
6137 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
6138 }
6139
6140 /**
6141 * Call a callback function on all regions of the given text that are not
6142 * inside strip markers, and replace those regions with the return value
6143 * of the callback. For example, with input:
6144 *
6145 * aaa<MARKER>bbb
6146 *
6147 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6148 * two strings will be replaced with the value returned by the callback in
6149 * each case.
6150 *
6151 * @param string $s
6152 * @param callable $callback
6153 *
6154 * @return string
6155 */
6156 public function markerSkipCallback( $s, $callback ) {
6157 $i = 0;
6158 $out = '';
6159 while ( $i < strlen( $s ) ) {
6160 $markerStart = strpos( $s, self::MARKER_PREFIX, $i );
6161 if ( $markerStart === false ) {
6162 $out .= call_user_func( $callback, substr( $s, $i ) );
6163 break;
6164 } else {
6165 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6166 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
6167 if ( $markerEnd === false ) {
6168 $out .= substr( $s, $markerStart );
6169 break;
6170 } else {
6171 $markerEnd += strlen( self::MARKER_SUFFIX );
6172 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6173 $i = $markerEnd;
6174 }
6175 }
6176 }
6177 return $out;
6178 }
6179
6180 /**
6181 * Remove any strip markers found in the given text.
6182 *
6183 * @param string $text
6184 * @return string
6185 */
6186 public function killMarkers( $text ) {
6187 return $this->mStripState->killMarkers( $text );
6188 }
6189
6190 /**
6191 * Save the parser state required to convert the given half-parsed text to
6192 * HTML. "Half-parsed" in this context means the output of
6193 * recursiveTagParse() or internalParse(). This output has strip markers
6194 * from replaceVariables (extensionSubstitution() etc.), and link
6195 * placeholders from replaceLinkHolders().
6196 *
6197 * Returns an array which can be serialized and stored persistently. This
6198 * array can later be loaded into another parser instance with
6199 * unserializeHalfParsedText(). The text can then be safely incorporated into
6200 * the return value of a parser hook.
6201 *
6202 * @deprecated since 1.31
6203 * @param string $text
6204 *
6205 * @return array
6206 */
6207 public function serializeHalfParsedText( $text ) {
6208 wfDeprecated( __METHOD__, '1.31' );
6209 $data = [
6210 'text' => $text,
6211 'version' => self::HALF_PARSED_VERSION,
6212 'stripState' => $this->mStripState->getSubState( $text ),
6213 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6214 ];
6215 return $data;
6216 }
6217
6218 /**
6219 * Load the parser state given in the $data array, which is assumed to
6220 * have been generated by serializeHalfParsedText(). The text contents is
6221 * extracted from the array, and its markers are transformed into markers
6222 * appropriate for the current Parser instance. This transformed text is
6223 * returned, and can be safely included in the return value of a parser
6224 * hook.
6225 *
6226 * If the $data array has been stored persistently, the caller should first
6227 * check whether it is still valid, by calling isValidHalfParsedText().
6228 *
6229 * @deprecated since 1.31
6230 * @param array $data Serialized data
6231 * @throws MWException
6232 * @return string
6233 */
6234 public function unserializeHalfParsedText( $data ) {
6235 wfDeprecated( __METHOD__, '1.31' );
6236 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6237 throw new MWException( __METHOD__ . ': invalid version' );
6238 }
6239
6240 # First, extract the strip state.
6241 $texts = [ $data['text'] ];
6242 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6243
6244 # Now renumber links
6245 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6246
6247 # Should be good to go.
6248 return $texts[0];
6249 }
6250
6251 /**
6252 * Returns true if the given array, presumed to be generated by
6253 * serializeHalfParsedText(), is compatible with the current version of the
6254 * parser.
6255 *
6256 * @deprecated since 1.31
6257 * @param array $data
6258 *
6259 * @return bool
6260 */
6261 public function isValidHalfParsedText( $data ) {
6262 wfDeprecated( __METHOD__, '1.31' );
6263 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6264 }
6265
6266 /**
6267 * Parsed a width param of imagelink like 300px or 200x300px
6268 *
6269 * @param string $value
6270 * @param bool $parseHeight
6271 *
6272 * @return array
6273 * @since 1.20
6274 */
6275 public static function parseWidthParam( $value, $parseHeight = true ) {
6276 $parsedWidthParam = [];
6277 if ( $value === '' ) {
6278 return $parsedWidthParam;
6279 }
6280 $m = [];
6281 # (T15500) In both cases (width/height and width only),
6282 # permit trailing "px" for backward compatibility.
6283 if ( $parseHeight && preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6284 $width = intval( $m[1] );
6285 $height = intval( $m[2] );
6286 $parsedWidthParam['width'] = $width;
6287 $parsedWidthParam['height'] = $height;
6288 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6289 $width = intval( $value );
6290 $parsedWidthParam['width'] = $width;
6291 }
6292 return $parsedWidthParam;
6293 }
6294
6295 /**
6296 * Lock the current instance of the parser.
6297 *
6298 * This is meant to stop someone from calling the parser
6299 * recursively and messing up all the strip state.
6300 *
6301 * @throws MWException If parser is in a parse
6302 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6303 */
6304 protected function lock() {
6305 if ( $this->mInParse ) {
6306 throw new MWException( "Parser state cleared while parsing. "
6307 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse );
6308 }
6309
6310 // Save the backtrace when locking, so that if some code tries locking again,
6311 // we can print the lock owner's backtrace for easier debugging
6312 $e = new Exception;
6313 $this->mInParse = $e->getTraceAsString();
6314
6315 $recursiveCheck = new ScopedCallback( function () {
6316 $this->mInParse = false;
6317 } );
6318
6319 return $recursiveCheck;
6320 }
6321
6322 /**
6323 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6324 *
6325 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6326 * or if there is more than one <p/> tag in the input HTML.
6327 *
6328 * @param string $html
6329 * @return string
6330 * @since 1.24
6331 */
6332 public static function stripOuterParagraph( $html ) {
6333 $m = [];
6334 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6335 if ( strpos( $m[1], '</p>' ) === false ) {
6336 $html = $m[1];
6337 }
6338 }
6339
6340 return $html;
6341 }
6342
6343 /**
6344 * Return this parser if it is not doing anything, otherwise
6345 * get a fresh parser. You can use this method by doing
6346 * $myParser = $wgParser->getFreshParser(), or more simply
6347 * $wgParser->getFreshParser()->parse( ... );
6348 * if you're unsure if $wgParser is safe to use.
6349 *
6350 * @since 1.24
6351 * @return Parser A parser object that is not parsing anything
6352 */
6353 public function getFreshParser() {
6354 if ( $this->mInParse ) {
6355 return $this->factory->create();
6356 } else {
6357 return $this;
6358 }
6359 }
6360
6361 /**
6362 * Set's up the PHP implementation of OOUI for use in this request
6363 * and instructs OutputPage to enable OOUI for itself.
6364 *
6365 * @since 1.26
6366 */
6367 public function enableOOUI() {
6368 OutputPage::setupOOUI();
6369 $this->mOutput->setEnableOOUI( true );
6370 }
6371 }