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