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