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