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