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