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