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