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