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