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