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