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