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