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