Debian Codegraph @

includes/parser/Parser.php

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