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