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