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