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