Debian Codegraph @

includes/parser/ParserOutput.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Parser;
22
23 use InvalidArgumentException;
24 use LogicException;
25 use MediaWiki\Edit\ParsoidRenderID;
26 use MediaWiki\Json\JsonDeserializable;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Message\Converter;
30 use MediaWiki\Output\OutputPage;
31 use MediaWiki\Parser\Parsoid\PageBundleParserOutputConverter;
32 use MediaWiki\Title\TitleValue;
33 use UnexpectedValueException;
34 use Wikimedia\Bcp47Code\Bcp47Code;
35 use Wikimedia\Bcp47Code\Bcp47CodeValue;
36 use Wikimedia\JsonCodec\Hint;
37 use Wikimedia\Message\MessageValue;
38 use Wikimedia\Parsoid\Core\ContentMetadataCollector;
39 use Wikimedia\Parsoid\Core\ContentMetadataCollectorCompat;
40 use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
41 use Wikimedia\Parsoid\Core\TOCData;
42 use Wikimedia\Reflection\GhostFieldAccessTrait;
43
44 /**
45 * ParserOutput is a rendering of a Content object or a message.
46 * Content objects and messages often contain wikitext, but not always.
47 *
48 * `ParserOutput` object combine the HTML rendering of Content objects
49 * or messages, available via `::getRawText()`, with various bits of
50 * metadata generated during rendering, which may include categories,
51 * links, page properties, and extension data, among others.
52 *
53 * `ParserOutput` objects corresponding to the content of page revisions
54 * are created by the `ParserOutputAccess` service, which
55 * automatically caches them via `ParserCache` where appropriate and
56 * produces new output via `ContentHandler` as needed.
57 *
58 * In addition, wikitext from system messages as well as odd bits of
59 * wikitext rendered to create special pages and other UX elements are
60 * rendered to `ParserOutput` objects. In these cases the metadata
61 * from the `ParserOutput` is generally discarded and the
62 * `ParserOutput` is not cached. These bits of wikitext are generally
63 * rendered with `ParserOptions::setInterfaceMessage(true)` when
64 * content is intended to be in the user interface language, but
65 * sometimes rendered to the content language and displayed in the
66 * content area instead.
67 *
68 * A `ParserOutput` object corresponding to a given revision may be a
69 * combination of the renderings of multiple "slots":
70 * the Multi-Content Revisions (MCR) work allows articles to be
71 * composed from multiple `Content` objects. Each `Content` renders
72 * to a `ParserOutput`, and those `ParserOutput`s are merged by
73 * `RevisionRenderer::combineSlotOutput()` to create the final article
74 * output.
75 *
76 * Similarly, `OutputPage` maintains metadata overlapping
77 * with the metadata kept by `ParserOutput` (T301020) and may merge
78 * several `ParserOutput`s using `OutputPage::addParserOutput()` to
79 * create the final output page. Parsoid parses certain transclusions
80 * in independent top-level contexts using
81 * `Parser::parseExtensionTagAsTopLevelDoc()` and these also result in
82 * `ParserOutput`s which are merged via
83 * `ParserOutput::collectMetadata()`.
84 *
85 * Future plans for incremental parsing and asynchronous rendering may
86 * result in several of these component `ParserOutput` objects being
87 * cached independently and then recombined asynchronously, so
88 * operations on `ParserOutput` objects should be compatible with that
89 * model (T300979).
90 *
91 * @ingroup Parser
92 */
93 class ParserOutput extends CacheTime implements ContentMetadataCollector {
94 use GhostFieldAccessTrait;
95 // This is used to break cyclic dependencies and allow a measure
96 // of compatibility when new methods are added to ContentMetadataCollector
97 // by Parsoid.
98 use ContentMetadataCollectorCompat;
99
100 /**
101 * Feature flags to indicate to extensions that MediaWiki core supports and
102 * uses getText() stateless transforms.
103 *
104 * @since 1.31
105 */
106 public const SUPPORTS_STATELESS_TRANSFORMS = 1;
107
108 /**
109 * @since 1.31
110 */
111 public const SUPPORTS_UNWRAP_TRANSFORM = 1;
112
113 /**
114 * @internal
115 * @since 1.38
116 */
117 public const MW_MERGE_STRATEGY_KEY = '_mw-strategy';
118
119 /**
120 * Merge strategy to use for ParserOutput accumulators: "union"
121 * means that values are strings, stored as a set, and exposed as
122 * a PHP associative array mapping from values to `true`.
123 *
124 * This constant should be treated as @internal until we expose
125 * alternative merge strategies for external use.
126 * @internal
127 * @since 1.38
128 */
129 public const MW_MERGE_STRATEGY_UNION = 'union';
130
131 /**
132 * @var string|null The output text
133 */
134 private $mRawText = null;
135
136 /**
137 * @var array<string,string> Array mapping interwiki prefix to (non DB key) Titles (e.g. 'fr' => 'Test page')
138 */
139 private $mLanguageLinkMap = [];
140
141 /**
142 * @var array<string,string> Map of category names to sort keys
143 */
144 private $mCategories;
145
146 /**
147 * @var array<string,string> Page status indicators, usually displayed in top-right corner.
148 */
149 private $mIndicators = [];
150
151 /**
152 * @var string Title text of the chosen language variant, as HTML.
153 */
154 private $mTitleText;
155
156 /**
157 * @var array<int,array<string,int>> 2-D map of NS/DBK to ID for the links in the document.
158 * ID=zero for broken.
159 */
160 private $mLinks = [];
161
162 /**
163 * @var array<string,int> Keys are DBKs for the links to special pages in the document.
164 * @since 1.35
165 */
166 private $mLinksSpecial = [];
167
168 /**
169 * @var array<int,array<string,int>> 2-D map of NS/DBK to ID for the template references.
170 * ID=zero for broken.
171 */
172 private $mTemplates = [];
173
174 /**
175 * @var array<int,array<string,int>> 2-D map of NS/DBK to rev ID for the template references.
176 * ID=zero for broken.
177 */
178 private $mTemplateIds = [];
179
180 /**
181 * @var array<string,int> DB keys of the images used, in the array key only
182 */
183 private $mImages = [];
184
185 /**
186 * @var array<string,array<string,string>> DB keys of the images used mapped to sha1 and MW timestamp.
187 */
188 private $mFileSearchOptions = [];
189
190 /**
191 * @var array<string,int> External link URLs, in the key only.
192 */
193 private array $mExternalLinks = [];
194
195 /**
196 * @var array<string,array<string,int>> 2-D map of prefix/DBK (in keys only)
197 * for the inline interwiki links in the document.
198 */
199 private $mInterwikiLinks = [];
200
201 /**
202 * @var bool Show a new section link?
203 */
204 private $mNewSection = false;
205
206 /**
207 * @var bool Hide the new section link?
208 */
209 private $mHideNewSection = false;
210
211 /**
212 * @var bool No gallery on category page? (__NOGALLERY__).
213 */
214 private $mNoGallery = false;
215
216 /**
217 * @var string[] Items to put in the <head> section
218 */
219 private $mHeadItems = [];
220
221 /**
222 * @var array<string,true> Modules to be loaded by ResourceLoader
223 */
224 private $mModuleSet = [];
225
226 /**
227 * @var array<string,true> Modules of which only the CSS will be loaded by ResourceLoader.
228 */
229 private $mModuleStyleSet = [];
230
231 /**
232 * @var array JavaScript config variable for mw.config combined with this page.
233 */
234 private $mJsConfigVars = [];
235
236 /**
237 * @var array<string,int> Warning text to be returned to the user.
238 * Wikitext formatted, in the key only.
239 */
240 private $mWarnings = [];
241
242 /**
243 * @var array<string,array> *Unformatted* warning messages and
244 * arguments to be returned to the user. This is for internal use
245 * when merging ParserOutputs and are not serialized/deserialized.
246 */
247 private $mWarningMsgs = [];
248
249 /**
250 * @var ?TOCData Table of contents data, or null if it hasn't been set.
251 */
252 private $mTOCData;
253
254 /**
255 * @var array Name/value pairs to be cached in the DB.
256 */
257 private $mProperties = [];
258
259 /**
260 * @var ?string Timestamp of the revision.
261 */
262 private $mTimestamp;
263
264 /**
265 * @var bool Whether OOUI should be enabled.
266 */
267 private $mEnableOOUI = false;
268
269 /**
270 * @var bool Whether the index policy has been set to 'index'.
271 */
272 private $mIndexSet = false;
273
274 /**
275 * @var bool Whether the index policy has been set to 'noindex'.
276 */
277 private $mNoIndexSet = false;
278
279 /**
280 * @var array extra data used by extensions.
281 */
282 private $mExtensionData = [];
283
284 /**
285 * @var array Parser limit report data.
286 */
287 private $mLimitReportData = [];
288
289 /** @var array Parser limit report data for JSON */
290 private $mLimitReportJSData = [];
291
292 /** @var string Debug message added by ParserCache */
293 private $mCacheMessage = '';
294
295 /**
296 * @var array Timestamps for getTimeSinceStart().
297 */
298 private $mParseStartTime = [];
299
300 /**
301 * @var array Durations for getTimeProfile().
302 */
303 private $mTimeProfile = [];
304
305 /**
306 * @var bool Whether to emit X-Frame-Options: DENY.
307 * This controls if anti-clickjacking / frame-breaking headers will
308 * be sent. This should be done for pages where edit actions are possible.
309 */
310 private $mPreventClickjacking = false;
311
312 /**
313 * @var string[] Extra script-src for CSP
314 */
315 private $mExtraScriptSrcs = [];
316
317 /**
318 * @var string[] Extra default-src for CSP [Everything but script and style]
319 */
320 private $mExtraDefaultSrcs = [];
321
322 /**
323 * @var string[] Extra style-src for CSP
324 */
325 private $mExtraStyleSrcs = [];
326
327 /**
328 * @var array<string,true> Generic flags.
329 */
330 private $mFlags = [];
331
332 private const SPECULATIVE_FIELDS = [
333 'speculativePageIdUsed',
334 'mSpeculativeRevId',
335 'revisionTimestampUsed',
336 ];
337
338 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
339 private $mSpeculativeRevId;
340 /** @var int|null Assumed page ID for {{PAGEID}} if no revision is set */
341 private $speculativePageIdUsed;
342 /** @var string|null Assumed rev timestamp for {{REVISIONTIMESTAMP}} if no revision is set */
343 private $revisionTimestampUsed;
344
345 /** @var string|null SHA-1 base 36 hash of any self-transclusion */
346 private $revisionUsedSha1Base36;
347
348 /** string CSS classes to use for the wrapping div, stored in the array keys.
349 * If no class is given, no wrapper is added.
350 * @var array<string,true>
351 */
352 private $mWrapperDivClasses = [];
353
354 /** @var int Upper bound of expiry based on parse duration */
355 private $mMaxAdaptiveExpiry = INF;
356
357 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
358 // Current values imply that m=3933.333333 and b=-333.333333
359 // See https://www.nngroup.com/articles/website-response-times/
360 private const PARSE_FAST_SEC = 0.100; // perceived "fast" page parse
361 private const PARSE_SLOW_SEC = 1.0; // perceived "slow" page parse
362 private const FAST_AR_TTL = 60; // adaptive TTL for "fast" pages
363 private const SLOW_AR_TTL = 3600; // adaptive TTL for "slow" pages
364 private const MIN_AR_TTL = 15; // min adaptive TTL (for pool counter, and edit stashing)
365
366 /**
367 * @param string|null $text HTML. Use null to indicate that this ParserOutput contains only
368 * meta-data, and the HTML output is undetermined, as opposed to empty. Passing null
369 * here causes hasText() to return false. In 1.39 the default value changed from ''
370 * to null.
371 * @param array $languageLinks
372 * @param array $categoryLinks
373 * @param bool $unused
374 * @param string $titletext
375 */
376 public function __construct( $text = null, $languageLinks = [], $categoryLinks = [],
377 $unused = false, $titletext = ''
378 ) {
379 $this->mRawText = $text;
380 $this->mCategories = $categoryLinks;
381 $this->mTitleText = $titletext;
382 if ( $languageLinks === null ) { // T376323
383 wfDeprecated( __METHOD__ . ' with null $languageLinks', '1.43' );
384 }
385 foreach ( ( $languageLinks ?? [] ) as $ll ) {
386 $this->addLanguageLink( $ll );
387 }
388 // If the content handler does not specify an alternative (by
389 // calling ::resetParseStartTime() at a later point) then use
390 // the creation of the ParserOutput as the "start of parse" time.
391 $this->resetParseStartTime();
392 }
393
394 /**
395 * Returns true if text was passed to the constructor, or set using setText(). Returns false
396 * if null was passed to the $text parameter of the constructor to indicate that this
397 * ParserOutput only contains meta-data, and the HTML output is undetermined.
398 *
399 * @since 1.32
400 *
401 * @return bool Whether this ParserOutput contains rendered text. If this returns false, the
402 * ParserOutput contains meta-data only.
403 */
404 public function hasText(): bool {
405 return ( $this->mRawText !== null );
406 }
407
408 /**
409 * Get the cacheable text with <mw:editsection> markers still in it. The
410 * return value is suitable for writing back via setText() but is not valid
411 * for display to the user.
412 *
413 * @return string
414 * @since 1.27
415 */
416 public function getRawText() {
417 if ( $this->mRawText === null ) {
418 throw new LogicException( 'This ParserOutput contains no text!' );
419 }
420
421 return $this->mRawText;
422 }
423
424 /**
425 * Get the output HTML
426 *
427 * T293512: in the future, ParserOutput::getText() will be deprecated in favor of invoking
428 * the OutputTransformPipeline directly on a ParserOutput.
429 * @param array $options (since 1.31) Transformations to apply to the HTML
430 * - allowClone: (bool) Whether to clone the ParserOutput before
431 * applying transformations. Default is false.
432 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
433 * to generate one and `__NOTOC__` wasn't used. Default is true,
434 * but might be statefully overridden.
435 * - injectTOC: (bool) Replace the TOC_PLACEHOLDER with TOC contents;
436 * otherwise the marker will be left in the article (and the skin
437 * will be responsible for replacing or removing it). Default is
438 * true.
439 * - enableSectionEditLinks: (bool) Include section edit links, assuming
440 * section edit link tokens are present in the HTML. Default is true,
441 * but might be statefully overridden.
442 * - userLang: (Language) Language object used for localizing UX messages,
443 * for example the heading of the table of contents. If omitted, will
444 * use the language of the main request context.
445 * - skin: (Skin) Skin object used for transforming section edit links.
446 * - unwrap: (bool) Return text without a wrapper div. Default is false,
447 * meaning a wrapper div will be added if getWrapperDivClass() returns
448 * a non-empty string.
449 * - wrapperDivClass: (string) Wrap the output in a div and apply the given
450 * CSS class to that div. This overrides the output of getWrapperDivClass().
451 * Setting this to an empty string has the same effect as 'unwrap' => true.
452 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
453 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
454 * value of the attribute: all but the first will be replaced by `<link
455 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
456 * the scheme-specific-part of the href is the (percent-encoded) value
457 * of the `data-mw-deduplicate` attribute.
458 * - absoluteURLs: (bool) use absolute URLs in all links. Default: false
459 * - includeDebugInfo: (bool) render PP limit report in HTML. Default: false
460 * @return string HTML
461 * @return-taint escaped
462 * @deprecated since 1.42, this method has side-effects on the ParserOutput
463 * (see T353257) and so should be avoided in favor of directly invoking
464 * the default output pipeline on a ParserOutput; for now, use of
465 * ::runOutputPipeline() is preferred to ensure that ParserOptions are
466 * available.
467 */
468 public function getText( $options = [] ) {
469 $oldText = $this->mRawText; // T353257
470 $options += [ 'allowClone' => false ];
471 $po = $this->runPipelineInternal( null, $options );
472 $newText = $po->getContentHolderText();
473 // T353257: for back-compat only mutations to metadata performed by
474 // the pipeline should be preserved; mutations to $mText should be
475 // discarded.
476 $this->setRawText( $oldText );
477 return $newText;
478 }
479
480 /**
481 * @unstable This method is transitional and will be replaced by a method
482 * in another class, maybe ContentRenderer. It allows us to break our
483 * porting work into two steps; in the first we bring ParserOptions to
484 * to each ::getText() callsite to ensure it is made available to the
485 * postprocessing pipeline. In the second we move this functionality
486 * into the Content hierarchy and out of ParserOutput, which should become
487 * a pure value object.
488 *
489 * @param ParserOptions $popts
490 * @param array $options (since 1.31) Transformations to apply to the HTML
491 * - allowClone: (bool) Whether to clone the ParserOutput before
492 * applying transformations. Default is true.
493 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
494 * to generate one and `__NOTOC__` wasn't used. Default is true,
495 * but might be statefully overridden.
496 * - injectTOC: (bool) Replace the TOC_PLACEHOLDER with TOC contents;
497 * otherwise the marker will be left in the article (and the skin
498 * will be responsible for replacing or removing it). Default is
499 * true.
500 * - enableSectionEditLinks: (bool) Include section edit links, assuming
501 * section edit link tokens are present in the HTML. Default is true,
502 * but might be statefully overridden.
503 * - userLang: (Language) Language object used for localizing UX messages,
504 * for example the heading of the table of contents. If omitted, will
505 * use the language of the main request context.
506 * - skin: (Skin) Skin object used for transforming section edit links.
507 * - unwrap: (bool) Return text without a wrapper div. Default is false,
508 * meaning a wrapper div will be added if getWrapperDivClass() returns
509 * a non-empty string.
510 * - wrapperDivClass: (string) Wrap the output in a div and apply the given
511 * CSS class to that div. This overrides the output of getWrapperDivClass().
512 * Setting this to an empty string has the same effect as 'unwrap' => true.
513 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
514 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
515 * value of the attribute: all but the first will be replaced by `<link
516 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
517 * the scheme-specific-part of the href is the (percent-encoded) value
518 * of the `data-mw-deduplicate` attribute.
519 * - absoluteURLs: (bool) use absolute URLs in all links. Default: false
520 * - includeDebugInfo: (bool) render PP limit report in HTML. Default: false
521 * It is planned to eventually deprecate this $options array and to be able to
522 * pass its content in the $popts ParserOptions.
523 * @return ParserOutput
524 */
525 public function runOutputPipeline( ParserOptions $popts, array $options = [] ): ParserOutput {
526 return $this->runPipelineInternal( $popts, $options );
527 }
528
529 /**
530 * Temporary helper method to allow running the pipeline with null $popts for now, although
531 * passing a null ParserOptions is a temporary backward-compatibility hack and will be deprecated.
532 */
533 private function runPipelineInternal( ?ParserOptions $popts, array $options = [] ): ParserOutput {
534 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
535 $options += [
536 'allowClone' => true,
537 'allowTOC' => true,
538 'injectTOC' => true,
539 'enableSectionEditLinks' => !$this->getOutputFlag( ParserOutputFlags::NO_SECTION_EDIT_LINKS ),
540 'userLang' => null,
541 'skin' => null,
542 'unwrap' => false,
543 'wrapperDivClass' => $this->getWrapperDivClass(),
544 'deduplicateStyles' => true,
545 'absoluteURLs' => false,
546 'includeDebugInfo' => false,
547 'isParsoidContent' => PageBundleParserOutputConverter::hasPageBundle( $this ),
548 ];
549 return $pipeline->run( $this, $popts, $options );
550 }
551
552 /**
553 * Adds a comment notice about cache state to the text of the page
554 * @param string $msg
555 * @internal used by ParserCache
556 */
557 public function addCacheMessage( string $msg ): void {
558 $this->mCacheMessage .= $msg;
559 }
560
561 /**
562 * Add a CSS class to use for the wrapping div. If no class is given, no wrapper is added.
563 *
564 * @param string $class
565 */
566 public function addWrapperDivClass( $class ): void {
567 $this->mWrapperDivClasses[$class] = true;
568 }
569
570 /**
571 * Clears the CSS class to use for the wrapping div, effectively disabling the wrapper div
572 * until addWrapperDivClass() is called.
573 */
574 public function clearWrapperDivClass(): void {
575 $this->mWrapperDivClasses = [];
576 }
577
578 /**
579 * Returns the class (or classes) to be used with the wrapper div for this output.
580 * If there is no wrapper class given, no wrapper div should be added.
581 * The wrapper div is added automatically by getText().
582 *
583 * @return string
584 */
585 public function getWrapperDivClass(): string {
586 return implode( ' ', array_keys( $this->mWrapperDivClasses ) );
587 }
588
589 /**
590 * @param int $id
591 * @since 1.28
592 */
593 public function setSpeculativeRevIdUsed( $id ): void {
594 $this->mSpeculativeRevId = $id;
595 }
596
597 /**
598 * @return int|null
599 * @since 1.28
600 */
601 public function getSpeculativeRevIdUsed(): ?int {
602 return $this->mSpeculativeRevId;
603 }
604
605 /**
606 * @param int $id
607 * @since 1.34
608 */
609 public function setSpeculativePageIdUsed( $id ): void {
610 $this->speculativePageIdUsed = $id;
611 }
612
613 /**
614 * @return int|null
615 * @since 1.34
616 */
617 public function getSpeculativePageIdUsed() {
618 return $this->speculativePageIdUsed;
619 }
620
621 /**
622 * @param string $timestamp TS_MW timestamp
623 * @since 1.34
624 */
625 public function setRevisionTimestampUsed( $timestamp ): void {
626 $this->revisionTimestampUsed = $timestamp;
627 }
628
629 /**
630 * @return string|null TS_MW timestamp or null if not used
631 * @since 1.34
632 */
633 public function getRevisionTimestampUsed() {
634 return $this->revisionTimestampUsed;
635 }
636
637 /**
638 * @param string $hash Lowercase SHA-1 base 36 hash
639 * @since 1.34
640 */
641 public function setRevisionUsedSha1Base36( $hash ): void {
642 if ( $hash === null ) {
643 return; // e.g. RevisionRecord::getSha1() returned null
644 }
645
646 if (
647 $this->revisionUsedSha1Base36 !== null &&
648 $this->revisionUsedSha1Base36 !== $hash
649 ) {
650 $this->revisionUsedSha1Base36 = ''; // mismatched
651 } else {
652 $this->revisionUsedSha1Base36 = $hash;
653 }
654 }
655
656 /**
657 * @return string|null Lowercase SHA-1 base 36 hash, null if unused, or "" on inconsistency
658 * @since 1.34
659 */
660 public function getRevisionUsedSha1Base36() {
661 return $this->revisionUsedSha1Base36;
662 }
663
664 /**
665 * @return string[]
666 * @note Before 1.43, this function returned an array reference.
667 * @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::LANGUAGE)
668 */
669 public function getLanguageLinks() {
670 $result = [];
671 foreach ( $this->mLanguageLinkMap as $lang => $title ) {
672 // T374736: Back-compat with empty prefix; see ::addLanguageLink()
673 $result[] = $title === '|' ? "$lang" : "$lang:$title";
674 }
675 return $result;
676 }
677
678 /** @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::INTERWIKI) */
679 public function getInterwikiLinks() {
680 return $this->mInterwikiLinks;
681 }
682
683 /**
684 * Return the names of the categories on this page.
685 * Unlike ::getCategories(), sort keys are *not* included in the
686 * return value.
687 * @return array<string> The names of the categories
688 * @since 1.38
689 */
690 public function getCategoryNames(): array {
691 # Note that numeric category names get converted to 'int' when
692 # stored as array keys; stringify the keys to ensure they
693 # return to original string form so as not to confuse callers.
694 return array_map( 'strval', array_keys( $this->mCategories ) );
695 }
696
697 /**
698 * Return category names and sort keys as a map.
699 *
700 * BEWARE that numeric category names get converted to 'int' when stored
701 * as array keys. Because of this, use of this method is not recommended
702 * in new code; using ::getCategoryNames() and ::getCategorySortKey() will
703 * be less error-prone.
704 *
705 * @return array<string|int,string>
706 * @internal
707 */
708 public function getCategoryMap(): array {
709 return $this->mCategories;
710 }
711
712 /**
713 * Return the sort key for a given category name, or `null` if the
714 * category is not present in this ParserOutput. Returns the
715 * empty string if the category is to use the default sort key.
716 *
717 * @note The effective sort key in the database may vary from what
718 * is returned here; see note in ParserOutput::addCategory().
719 *
720 * @param string $name The category name
721 * @return ?string The sort key for the category, or `null` if the
722 * category is not present in this ParserOutput
723 * @since 1.40
724 */
725 public function getCategorySortKey( string $name ): ?string {
726 // This API avoids exposing the fact that numeric string category
727 // names are going to be converted to 'int' when used as array
728 // keys for the `mCategories` field.
729 return $this->mCategories[$name] ?? null;
730 }
731
732 /**
733 * @return string[]
734 * @since 1.25
735 */
736 public function getIndicators(): array {
737 return $this->mIndicators;
738 }
739
740 public function getTitleText() {
741 return $this->mTitleText;
742 }
743
744 /**
745 * @return ?TOCData the table of contents data, or null if it hasn't been
746 * set.
747 */
748 public function getTOCData(): ?TOCData {
749 return $this->mTOCData;
750 }
751
752 /**
753 * @internal
754 * @return string
755 */
756 public function getCacheMessage(): string {
757 return $this->mCacheMessage;
758 }
759
760 /**
761 * @internal
762 * @return array
763 */
764 public function getSections(): array {
765 if ( $this->mTOCData !== null ) {
766 return $this->mTOCData->toLegacy();
767 }
768 // For compatibility
769 return [];
770 }
771
772 /**
773 * Get a list of links of the given type.
774 *
775 * Provides a uniform interface to various lists of links stored in
776 * the metadata.
777 *
778 * Each element of the returned array has a LinkTarget as the 'link'
779 * property. Local and template links also have 'pageid' set.
780 * Template links have 'revid' set. Category links have 'sort' set.
781 * Media links optionally have 'time' and 'sha1' set.
782 *
783 * @param string $linkType A link type, which should be a constant from
784 * ParserOutputLinkTypes.
785 * @return list<array{link:ParsoidLinkTarget,pageid?:int,revid?:int,sort?:string,time?:string|false,sha1?:string|false}>
786 */
787 public function getLinkList( string $linkType ): array {
788 # Note that fragments are dropped for everything except language links
789 $result = [];
790 switch ( $linkType ) {
791 case ParserOutputLinkTypes::CATEGORY:
792 foreach ( $this->mCategories as $dbkey => $sort ) {
793 $result[] = [
794 'link' => new TitleValue( NS_CATEGORY, (string)$dbkey ),
795 'sort' => $sort,
796 ];
797 }
798 break;
799
800 case ParserOutputLinkTypes::INTERWIKI:
801 foreach ( $this->mInterwikiLinks as $prefix => $arr ) {
802 foreach ( $arr as $dbkey => $ignore ) {
803 $result[] = [
804 'link' => new TitleValue( NS_MAIN, (string)$dbkey, '', (string)$prefix ),
805 ];
806 }
807 }
808 break;
809
810 case ParserOutputLinkTypes::LANGUAGE:
811 foreach ( $this->mLanguageLinkMap as $lang => $title ) {
812 if ( $title === '|' ) {
813 continue; // T374736
814 }
815 # language links can have fragments!
816 [ $title, $frag ] = array_pad( explode( '#', $title, 2 ), 2, '' );
817 $result[] = [
818 'link' => new TitleValue( NS_MAIN, $title, $frag, (string)$lang ),
819 ];
820 }
821 break;
822
823 case ParserOutputLinkTypes::LOCAL:
824 foreach ( $this->mLinks as $ns => $arr ) {
825 foreach ( $arr as $dbkey => $id ) {
826 $result[] = [
827 'link' => new TitleValue( $ns, (string)$dbkey ),
828 'pageid' => $id,
829 ];
830 }
831 }
832 break;
833
834 case ParserOutputLinkTypes::MEDIA:
835 foreach ( $this->mImages as $dbkey => $ignore ) {
836 $extra = $this->mFileSearchOptions[$dbkey] ?? [];
837 $extra['link'] = new TitleValue( NS_FILE, (string)$dbkey );
838 $result[] = $extra;
839 }
840 break;
841
842 case ParserOutputLinkTypes::SPECIAL:
843 foreach ( $this->mLinksSpecial as $dbkey => $ignore ) {
844 $result[] = [
845 'link' => new TitleValue( NS_SPECIAL, (string)$dbkey ),
846 ];
847 }
848 break;
849
850 case ParserOutputLinkTypes::TEMPLATE:
851 foreach ( $this->mTemplates as $ns => $arr ) {
852 foreach ( $arr as $dbkey => $pageid ) {
853 $result[] = [
854 'link' => new TitleValue( $ns, (string)$dbkey ),
855 'pageid' => $pageid,
856 'revid' => $this->mTemplateIds[$ns][$dbkey],
857 ];
858 }
859 }
860 break;
861
862 default:
863 throw new UnexpectedValueException( "Unknown link type $linkType" );
864 }
865 return $result;
866 }
867
868 /** @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::LOCAL) */
869 public function &getLinks() {
870 return $this->mLinks;
871 }
872
873 /**
874 * @return array Keys are DBKs for the links to special pages in the document
875 * @since 1.35
876 * @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::SPECIAL)
877 */
878 public function &getLinksSpecial() {
879 return $this->mLinksSpecial;
880 }
881
882 /** @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::TEMPLATE) */
883 public function &getTemplates() {
884 return $this->mTemplates;
885 }
886
887 /** @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::TEMPLATE) */
888 public function &getTemplateIds() {
889 return $this->mTemplateIds;
890 }
891
892 /** @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::MEDIA) */
893 public function &getImages() {
894 return $this->mImages;
895 }
896
897 /** @deprecated since 1.43, use ::getLinkList(ParserOutputLinkTypes::MEDIA) */
898 public function &getFileSearchOptions() {
899 return $this->mFileSearchOptions;
900 }
901
902 /**
903 * @note Use of the reference returned by this method has been
904 * deprecated since 1.43. In a future release this will return a
905 * normal array. Use ::addExternalLink() to modify the set of
906 * external links stored in this ParserOutput.
907 */
908 public function &getExternalLinks(): array {
909 return $this->mExternalLinks;
910 }
911
912 public function setNoGallery( $value ): void {
913 $this->mNoGallery = (bool)$value;
914 }
915
916 public function getNoGallery() {
917 return $this->mNoGallery;
918 }
919
920 public function getHeadItems() {
921 return $this->mHeadItems;
922 }
923
924 public function getModules() {
925 return array_keys( $this->mModuleSet );
926 }
927
928 public function getModuleStyles() {
929 return array_keys( $this->mModuleStyleSet );
930 }
931
932 /**
933 * @param bool $showStrategyKeys Defaults to false; if set to true will
934 * expose the internal `MW_MERGE_STRATEGY_KEY` in the result. This
935 * should only be used internally to allow safe merge of config vars.
936 * @return array
937 * @since 1.23
938 */
939 public function getJsConfigVars( bool $showStrategyKeys = false ) {
940 $result = $this->mJsConfigVars;
941 // Don't expose the internal strategy key
942 foreach ( $result as &$value ) {
943 if ( is_array( $value ) && !$showStrategyKeys ) {
944 unset( $value[self::MW_MERGE_STRATEGY_KEY] );
945 }
946 }
947 return $result;
948 }
949
950 public function getWarnings(): array {
951 return array_keys( $this->mWarnings );
952 }
953
954 public function getIndexPolicy(): string {
955 // 'noindex' wins if both are set. (T16899)
956 if ( $this->mNoIndexSet ) {
957 return 'noindex';
958 } elseif ( $this->mIndexSet ) {
959 return 'index';
960 }
961 return '';
962 }
963
964 /**
965 * @return string|null TS_MW timestamp of the revision content
966 */
967 public function getRevisionTimestamp(): ?string {
968 return $this->mTimestamp;
969 }
970
971 /**
972 * @return string|null TS_MW timestamp of the revision content
973 * @deprecated since 1.42; use ::getRevisionTimestamp() instead
974 */
975 public function getTimestamp() {
976 return $this->getRevisionTimestamp();
977 }
978
979 public function getLimitReportData() {
980 return $this->mLimitReportData;
981 }
982
983 public function getLimitReportJSData() {
984 return $this->mLimitReportJSData;
985 }
986
987 public function getEnableOOUI() {
988 return $this->mEnableOOUI;
989 }
990
991 /**
992 * Get extra Content-Security-Policy 'default-src' directives
993 * @since 1.35
994 * @return string[]
995 */
996 public function getExtraCSPDefaultSrcs() {
997 return $this->mExtraDefaultSrcs;
998 }
999
1000 /**
1001 * Get extra Content-Security-Policy 'script-src' directives
1002 * @since 1.35
1003 * @return string[]
1004 */
1005 public function getExtraCSPScriptSrcs() {
1006 return $this->mExtraScriptSrcs;
1007 }
1008
1009 /**
1010 * Get extra Content-Security-Policy 'style-src' directives
1011 * @since 1.35
1012 * @return string[]
1013 */
1014 public function getExtraCSPStyleSrcs() {
1015 return $this->mExtraStyleSrcs;
1016 }
1017
1018 /**
1019 * Set the raw text of the ParserOutput.
1020 *
1021 * If you did not generate html, pass null to mark it as such.
1022 *
1023 * @since 1.42
1024 * @param string|null $text HTML content of ParserOutput or null if not generated
1025 * @param-taint $text exec_html
1026 */
1027 public function setRawText( ?string $text ): void {
1028 $this->mRawText = $text;
1029 }
1030
1031 /**
1032 * Set the raw text of the ParserOutput.
1033 *
1034 * If you did not generate html, pass null to mark it as such.
1035 *
1036 * @since 1.39 You can now pass null to this function
1037 * @param string|null $text HTML content of ParserOutput or null if not generated
1038 * @param-taint $text exec_html
1039 * @return string|null Previous value of ParserOutput's raw text
1040 * @deprecated since 1.42; use ::setRawText() which matches the getter ::getRawText()
1041 */
1042 public function setText( $text ) {
1043 return wfSetVar( $this->mRawText, $text, true );
1044 }
1045
1046 /**
1047 * @deprecated since 1.42, use ::addLanguageLink() instead.
1048 */
1049 public function setLanguageLinks( $ll ) {
1050 $old = $this->getLanguageLinks();
1051 $this->mLanguageLinkMap = [];
1052 if ( $ll === null ) { // T376323
1053 wfDeprecated( __METHOD__ . ' with null argument', '1.43' );
1054 }
1055 foreach ( ( $ll ?? [] ) as $l ) {
1056 $this->addLanguageLink( $l );
1057 }
1058 return $old;
1059 }
1060
1061 public function setTitleText( $t ) {
1062 return wfSetVar( $this->mTitleText, $t );
1063 }
1064
1065 /**
1066 * @param TOCData $tocData Table of contents data for the page
1067 */
1068 public function setTOCData( TOCData $tocData ): void {
1069 $this->mTOCData = $tocData;
1070 }
1071
1072 /**
1073 * @param array $sectionArray
1074 * @return array Previous value of ::getSections()
1075 */
1076 public function setSections( array $sectionArray ) {
1077 $oldValue = $this->getSections();
1078 $this->setTOCData( TOCData::fromLegacy( $sectionArray ) );
1079 return $oldValue;
1080 }
1081
1082 /**
1083 * Update the index policy of the robots meta tag.
1084 *
1085 * Note that calling this method does not guarantee
1086 * that {@link self::getIndexPolicy()} will return the given policy –
1087 * if different calls set the index policy to 'index' and 'noindex',
1088 * then 'noindex' always wins (T16899), even if the 'index' call happened later.
1089 * If this is not what you want,
1090 * you can reset {@link ParserOutputFlags::NO_INDEX_POLICY} with {@link self::setOutputFlag()}.
1091 *
1092 * @param string $policy 'index' or 'noindex'.
1093 * @return string The previous policy.
1094 */
1095 public function setIndexPolicy( $policy ): string {
1096 $old = $this->getIndexPolicy();
1097 if ( $policy === 'noindex' ) {
1098 $this->mNoIndexSet = true;
1099 } elseif ( $policy === 'index' ) {
1100 $this->mIndexSet = true;
1101 }
1102 return $old;
1103 }
1104
1105 /**
1106 * @param ?string $timestamp TS_MW timestamp of the revision content
1107 */
1108 public function setRevisionTimestamp( ?string $timestamp ): void {
1109 $this->mTimestamp = $timestamp;
1110 }
1111
1112 /**
1113 * @param ?string $timestamp TS_MW timestamp of the revision content
1114 *
1115 * @return ?string The previous value of the timestamp
1116 * @deprecated since 1.42; use ::setRevisionTimestamp() instead
1117 */
1118 public function setTimestamp( $timestamp ) {
1119 return wfSetVar( $this->mTimestamp, $timestamp );
1120 }
1121
1122 /**
1123 * Add a category.
1124 *
1125 * Although ParserOutput::getCategorySortKey() will return exactly
1126 * the sort key you specify here, before storing in the database
1127 * all sort keys will be language converted, HTML entities will be
1128 * decoded, newlines stripped, and then they will be truncated to
1129 * 255 bytes. Thus the "effective" sort key in the DB may be different
1130 * from what is passed to `$sort` here and returned by
1131 * ::getCategorySortKey().
1132 *
1133 * @param string|ParsoidLinkTarget $c The category name
1134 * @param string $sort The sort key; an empty string indicates
1135 * that the default sort key for the page should be used.
1136 */
1137 public function addCategory( $c, $sort = '' ): void {
1138 if ( $c instanceof ParsoidLinkTarget ) {
1139 $c = $c->getDBkey();
1140 }
1141 $this->mCategories[$c] = $sort;
1142 }
1143
1144 /**
1145 * Overwrite the category map.
1146 * @param array<string,string> $c Map of category names to sort keys
1147 * @since 1.38
1148 */
1149 public function setCategories( array $c ): void {
1150 $this->mCategories = $c;
1151 }
1152
1153 /**
1154 * @param string $id
1155 * @param string $content
1156 * @param-taint $content exec_html
1157 * @since 1.25
1158 */
1159 public function setIndicator( $id, $content ): void {
1160 $this->mIndicators[$id] = $content;
1161 }
1162
1163 /**
1164 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
1165 * object is added to.
1166 *
1167 * @since 1.26
1168 * @param bool $enable If OOUI should be enabled or not
1169 */
1170 public function setEnableOOUI( bool $enable = false ): void {
1171 $this->mEnableOOUI = $enable;
1172 }
1173
1174 /**
1175 * Add a language link.
1176 * @param ParsoidLinkTarget|string $t
1177 */
1178 public function addLanguageLink( $t ): void {
1179 # Note that fragments are preserved
1180 if ( $t instanceof ParsoidLinkTarget ) {
1181 // Language links are unusual in using 'text' rather than 'db key'
1182 // Note that fragments are preserved.
1183 $lang = $t->getInterwiki();
1184 $title = $t->getText();
1185 if ( $t->hasFragment() ) {
1186 $title .= '#' . $t->getFragment();
1187 }
1188 } else {
1189 [ $lang, $title ] = array_pad( explode( ':', $t, 2 ), -2, '' );
1190 }
1191 if ( $lang === '' ) {
1192 // T374736: For backward compatibility with test cases only!
1193 wfDeprecated( __METHOD__ . ' without prefix', '1.43' );
1194 [ $lang, $title ] = [ $title, '|' ]; // | can not occur in valid title
1195 }
1196 $this->mLanguageLinkMap[$lang] ??= $title;
1197 }
1198
1199 /**
1200 * Add a warning to the output for this page.
1201 * @param MessageValue $mv Note that the parameters must be serializable/deserializable
1202 * with JsonCodec; see the @note on ParserOutput::setExtensionData(). MessageValue guarantees
1203 * that unless the deprecated ParamType::OBJECT or the ->objectParams() method is used.
1204 * @since 1.43
1205 */
1206 public function addWarningMsgVal( MessageValue $mv ) {
1207 $m = ( new Converter() )->convertMessageValue( $mv );
1208 // These can eventually be stored as MessageValue instead of converting to Message.
1209 $this->addWarningMsg( $m->getKey(), ...$m->getParams() );
1210 }
1211
1212 /**
1213 * Add a warning to the output for this page.
1214 * @param string $msg The localization message key for the warning
1215 * @param mixed|JsonDeserializable ...$args Optional arguments for the
1216 * message. These arguments must be serializable/deserializable with
1217 * JsonCodec; see the @note on ParserOutput::setExtensionData()
1218 * @since 1.38
1219 */
1220 public function addWarningMsg( string $msg, ...$args ): void {
1221 // MessageValue objects are defined in core and thus not visible
1222 // to Parsoid or to its ContentMetadataCollector interface.
1223 // Eventually this method (defined in ContentMetadataCollector) should
1224 // call ::addWarningMsgVal() instead of the other way around.
1225
1226 // preserve original arguments in $mWarningMsgs to allow merge
1227 // @todo: these aren't serialized/deserialized yet -- before we
1228 // turn on serialization of $this->mWarningMsgs we need to ensure
1229 // callers aren't passing nonserializable arguments: T343048.
1230 $jsonCodec = MediaWikiServices::getInstance()->getJsonCodec();
1231 $path = $jsonCodec->detectNonSerializableData( $args, true );
1232 if ( $path !== null ) {
1233 wfDeprecatedMsg(
1234 "ParserOutput::addWarningMsg() called with nonserializable arguments: $path",
1235 '1.41'
1236 );
1237 }
1238 $this->mWarningMsgs[$msg] = $args;
1239 $s = wfMessage( $msg, ...$args )
1240 // some callers set the title here?
1241 ->inContentLanguage() // because this ends up in cache
1242 ->text();
1243 $this->mWarnings[$s] = 1;
1244 }
1245
1246 public function setNewSection( $value ): void {
1247 $this->mNewSection = (bool)$value;
1248 }
1249
1250 /**
1251 * @param bool $value Hide the new section link?
1252 */
1253 public function setHideNewSection( bool $value ): void {
1254 $this->mHideNewSection = $value;
1255 }
1256
1257 public function getHideNewSection(): bool {
1258 return (bool)$this->mHideNewSection;
1259 }
1260
1261 public function getNewSection(): bool {
1262 return (bool)$this->mNewSection;
1263 }
1264
1265 /**
1266 * Checks, if a url is pointing to the own server
1267 *
1268 * @param string $internal The server to check against
1269 * @param string $url The url to check
1270 * @return bool
1271 * @internal
1272 */
1273 public static function isLinkInternal( $internal, $url ): bool {
1274 return (bool)preg_match( '/^' .
1275 # If server is proto relative, check also for http/https links
1276 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
1277 preg_quote( $internal, '/' ) .
1278 # check for query/path/anchor or end of link in each case
1279 '(?:[\?\/\#]|$)/i',
1280 $url
1281 );
1282 }
1283
1284 public function addExternalLink( $url ): void {
1285 # We don't register links pointing to our own server, unless... :-)
1286 $config = MediaWikiServices::getInstance()->getMainConfig();
1287 $server = $config->get( MainConfigNames::Server );
1288 $registerInternalExternals = $config->get( MainConfigNames::RegisterInternalExternals );
1289 # Replace unnecessary URL escape codes with the referenced character
1290 # This prevents spammers from hiding links from the filters
1291 $url = Parser::normalizeLinkUrl( $url );
1292
1293 $registerExternalLink = true;
1294 if ( !$registerInternalExternals ) {
1295 $registerExternalLink = !self::isLinkInternal( $server, $url );
1296 }
1297 if ( $registerExternalLink ) {
1298 $this->mExternalLinks[$url] = 1;
1299 }
1300 }
1301
1302 /**
1303 * Record a local or interwiki inline link for saving in future link tables.
1304 *
1305 * @param ParsoidLinkTarget $link (used to require Title until 1.38)
1306 * @param int|null $id Optional known page_id so we can skip the lookup
1307 */
1308 public function addLink( ParsoidLinkTarget $link, $id = null ): void {
1309 if ( $link->isExternal() ) {
1310 // Don't record interwikis in pagelinks
1311 $this->addInterwikiLink( $link );
1312 return;
1313 }
1314 $ns = $link->getNamespace();
1315 $dbk = $link->getDBkey();
1316 if ( $ns === NS_MEDIA ) {
1317 // Normalize this pseudo-alias if it makes it down here...
1318 $ns = NS_FILE;
1319 } elseif ( $ns === NS_SPECIAL ) {
1320 // We don't want to record Special: links in the database, so put them in a separate place.
1321 // It might actually be wise to, but we'd need to do some normalization.
1322 $this->mLinksSpecial[$dbk] = 1;
1323 return;
1324 } elseif ( $dbk === '' ) {
1325 // Don't record self links - [[#Foo]]
1326 return;
1327 }
1328 if ( $id === null ) {
1329 // T357048: This actually kills performance; we should batch these.
1330 $page = MediaWikiServices::getInstance()->getPageStore()->getPageForLink( $link );
1331 $id = $page->getId();
1332 }
1333 $this->mLinks[$ns][$dbk] = $id;
1334 }
1335
1336 /**
1337 * Register a file dependency for this output
1338 * @param string|ParsoidLinkTarget $name Title dbKey
1339 * @param string|false|null $timestamp MW timestamp of file creation (or false if non-existing)
1340 * @param string|false|null $sha1 Base 36 SHA-1 of file (or false if non-existing)
1341 */
1342 public function addImage( $name, $timestamp = null, $sha1 = null ): void {
1343 if ( $name instanceof ParsoidLinkTarget ) {
1344 $name = $name->getDBkey();
1345 }
1346 $this->mImages[$name] = 1;
1347 if ( $timestamp !== null && $sha1 !== null ) {
1348 $this->mFileSearchOptions[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
1349 }
1350 }
1351
1352 /**
1353 * Register a template dependency for this output
1354 *
1355 * @param ParsoidLinkTarget $link (used to require Title until 1.38)
1356 * @param int $page_id
1357 * @param int $rev_id
1358 */
1359 public function addTemplate( $link, $page_id, $rev_id ): void {
1360 if ( $link->isExternal() ) {
1361 // Will throw an InvalidArgumentException in a future release.
1362 wfDeprecated( __METHOD__ . " with interwiki link", '1.42' );
1363 return;
1364 }
1365 $ns = $link->getNamespace();
1366 $dbk = $link->getDBkey();
1367 // T357048: Parsoid doesn't have page_id
1368 $this->mTemplates[$ns][$dbk] = $page_id;
1369 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
1370 }
1371
1372 /**
1373 * @param ParsoidLinkTarget $link must be an interwiki link
1374 * (used to require Title until 1.38).
1375 */
1376 public function addInterwikiLink( $link ): void {
1377 if ( !$link->isExternal() ) {
1378 throw new InvalidArgumentException( 'Non-interwiki link passed, internal parser error.' );
1379 }
1380 $prefix = $link->getInterwiki();
1381 $this->mInterwikiLinks[$prefix][$link->getDBkey()] = 1;
1382 }
1383
1384 /**
1385 * Add some text to the "<head>".
1386 * If $tag is set, the section with that tag will only be included once
1387 * in a given page.
1388 * @param string $section
1389 * @param string|false $tag
1390 */
1391 public function addHeadItem( $section, $tag = false ): void {
1392 if ( $tag !== false ) {
1393 $this->mHeadItems[$tag] = $section;
1394 } else {
1395 $this->mHeadItems[] = $section;
1396 }
1397 }
1398
1399 /**
1400 * @see OutputPage::addModules
1401 * @param string[] $modules
1402 */
1403 public function addModules( array $modules ): void {
1404 $modules = array_fill_keys( $modules, true );
1405 $this->mModuleSet = array_merge( $this->mModuleSet, $modules );
1406 }
1407
1408 /**
1409 * @see OutputPage::addModuleStyles
1410 * @param string[] $modules
1411 */
1412 public function addModuleStyles( array $modules ): void {
1413 $modules = array_fill_keys( $modules, true );
1414 $this->mModuleStyleSet = array_merge( $this->mModuleStyleSet, $modules );
1415 }
1416
1417 /**
1418 * Add one or more variables to be set in mw.config in JavaScript.
1419 *
1420 * @param string|array $keys Key or array of key/value pairs.
1421 * @param mixed|null $value [optional] Value of the configuration variable.
1422 * @since 1.23
1423 * @deprecated since 1.38, use ::setJsConfigVar() or ::appendJsConfigVar()
1424 * which ensures compatibility with asynchronous parsing; emitting warnings
1425 * since 1.43.
1426 */
1427 public function addJsConfigVars( $keys, $value = null ): void {
1428 wfDeprecated( __METHOD__, '1.38' );
1429 if ( is_array( $keys ) ) {
1430 foreach ( $keys as $key => $value ) {
1431 $this->mJsConfigVars[$key] = $value;
1432 }
1433 return;
1434 }
1435
1436 $this->mJsConfigVars[$keys] = $value;
1437 }
1438
1439 /**
1440 * Add a variable to be set in mw.config in JavaScript.
1441 *
1442 * In order to ensure the result is independent of the parse order, the values
1443 * set here must be unique -- that is, you can pass the same $key
1444 * multiple times but ONLY if the $value is identical each time.
1445 * If you want to collect multiple pieces of data under a single key,
1446 * use ::appendJsConfigVar().
1447 *
1448 * @param string $key Key to use under mw.config
1449 * @param mixed|null $value Value of the configuration variable.
1450 * @since 1.38
1451 */
1452 public function setJsConfigVar( string $key, $value ): void {
1453 if (
1454 array_key_exists( $key, $this->mJsConfigVars ) &&
1455 $this->mJsConfigVars[$key] !== $value
1456 ) {
1457 // Ensure that a key is mapped to only a single value in order
1458 // to prevent the resulting array from varying if content
1459 // is parsed in a different order.
1460 throw new InvalidArgumentException( "Multiple conflicting values given for $key" );
1461 }
1462 $this->mJsConfigVars[$key] = $value;
1463 }
1464
1465 /**
1466 * Append a value to a variable to be set in mw.config in JavaScript.
1467 *
1468 * In order to ensure the result is independent of the parse order,
1469 * the value of this key will be an associative array, mapping all of
1470 * the values set under that key to true. (The array is implicitly
1471 * ordered in PHP, but you should treat it as unordered.)
1472 * If you want a non-array type for the key, and can ensure that only
1473 * a single value will be set, you should use ::setJsConfigVar() instead.
1474 *
1475 * @param string $key Key to use under mw.config
1476 * @param string $value Value to append to the configuration variable.
1477 * @param string $strategy Merge strategy:
1478 * only MW_MERGE_STRATEGY_UNION is currently supported and external callers
1479 * should treat this parameter as @internal at this time and omit it.
1480 * @since 1.38
1481 */
1482 public function appendJsConfigVar(
1483 string $key,
1484 string $value,
1485 string $strategy = self::MW_MERGE_STRATEGY_UNION
1486 ): void {
1487 if ( $strategy !== self::MW_MERGE_STRATEGY_UNION ) {
1488 throw new InvalidArgumentException( "Unknown merge strategy $strategy." );
1489 }
1490 if ( !array_key_exists( $key, $this->mJsConfigVars ) ) {
1491 $this->mJsConfigVars[$key] = [
1492 // Indicate how these values are to be merged.
1493 self::MW_MERGE_STRATEGY_KEY => $strategy,
1494 ];
1495 } elseif ( !is_array( $this->mJsConfigVars[$key] ) ) {
1496 throw new InvalidArgumentException( "Mixing set and append for $key" );
1497 } elseif ( ( $this->mJsConfigVars[$key][self::MW_MERGE_STRATEGY_KEY] ?? null ) !== $strategy ) {
1498 throw new InvalidArgumentException( "Conflicting merge strategies for $key" );
1499 }
1500 $this->mJsConfigVars[$key][$value] = true;
1501 }
1502
1503 /**
1504 * Accommodate very basic transcluding of a temporary OutputPage object into parser output.
1505 *
1506 * This is a fragile method that cannot be relied upon in any meaningful way.
1507 * It exists solely to support the wikitext feature of transcluding a SpecialPage, and
1508 * only has to work for that use case to ensure relevant styles are loaded, and that
1509 * essential config vars needed between SpecialPage and a JS feature are added.
1510 *
1511 * This relies on there being no overlap between modules or config vars added by
1512 * the SpecialPage and those added by parser extensions. If there is overlap,
1513 * then arise and break one or both sides. This is expected and unsupported.
1514 *
1515 * @internal For use by Parser for basic special page transclusion
1516 * @param OutputPage $out
1517 */
1518 public function addOutputPageMetadata( OutputPage $out ): void {
1519 // This should eventually use the same merge mechanism used
1520 // internally to merge ParserOutputs together.
1521 // (ie: $this->mergeHtmlMetaDataFrom( $out->getMetadata() )
1522 // once preventClickjacking, moduleStyles, modules, jsconfigvars,
1523 // and head items are moved to OutputPage::$metadata)
1524
1525 // Take the strictest click-jacking policy. This is to ensure any one-click features
1526 // such as patrol or rollback on the transcluded special page will result in the wiki page
1527 // disallowing embedding in cross-origin iframes. Articles are generally allowed to be
1528 // embedded. Pages that transclude special pages are expected to be user pages or
1529 // other non-content pages that content re-users won't discover or care about.
1530 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
1531
1532 $this->addModuleStyles( $out->getModuleStyles() );
1533
1534 // TODO: Figure out if style modules suffice, or whether the below is needed as well.
1535 // Are there special pages that permit transcluding/including and also have JS modules
1536 // that should be activate on the host page?
1537 $this->addModules( $out->getModules() );
1538 $this->mJsConfigVars = self::mergeMapStrategy(
1539 $this->mJsConfigVars, $out->getJsConfigVars()
1540 );
1541 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
1542 }
1543
1544 /**
1545 * Override the title to be used for display
1546 *
1547 * @note this is assumed to have been validated
1548 * (check equal normalisation, etc.)
1549 *
1550 * @note this is expected to be safe HTML,
1551 * ready to be served to the client.
1552 *
1553 * @param string $text Desired title text
1554 */
1555 public function setDisplayTitle( $text ): void {
1556 $this->setTitleText( $text );
1557 $this->setPageProperty( 'displaytitle', $text );
1558 }
1559
1560 /**
1561 * Get the title to be used for display.
1562 *
1563 * As per the contract of setDisplayTitle(), this is safe HTML,
1564 * ready to be served to the client.
1565 *
1566 * @return string|false HTML
1567 */
1568 public function getDisplayTitle() {
1569 $t = $this->getTitleText();
1570 if ( $t === '' ) {
1571 return false;
1572 }
1573 return $t;
1574 }
1575
1576 /**
1577 * Get the page used as context for creating this output.
1578 *
1579 * The displayed page title may differ, see ::getDisplayTitle(), but
1580 * this is the context object, corresponding to Parser::getPage().
1581 *
1582 * @since 1.46 (also backported to 1.43.7, 1.44.4, 1.45.2)
1583 */
1584 public function getTitle(): ?ParsoidLinkTarget {
1585 $ns = $this->getExtensionData( 'core:title-ns' );
1586 $dbkey = $this->getExtensionData( 'core:title-dbkey' );
1587 if ( $dbkey !== null ) {
1588 return new TitleValue( $ns ?? NS_MAIN, $dbkey );
1589 }
1590 // Backward-compatibility with cache contents generated by MW < 1.46
1591 $dbkey = $this->getExtensionData( 'parsoid:title-dbkey' );
1592 if ( $dbkey !== null ) {
1593 // This is a prefixed DB key w/ localized namespace
1594 $titleFactory = MediaWikiServices::getInstance()->getTitleFactory();
1595 return $titleFactory->newFromDBkey( $dbkey );
1596 }
1597 return null;
1598 }
1599
1600 /**
1601 * Get the primary language code of the output.
1602 *
1603 * This returns the primary language of the output, including
1604 * any LanguageConverter variant applied.
1605 *
1606 * NOTE: This may differ from the wiki's default content language
1607 * ($wgLanguageCode, MediaWikiServices::getContentLanguage), because
1608 * each page may have its own "page language" set (PageStoreRecord,
1609 * Title::getDbPageLanguageCode, ContentHandler::getPageLanguage).
1610 *
1611 * NOTE: This may differ from the "page language" when parsing
1612 * user interface messages, in which case this reflects the user
1613 * language (including any variant preference).
1614 *
1615 * NOTE: This may differ from the Parser's "target language" that was
1616 * set while the Parser was parsing the page, because the final output
1617 * is converted to the current user's preferred LanguageConverter variant
1618 * (assuming this is a variant of the target language).
1619 * See Parser::getTargetLanguageConverter()->getPreferredVariant(); use
1620 * LanguageFactory::getParentLanguage() on the language code to obtain
1621 * the base language code. LanguageConverter::getPreferredVariant()
1622 * depends on the global RequestContext for the URL and the User
1623 * language preference.
1624 *
1625 * Finally, note that a single ParserOutput object may contain
1626 * HTML content in multiple different languages and directions
1627 * (T114640). Authors of wikitext and of parser extensions are
1628 * expected to mark such subtrees with a `lang` attribute (set to
1629 * a BCP-47 value, see Language::toBcp47Code()) and a corresponding
1630 * `dir` attribute (see Language::getDir()). This method returns
1631 * the language code for wrapper of the HTML content.
1632 *
1633 * @see Parser::internalParseHalfParsed
1634 * @since 1.40
1635 * @return ?Bcp47Code The primary language for this output,
1636 * or `null` if a language was not set.
1637 */
1638 public function getLanguage(): ?Bcp47Code {
1639 // This information is temporarily stored in extension data (T303329)
1640 $code = $this->getExtensionData( 'core:target-lang-variant' );
1641 // This is null if the ParserOutput was cached by MW 1.40 or earlier,
1642 // or not constructed by Parser/ParserCache.
1643 return $code === null ? null : new Bcp47CodeValue( $code );
1644 }
1645
1646 /**
1647 * Set the primary language of the output.
1648 *
1649 * See the discussion and caveats in ::getLanguage().
1650 *
1651 * @param Bcp47Code $lang The primary language for this output, including
1652 * any variant specification.
1653 * @since 1.40
1654 */
1655 public function setLanguage( Bcp47Code $lang ): void {
1656 $this->setExtensionData( 'core:target-lang-variant', $lang->toBcp47Code() );
1657 }
1658
1659 /**
1660 * Return an HTML prefix to be applied on redirect pages, or null
1661 * if this is not a redirect.
1662 * @return ?string HTML to prepend to redirect pages, or null
1663 * @internal
1664 */
1665 public function getRedirectHeader(): ?string {
1666 return $this->getExtensionData( 'core:redirect-header' );
1667 }
1668
1669 /**
1670 * Set an HTML prefix to be applied on redirect pages.
1671 * @param string $html HTML to prepend to redirect pages
1672 */
1673 public function setRedirectHeader( string $html ): void {
1674 $this->setExtensionData( 'core:redirect-header', $html );
1675 }
1676
1677 /**
1678 * Store a unique rendering id for this ParserOutput. This is used
1679 * whenever a client needs to record a dependency on a specific parse.
1680 * It is typically set only when a parser output is cached.
1681 *
1682 * @param string $renderId a UUID identifying a specific parse
1683 * @internal
1684 */
1685 public function setRenderId( string $renderId ): void {
1686 $this->setExtensionData( 'core:render-id', $renderId );
1687 }
1688
1689 /**
1690 * Return the unique rendering id for this ParserOutput. This is used
1691 * whenever a client needs to record a dependency on a specific parse.
1692 *
1693 * @return string|null
1694 * @internal
1695 */
1696 public function getRenderId(): ?string {
1697 // Backward-compatibility with old cache contents
1698 // Can be removed after parser cache contents have expired
1699 $old = $this->getExtensionData( 'parsoid-render-id' );
1700 if ( $old !== null ) {
1701 return ParsoidRenderId::newFromKey( $old )->getUniqueID();
1702 }
1703 return $this->getExtensionData( 'core:render-id' );
1704 }
1705
1706 /**
1707 * @return string[] List of flags signifying special cases
1708 * @internal
1709 */
1710 public function getAllFlags(): array {
1711 return array_keys( $this->mFlags );
1712 }
1713
1714 /**
1715 * Set a page property to be stored in the page_props database table.
1716 *
1717 * page_props is a key-value store indexed by the page ID. This allows
1718 * the parser to set a property on a page which can then be quickly
1719 * retrieved given the page ID or via a DB join when given the page
1720 * title.
1721 *
1722 * Since 1.23, page_props are also indexed by numeric value, to allow
1723 * for efficient "top k" queries of pages wrt a given property.
1724 * This only works if the value is passed as a int, float, or
1725 * bool. Since 1.42 you should use ::setNumericPageProperty()
1726 * if you want your page property value to be indexed, which will ensure
1727 * that the value is of the proper type.
1728 *
1729 * setPageProperty() is thus used to propagate properties from the parsed
1730 * page to request contexts other than a page view of the currently parsed
1731 * article.
1732 *
1733 * Some applications examples:
1734 *
1735 * * To implement hidden categories, hiding pages from category listings
1736 * by storing a page property.
1737 *
1738 * * Overriding the displayed article title (ParserOutput::setDisplayTitle()).
1739 *
1740 * * To implement image tagging, for example displaying an icon on an
1741 * image thumbnail to indicate that it is listed for deletion on
1742 * Wikimedia Commons.
1743 * This is not actually implemented, yet but would be pretty cool.
1744 *
1745 * @note Use of non-scalar values (anything other than
1746 * `string|int|float|bool`) has been deprecated in 1.42.
1747 * Although any JSON-serializable value can be stored/fetched in
1748 * ParserOutput, when the values are stored to the database
1749 * (in `deferred/LinksUpdate/PagePropsTable.php`) they will be
1750 * converted: booleans will be converted to '0' and '1', null
1751 * will become '', and everything else will be cast to string
1752 * (not JSON-serialized). Page properties obtained from the
1753 * PageProps service will thus always be strings.
1754 *
1755 * @note The sort key stored in the database *will be NULL* unless
1756 * the value passed here is an `int|float|bool`. If you *do not*
1757 * want your property *value* indexed and sorted (for example, the
1758 * value is a title string which can be numeric but only
1759 * incidentally, like when it gets retrieved from an array key)
1760 * be sure to cast to string or use
1761 * `::setUnsortedPageProperty()`. If you *do* want your property
1762 * *value* indexed and sorted, you should use
1763 * `::setNumericPageProperty()` instead as this will ensure the
1764 * value type is correct. Note that either way it is possible to
1765 * efficiently look up all the pages with a certain property; we
1766 * are only talking about sorting the *values* assigned to the
1767 * property, for example for a "top N values of the property"
1768 * query.
1769 *
1770 * @note Note that `::getPageProperty()`/`::setPageProperty()` do
1771 * not do any conversions themselves; you should therefore be
1772 * careful to distinguish values returned from the PageProp
1773 * service (always strings) from values retrieved from a
1774 * ParserOutput.
1775 *
1776 * @note Do not use setPageProperty() to set a property which is only used
1777 * in a context where the ParserOutput object itself is already available,
1778 * for example a normal page view. There is no need to save such a property
1779 * in the database since the text is already parsed; use
1780 * ::setExtensionData() instead.
1781 *
1782 * @par Example:
1783 * @code
1784 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1785 * @endcode
1786 *
1787 * And then later, in OutputPageParserOutput or similar:
1788 *
1789 * @par Example:
1790 * @code
1791 * $output->getExtensionData( 'my_ext_foo' );
1792 * @endcode
1793 *
1794 * @note The use of `null` as a value is deprecated since 1.42; use
1795 * the empty string instead if you need a placeholder value, or
1796 * ::unsetPageProperty() if you mean to remove a page property.
1797 *
1798 * @note The use of non-string values is deprecated since 1.42; if you
1799 * need an page property value with a sort index
1800 * use ::setNumericPageProperty().
1801 *
1802 * @param string $name
1803 * @param ?scalar $value
1804 * @since 1.38
1805 */
1806 public function setPageProperty( string $name, $value ): void {
1807 if ( $value === null ) {
1808 // Use an empty string instead.
1809 wfDeprecated( __METHOD__ . " with null value for $name", '1.42' );
1810 } elseif ( !is_scalar( $value ) ) {
1811 // Use ::setExtensionData() instead.
1812 wfDeprecated( __METHOD__ . " with non-scalar value for $name", '1.42' );
1813 } elseif ( !is_string( $value ) ) {
1814 // Use ::setNumericPageProperty() instead.
1815 wfDeprecated( __METHOD__ . " with non-string value for $name", '1.42' );
1816 }
1817 $this->mProperties[$name] = $value;
1818 }
1819
1820 /**
1821 * Set a numeric page property whose *value* is intended to be sorted
1822 * and indexed. The sort key used for the property will be the value,
1823 * coerced to a number.
1824 *
1825 * See `::setPageProperty()` for details.
1826 *
1827 * In the future, we may allow the value to be specified independent
1828 * of sort key (T357783).
1829 *
1830 * @param string $propName The name of the page property
1831 * @param int|float|string $numericValue the numeric value
1832 * @since 1.42
1833 */
1834 public function setNumericPageProperty( string $propName, $numericValue ): void {
1835 if ( !is_numeric( $numericValue ) ) {
1836 throw new \TypeError( __METHOD__ . " with non-numeric value" );
1837 }
1838 // Coerce numeric sort key to a number.
1839 $this->mProperties[$propName] = 0 + $numericValue;
1840 }
1841
1842 /**
1843 * Set a page property whose *value* is not intended to be sorted and
1844 * indexed.
1845 *
1846 * See `::setPageProperty()` for details. It is recommended to
1847 * use the empty string if you need a placeholder value (ie, if
1848 * it is the *presence* of the property which is important, not
1849 * the *value* the property is set to).
1850 *
1851 * It is still possible to efficiently look up all the pages with
1852 * a certain property (the "presence" of it *is* indexed; see
1853 * Special:PagesWithProp, list=pageswithprop).
1854 *
1855 * @param string $propName The name of the page property
1856 * @param string $value Optional value; defaults to the empty string.
1857 * @since 1.42
1858 */
1859 public function setUnsortedPageProperty( string $propName, string $value = '' ): void {
1860 $this->mProperties[$propName] = $value;
1861 }
1862
1863 /**
1864 * Look up a page property.
1865 * @param string $name The page property name to look up.
1866 * @return ?scalar The value previously set using
1867 * ::setPageProperty(), ::setUnsortedPageProperty(), or
1868 * ::setNumericPageProperty().
1869 * Returns null if no value was set for the given property name.
1870 *
1871 * @note You would need to use ::getPageProperties() to test for an
1872 * explicitly-set null value; but see the note in ::setPageProperty()
1873 * deprecating the use of null values.
1874 * @since 1.38
1875 */
1876 public function getPageProperty( string $name ) {
1877 return $this->mProperties[$name] ?? null;
1878 }
1879
1880 /**
1881 * Remove a page property.
1882 * @param string $name The page property name.
1883 * @since 1.38
1884 */
1885 public function unsetPageProperty( string $name ): void {
1886 unset( $this->mProperties[$name] );
1887 }
1888
1889 /**
1890 * Return all the page properties set on this ParserOutput.
1891 * @return array<string,?scalar>
1892 * @since 1.38
1893 */
1894 public function getPageProperties(): array {
1895 if ( !isset( $this->mProperties ) ) {
1896 $this->mProperties = [];
1897 }
1898 return $this->mProperties;
1899 }
1900
1901 /**
1902 * Provides a uniform interface to various boolean flags stored
1903 * in the ParserOutput. Flags internal to MediaWiki core should
1904 * have names which are constants in ParserOutputFlags. Extensions
1905 * should use ::setExtensionData() rather than creating new flags
1906 * with ::setOutputFlag() in order to prevent namespace conflicts.
1907 *
1908 * Flags are always combined with OR. That is, the flag is set in
1909 * the resulting ParserOutput if the flag is set in *any* of the
1910 * fragments composing the ParserOutput.
1911 *
1912 * @note The combination policy means that a ParserOutput may end
1913 * up with both INDEX_POLICY and NO_INDEX_POLICY set. It is
1914 * expected that NO_INDEX_POLICY "wins" in that case. (T16899)
1915 * (This resolution is implemented in ::getIndexPolicy().)
1916 *
1917 * @param string $name A flag name
1918 * @param bool $val
1919 * @since 1.38
1920 */
1921 public function setOutputFlag( string $name, bool $val = true ): void {
1922 switch ( $name ) {
1923 case ParserOutputFlags::NO_GALLERY:
1924 $this->setNoGallery( $val );
1925 break;
1926
1927 case ParserOutputFlags::ENABLE_OOUI:
1928 $this->setEnableOOUI( $val );
1929 break;
1930
1931 case ParserOutputFlags::NO_INDEX_POLICY:
1932 $this->mNoIndexSet = $val;
1933 break;
1934
1935 case ParserOutputFlags::INDEX_POLICY:
1936 $this->mIndexSet = $val;
1937 break;
1938
1939 case ParserOutputFlags::NEW_SECTION:
1940 $this->setNewSection( $val );
1941 break;
1942
1943 case ParserOutputFlags::HIDE_NEW_SECTION:
1944 $this->setHideNewSection( $val );
1945 break;
1946
1947 case ParserOutputFlags::PREVENT_CLICKJACKING:
1948 $this->setPreventClickjacking( $val );
1949 break;
1950
1951 default:
1952 if ( $val ) {
1953 $this->mFlags[$name] = true;
1954 } else {
1955 unset( $this->mFlags[$name] );
1956 }
1957 break;
1958 }
1959 }
1960
1961 /**
1962 * Provides a uniform interface to various boolean flags stored
1963 * in the ParserOutput. Flags internal to MediaWiki core should
1964 * have names which are constants in ParserOutputFlags. Extensions
1965 * should only use ::getOutputFlag() to query flags defined in
1966 * ParserOutputFlags in core; they should use ::getExtensionData()
1967 * to define their own flags.
1968 *
1969 * @param string $name A flag name
1970 * @return bool The flag value
1971 * @since 1.38
1972 */
1973 public function getOutputFlag( string $name ): bool {
1974 switch ( $name ) {
1975 case ParserOutputFlags::NO_GALLERY:
1976 return $this->getNoGallery();
1977
1978 case ParserOutputFlags::ENABLE_OOUI:
1979 return $this->getEnableOOUI();
1980
1981 case ParserOutputFlags::INDEX_POLICY:
1982 return $this->mIndexSet;
1983
1984 case ParserOutputFlags::NO_INDEX_POLICY:
1985 return $this->mNoIndexSet;
1986
1987 case ParserOutputFlags::NEW_SECTION:
1988 return $this->getNewSection();
1989
1990 case ParserOutputFlags::HIDE_NEW_SECTION:
1991 return $this->getHideNewSection();
1992
1993 case ParserOutputFlags::PREVENT_CLICKJACKING:
1994 return $this->getPreventClickjacking();
1995
1996 default:
1997 return isset( $this->mFlags[$name] );
1998
1999 }
2000 }
2001
2002 /**
2003 * Provides a uniform interface to various string sets stored
2004 * in the ParserOutput. String sets internal to MediaWiki core should
2005 * have names which are constants in ParserOutputStringSets. Extensions
2006 * should use ::appendExtensionData() rather than creating new string sets
2007 * with ::appendOutputStrings() in order to prevent namespace conflicts.
2008 *
2009 * @param string $name A string set name
2010 * @param string[] $value
2011 * @since 1.41
2012 */
2013 public function appendOutputStrings( string $name, array $value ): void {
2014 switch ( $name ) {
2015 case ParserOutputStringSets::MODULE:
2016 $this->addModules( $value );
2017 break;
2018 case ParserOutputStringSets::MODULE_STYLE:
2019 $this->addModuleStyles( $value );
2020 break;
2021 case ParserOutputStringSets::EXTRA_CSP_DEFAULT_SRC:
2022 foreach ( $value as $v ) {
2023 $this->addExtraCSPDefaultSrc( $v );
2024 }
2025 break;
2026 case ParserOutputStringSets::EXTRA_CSP_SCRIPT_SRC:
2027 foreach ( $value as $v ) {
2028 $this->addExtraCSPScriptSrc( $v );
2029 }
2030 break;
2031 case ParserOutputStringSets::EXTRA_CSP_STYLE_SRC:
2032 foreach ( $value as $v ) {
2033 $this->addExtraCSPStyleSrc( $v );
2034 }
2035 break;
2036 default:
2037 throw new UnexpectedValueException( "Unknown output string set name $name" );
2038 }
2039 }
2040
2041 /**
2042 * Provides a uniform interface to various boolean string sets stored
2043 * in the ParserOutput. String sets internal to MediaWiki core should
2044 * have names which are constants in ParserOutputStringSets. Extensions
2045 * should only use ::getOutputStrings() to query string sets defined in
2046 * ParserOutputStringSets in core; they should use ::appendExtensionData()
2047 * to define their own string sets.
2048 *
2049 * @param string $name A string set name
2050 * @return string[] The string set value
2051 * @since 1.41
2052 */
2053 public function getOutputStrings( string $name ): array {
2054 switch ( $name ) {
2055 case ParserOutputStringSets::MODULE:
2056 return $this->getModules();
2057 case ParserOutputStringSets::MODULE_STYLE:
2058 return $this->getModuleStyles();
2059 case ParserOutputStringSets::EXTRA_CSP_DEFAULT_SRC:
2060 return $this->getExtraCSPDefaultSrcs();
2061 case ParserOutputStringSets::EXTRA_CSP_SCRIPT_SRC:
2062 return $this->getExtraCSPScriptSrcs();
2063 case ParserOutputStringSets::EXTRA_CSP_STYLE_SRC:
2064 return $this->getExtraCSPStyleSrcs();
2065 default:
2066 throw new UnexpectedValueException( "Unknown output string set name $name" );
2067 }
2068 }
2069
2070 /**
2071 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
2072 * the ParserOutput object for later use during page output. The data will be cached along with
2073 * the ParserOutput object, but unlike data set using setPageProperty(), it is not recorded in the
2074 * database.
2075 *
2076 * This method is provided to overcome the unsafe practice of attaching extra information to a
2077 * ParserObject by directly assigning member variables.
2078 *
2079 * To use setExtensionData() to pass extension information from a hook inside the parser to a
2080 * hook in the page output, use this in the parser hook:
2081 *
2082 * @par Example:
2083 * @code
2084 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
2085 * @endcode
2086 *
2087 * And then later, in OutputPageParserOutput or similar:
2088 *
2089 * @par Example:
2090 * @code
2091 * $output->getExtensionData( 'my_ext_foo' );
2092 * @endcode
2093 *
2094 * In MediaWiki 1.20 and older, you have to use a custom member variable
2095 * within the ParserOutput object:
2096 *
2097 * @par Example:
2098 * @code
2099 * $parser->getOutput()->my_ext_foo = '...';
2100 * @endcode
2101 *
2102 * @note Only scalar values, e.g. numbers, strings, arrays or MediaWiki\Json\JsonDeserializable
2103 * instances are supported as a value. Attempt to set other class instance as extension data
2104 * will break ParserCache for the page.
2105 *
2106 * @note Since MW 1.38 the practice of setting conflicting values for
2107 * the same key has been deprecated. As with ::setJsConfigVar(), if
2108 * you set the same key multiple times on a ParserOutput, it is expected
2109 * that the value will be identical each time. If you want to collect
2110 * multiple pieces of data under a single key, use ::appendExtensionData().
2111 *
2112 * @param string $key The key for accessing the data. Extensions should take care to avoid
2113 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
2114 *
2115 * @param mixed|JsonDeserializable $value The value to set.
2116 * Setting a value to null is equivalent to removing the value.
2117 * @since 1.21
2118 */
2119 public function setExtensionData( $key, $value ): void {
2120 if (
2121 array_key_exists( $key, $this->mExtensionData ) &&
2122 $this->mExtensionData[$key] !== $value
2123 ) {
2124 // This behavior was deprecated in 1.38. We will eventually
2125 // emit a warning here, then throw an exception.
2126 }
2127 if ( $value === null ) {
2128 unset( $this->mExtensionData[$key] );
2129 } else {
2130 $this->mExtensionData[$key] = $value;
2131 }
2132 }
2133
2134 /**
2135 * Appends arbitrary data to this ParserObject. This can be used
2136 * to store some information in the ParserOutput object for later
2137 * use during page output. The data will be cached along with the
2138 * ParserOutput object, but unlike data set using
2139 * setPageProperty(), it is not recorded in the database.
2140 *
2141 * See ::setExtensionData() for more details on rationale and use.
2142 *
2143 * In order to provide for out-of-order/asynchronous/incremental
2144 * parsing, this method appends values to a set. See
2145 * ::setExtensionData() for the flag-like version of this method.
2146 *
2147 * @note Only values which can be array keys are currently supported
2148 * as values.
2149 *
2150 * @param string $key The key for accessing the data. Extensions should take care to avoid
2151 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
2152 *
2153 * @param int|string $value The value to append to the list.
2154 * @param string $strategy Merge strategy:
2155 * only MW_MERGE_STRATEGY_UNION is currently supported and external callers
2156 * should treat this parameter as @internal at this time and omit it.
2157 * @since 1.38
2158 */
2159 public function appendExtensionData(
2160 string $key,
2161 $value,
2162 string $strategy = self::MW_MERGE_STRATEGY_UNION
2163 ): void {
2164 if ( $strategy !== self::MW_MERGE_STRATEGY_UNION ) {
2165 throw new InvalidArgumentException( "Unknown merge strategy $strategy." );
2166 }
2167 if ( !array_key_exists( $key, $this->mExtensionData ) ) {
2168 $this->mExtensionData[$key] = [
2169 // Indicate how these values are to be merged.
2170 self::MW_MERGE_STRATEGY_KEY => $strategy,
2171 ];
2172 } elseif ( !is_array( $this->mExtensionData[$key] ) ) {
2173 throw new InvalidArgumentException( "Mixing set and append for $key" );
2174 } elseif ( ( $this->mExtensionData[$key][self::MW_MERGE_STRATEGY_KEY] ?? null ) !== $strategy ) {
2175 throw new InvalidArgumentException( "Conflicting merge strategies for $key" );
2176 }
2177 $this->mExtensionData[$key][$value] = true;
2178 }
2179
2180 /**
2181 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
2182 * Typically, such data would be set while parsing the page, e.g. by a parser function.
2183 *
2184 * @since 1.21
2185 *
2186 * @param string $key The key to look up.
2187 *
2188 * @return mixed|null The value previously set for the given key using setExtensionData()
2189 * or null if no value was set for this key.
2190 */
2191 public function getExtensionData( $key ) {
2192 $value = $this->mExtensionData[$key] ?? null;
2193 if ( is_array( $value ) ) {
2194 // Don't expose our internal merge strategy key.
2195 unset( $value[self::MW_MERGE_STRATEGY_KEY] );
2196 }
2197 return $value;
2198 }
2199
2200 private static function getTimes( $clock = null ): array {
2201 $ret = [];
2202 if ( !$clock || $clock === 'wall' ) {
2203 $ret['wall'] = microtime( true );
2204 }
2205 if ( !$clock || $clock === 'cpu' ) {
2206 $ru = getrusage( 0 /* RUSAGE_SELF */ );
2207 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
2208 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
2209 }
2210 return $ret;
2211 }
2212
2213 /**
2214 * Resets the parse start timestamps for future calls to getTimeSinceStart()
2215 * and recordTimeProfile().
2216 *
2217 * @since 1.22
2218 */
2219 public function resetParseStartTime(): void {
2220 $this->mParseStartTime = self::getTimes();
2221 $this->mTimeProfile = [];
2222 }
2223
2224 /**
2225 * Unset the parse start time.
2226 *
2227 * This is intended for testing purposes only, in order to avoid
2228 * spurious differences between testing outputs created at different
2229 * times.
2230 *
2231 * @since 1.43
2232 */
2233 public function clearParseStartTime(): void {
2234 $this->mParseStartTime = [];
2235 }
2236
2237 /**
2238 * Record the time since resetParseStartTime() was last called.
2239 * The recorded time can be accessed using getTimeProfile().
2240 *
2241 * After resetParseStartTime() was called, the first call to recordTimeProfile()
2242 * will record the time profile. Subsequent calls to recordTimeProfile() will have
2243 * no effect until resetParseStartTime() is called again.
2244 *
2245 * @since 1.42
2246 */
2247 public function recordTimeProfile() {
2248 if ( !$this->mParseStartTime ) {
2249 // If resetParseStartTime was never called, there is nothing to record
2250 return;
2251 }
2252
2253 if ( $this->mTimeProfile !== [] ) {
2254 // Don't override the times recorded by the previous call to recordTimeProfile().
2255 return;
2256 }
2257
2258 $now = self::getTimes();
2259 $this->mTimeProfile = [
2260 'wall' => $now['wall'] - $this->mParseStartTime['wall'],
2261 'cpu' => $now['cpu'] - $this->mParseStartTime['cpu'],
2262 ];
2263 }
2264
2265 /**
2266 * Returns the time that elapsed between the most recent call to resetParseStartTime()
2267 * and the first call to recordTimeProfile() after that.
2268 *
2269 * Clocks available are:
2270 * - wall: Wall clock time
2271 * - cpu: CPU time (requires getrusage)
2272 *
2273 * If recordTimeProfile() has noit been called since the most recent call to
2274 * resetParseStartTime(), or if resetParseStartTime() was never called, then
2275 * this method will return null.
2276 *
2277 * @param string $clock
2278 *
2279 * @since 1.42
2280 * @return float|null
2281 */
2282 public function getTimeProfile( string $clock ) {
2283 return $this->mTimeProfile[ $clock ] ?? null;
2284 }
2285
2286 /**
2287 * Returns the time since resetParseStartTime() was last called
2288 *
2289 * Clocks available are:
2290 * - wall: Wall clock time
2291 * - cpu: CPU time (requires getrusage)
2292 *
2293 * @since 1.22
2294 * @deprecated since 1.42, use getTimeProfile() instead.
2295 * @param string $clock
2296 * @return float|null
2297 */
2298 public function getTimeSinceStart( $clock ) {
2299 wfDeprecated( __METHOD__, '1.42' );
2300
2301 if ( !isset( $this->mParseStartTime[$clock] ) ) {
2302 return null;
2303 }
2304
2305 $end = self::getTimes( $clock );
2306 return $end[$clock] - $this->mParseStartTime[$clock];
2307 }
2308
2309 /**
2310 * Sets parser limit report data for a key
2311 *
2312 * The key is used as the prefix for various messages used for formatting:
2313 * - $key: The label for the field in the limit report
2314 * - $key-value-text: Message used to format the value in the "NewPP limit
2315 * report" HTML comment. If missing, uses $key-format.
2316 * - $key-value-html: Message used to format the value in the preview
2317 * limit report table. If missing, uses $key-format.
2318 * - $key-value: Message used to format the value. If missing, uses "$1".
2319 *
2320 * Note that all values are interpreted as wikitext, and so should be
2321 * encoded with htmlspecialchars() as necessary, but should avoid complex
2322 * HTML for display in the "NewPP limit report" comment.
2323 *
2324 * @since 1.22
2325 * @param string $key Message key
2326 * @param mixed $value Appropriate for Message::params()
2327 */
2328 public function setLimitReportData( $key, $value ): void {
2329 $this->mLimitReportData[$key] = $value;
2330
2331 if ( is_array( $value ) ) {
2332 if ( array_keys( $value ) === [ 0, 1 ]
2333 && is_numeric( $value[0] )
2334 && is_numeric( $value[1] )
2335 ) {
2336 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
2337 } else {
2338 $data = $value;
2339 }
2340 } else {
2341 $data = $value;
2342 }
2343
2344 if ( strpos( $key, '-' ) ) {
2345 [ $ns, $name ] = explode( '-', $key, 2 );
2346 $this->mLimitReportJSData[$ns][$name] = $data;
2347 } else {
2348 $this->mLimitReportJSData[$key] = $data;
2349 }
2350 }
2351
2352 /**
2353 * Check whether the cache TTL was lowered from the site default.
2354 *
2355 * When content is determined by more than hard state (e.g. page edits),
2356 * such as template/file transclusions based on the current timestamp or
2357 * extension tags that generate lists based on queries, this return true.
2358 *
2359 * This method mainly exists to facilitate the logic in
2360 * WikiPage::triggerOpportunisticLinksUpdate. As such, beware that reducing the TTL for
2361 * reasons that do not relate to "dynamic content", may have the side-effect of incurring
2362 * more RefreshLinksJob executions.
2363 *
2364 * @internal For use by Parser and WikiPage
2365 * @since 1.37
2366 * @return bool
2367 */
2368 public function hasReducedExpiry(): bool {
2369 $parserCacheExpireTime = MediaWikiServices::getInstance()->getMainConfig()->get(
2370 MainConfigNames::ParserCacheExpireTime );
2371
2372 return $this->getCacheExpiry() < $parserCacheExpireTime;
2373 }
2374
2375 /**
2376 * Set the prevent-clickjacking flag. If set this will cause an
2377 * `X-Frame-Options` header appropriate for edit pages to be sent.
2378 * The header value is controlled by `$wgEditPageFrameOptions`.
2379 *
2380 * This is the default for special pages. If you display a CSRF-protected
2381 * form on an ordinary view page, then you need to call this function
2382 * with `$flag = true`.
2383 *
2384 * @param bool $flag New flag value
2385 * @since 1.38
2386 */
2387 public function setPreventClickjacking( bool $flag ): void {
2388 $this->mPreventClickjacking = $flag;
2389 }
2390
2391 /**
2392 * Get the prevent-clickjacking flag.
2393 *
2394 * @return bool Flag value
2395 * @since 1.38
2396 * @see ::setPreventClickjacking
2397 */
2398 public function getPreventClickjacking(): bool {
2399 return $this->mPreventClickjacking;
2400 }
2401
2402 /**
2403 * Lower the runtime adaptive TTL to at most this value
2404 *
2405 * @param int $ttl
2406 * @since 1.28
2407 */
2408 public function updateRuntimeAdaptiveExpiry( $ttl ): void {
2409 $this->mMaxAdaptiveExpiry = min( $ttl, $this->mMaxAdaptiveExpiry );
2410 $this->updateCacheExpiry( $ttl );
2411 }
2412
2413 /**
2414 * Add an extra value to Content-Security-Policy default-src directive
2415 *
2416 * Call this if you are including a resource (e.g. image) from a third party domain.
2417 * This is used for all source types except style and script.
2418 *
2419 * @since 1.35
2420 * @param string $src CSP source e.g. example.com
2421 */
2422 public function addExtraCSPDefaultSrc( $src ): void {
2423 $this->mExtraDefaultSrcs[] = $src;
2424 }
2425
2426 /**
2427 * Add an extra value to Content-Security-Policy style-src directive
2428 *
2429 * @since 1.35
2430 * @param string $src CSP source e.g. example.com
2431 */
2432 public function addExtraCSPStyleSrc( $src ): void {
2433 $this->mExtraStyleSrcs[] = $src;
2434 }
2435
2436 /**
2437 * Add an extra value to Content-Security-Policy script-src directive
2438 *
2439 * Call this if you are loading third-party Javascript
2440 *
2441 * @since 1.35
2442 * @param string $src CSP source e.g. example.com
2443 */
2444 public function addExtraCSPScriptSrc( $src ): void {
2445 $this->mExtraScriptSrcs[] = $src;
2446 }
2447
2448 /**
2449 * Call this when parsing is done to lower the TTL based on low parse times
2450 *
2451 * @since 1.28
2452 */
2453 public function finalizeAdaptiveCacheExpiry(): void {
2454 if ( is_infinite( $this->mMaxAdaptiveExpiry ) ) {
2455 return; // not set
2456 }
2457
2458 $runtime = $this->getTimeProfile( 'wall' );
2459 if ( is_float( $runtime ) ) {
2460 $slope = ( self::SLOW_AR_TTL - self::FAST_AR_TTL )
2461 / ( self::PARSE_SLOW_SEC - self::PARSE_FAST_SEC );
2462 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
2463 $point = self::SLOW_AR_TTL - self::PARSE_SLOW_SEC * $slope;
2464
2465 $adaptiveTTL = min(
2466 max( $slope * $runtime + $point, self::MIN_AR_TTL ),
2467 $this->mMaxAdaptiveExpiry
2468 );
2469 $this->updateCacheExpiry( $adaptiveTTL );
2470 }
2471 }
2472
2473 /**
2474 * Transfer parser options which affect post-processing from ParserOptions
2475 * to this ParserOutput.
2476 * @param ParserOptions $parserOptions
2477 */
2478 public function setFromParserOptions( ParserOptions $parserOptions ) {
2479 // Copied from Parser.php::parse and should probably be abstracted
2480 // into the parent base class (probably as part of T236809)
2481 // Wrap non-interface parser output in a <div> so it can be targeted
2482 // with CSS (T37247)
2483 $class = $parserOptions->getWrapOutputClass();
2484 if ( $class !== false && !$parserOptions->getInterfaceMessage() ) {
2485 $this->addWrapperDivClass( $class );
2486 }
2487
2488 // Record whether we should suppress section edit links
2489 if ( $parserOptions->getSuppressSectionEditLinks() ) {
2490 $this->setOutputFlag( ParserOutputFlags::NO_SECTION_EDIT_LINKS );
2491 }
2492
2493 // Record whether we should wrap sections for collapsing them
2494 if ( $parserOptions->getCollapsibleSections() ) {
2495 $this->setOutputFlag( ParserOutputFlags::COLLAPSIBLE_SECTIONS );
2496 }
2497
2498 // Record whether this is a preview parse in the output (T341010)
2499 if ( $parserOptions->getIsPreview() ) {
2500 $this->setOutputFlag( ParserOutputFlags::IS_PREVIEW, true );
2501 // Ensure that previews aren't cacheable, just to be safe.
2502 $this->updateCacheExpiry( 0 );
2503 }
2504 }
2505
2506 public function __sleep() {
2507 return array_filter( array_keys( get_object_vars( $this ) ),
2508 static function ( $field ) {
2509 if ( $field === 'mParseStartTime' || $field === 'mWarningMsgs' ) {
2510 return false;
2511 }
2512 // Unserializing unknown private fields in HHVM causes
2513 // member variables with nulls in their names (T229366)
2514 return strpos( $field, "\0" ) === false;
2515 }
2516 );
2517 }
2518
2519 /**
2520 * Merges internal metadata such as flags, accessed options, and profiling info
2521 * from $source into this ParserOutput. This should be used whenever the state of $source
2522 * has any impact on the state of this ParserOutput.
2523 *
2524 * @param ParserOutput $source
2525 */
2526 public function mergeInternalMetaDataFrom( ParserOutput $source ): void {
2527 $this->mWarnings = self::mergeMap( $this->mWarnings, $source->mWarnings ); // don't use getter
2528 $this->mTimestamp = $this->useMaxValue( $this->mTimestamp, $source->getRevisionTimestamp() );
2529 if ( $source->hasCacheTime() ) {
2530 $sourceCacheTime = $source->getCacheTime();
2531 if (
2532 !$this->hasCacheTime() ||
2533 // "undocumented use of -1 to mean not cacheable"
2534 // deprecated, but still supported by ::setCacheTime()
2535 strval( $sourceCacheTime ) === '-1' ||
2536 (
2537 strval( $this->getCacheTime() ) !== '-1' &&
2538 // use newer of the two times
2539 $this->getCacheTime() < $sourceCacheTime
2540 )
2541 ) {
2542 $this->setCacheTime( $sourceCacheTime );
2543 }
2544 }
2545 if ( $source->getRenderId() !== null ) {
2546 // Final render ID should be a function of all component POs
2547 $rid = ( $this->getRenderId() ?? '' ) . $source->getRenderId();
2548 $this->setRenderId( $rid );
2549 }
2550 if ( $source->getCacheRevisionId() !== null ) {
2551 $sourceCacheRevisionId = $source->getCacheRevisionId();
2552 $thisCacheRevisionId = $this->getCacheRevisionId();
2553 if ( $thisCacheRevisionId === null ) {
2554 $this->setCacheRevisionId( $sourceCacheRevisionId );
2555 } elseif ( $sourceCacheRevisionId !== $thisCacheRevisionId ) {
2556 // May throw an exception here in the future
2557 wfDeprecated(
2558 __METHOD__ . ": conflicting revision IDs " .
2559 "$thisCacheRevisionId and $sourceCacheRevisionId"
2560 );
2561 }
2562 }
2563
2564 foreach ( self::SPECULATIVE_FIELDS as $field ) {
2565 if ( $this->$field && $source->$field && $this->$field !== $source->$field ) {
2566 wfLogWarning( __METHOD__ . ": inconsistent '$field' properties!" );
2567 }
2568 $this->$field = $this->useMaxValue( $this->$field, $source->$field );
2569 }
2570
2571 $this->mParseStartTime = $this->useEachMinValue(
2572 $this->mParseStartTime,
2573 $source->mParseStartTime
2574 );
2575
2576 $this->mTimeProfile = $this->useEachTotalValue(
2577 $this->mTimeProfile,
2578 $source->mTimeProfile
2579 );
2580
2581 $this->mFlags = self::mergeMap( $this->mFlags, $source->mFlags );
2582 $this->mParseUsedOptions = self::mergeMap( $this->mParseUsedOptions, $source->mParseUsedOptions );
2583
2584 // TODO: maintain per-slot limit reports!
2585 if ( !$this->mLimitReportData ) {
2586 $this->mLimitReportData = $source->mLimitReportData;
2587 }
2588 if ( !$this->mLimitReportJSData ) {
2589 $this->mLimitReportJSData = $source->mLimitReportJSData;
2590 }
2591 }
2592
2593 /**
2594 * Merges HTML metadata such as head items, JS config vars, and HTTP cache control info
2595 * from $source into this ParserOutput. This should be used whenever the HTML in $source
2596 * has been somehow merged into the HTML of this ParserOutput.
2597 *
2598 * @param ParserOutput $source
2599 */
2600 public function mergeHtmlMetaDataFrom( ParserOutput $source ): void {
2601 // HTML and HTTP
2602 $this->mHeadItems = self::mergeMixedList( $this->mHeadItems, $source->getHeadItems() );
2603 $this->addModules( $source->getModules() );
2604 $this->addModuleStyles( $source->getModuleStyles() );
2605 $this->mJsConfigVars = self::mergeMapStrategy( $this->mJsConfigVars, $source->mJsConfigVars );
2606 $this->mMaxAdaptiveExpiry = min( $this->mMaxAdaptiveExpiry, $source->mMaxAdaptiveExpiry );
2607 $this->mExtraStyleSrcs = self::mergeList(
2608 $this->mExtraStyleSrcs,
2609 $source->getExtraCSPStyleSrcs()
2610 );
2611 $this->mExtraScriptSrcs = self::mergeList(
2612 $this->mExtraScriptSrcs,
2613 $source->getExtraCSPScriptSrcs()
2614 );
2615 $this->mExtraDefaultSrcs = self::mergeList(
2616 $this->mExtraDefaultSrcs,
2617 $source->getExtraCSPDefaultSrcs()
2618 );
2619
2620 // "noindex" always wins!
2621 $this->mIndexSet = $this->mIndexSet || $source->mIndexSet;
2622 $this->mNoIndexSet = $this->mNoIndexSet || $source->mNoIndexSet;
2623
2624 // Skin control
2625 $this->mNewSection = $this->mNewSection || $source->getNewSection();
2626 $this->mHideNewSection = $this->mHideNewSection || $source->getHideNewSection();
2627 $this->mNoGallery = $this->mNoGallery || $source->getNoGallery();
2628 $this->mEnableOOUI = $this->mEnableOOUI || $source->getEnableOOUI();
2629 $this->mPreventClickjacking = $this->mPreventClickjacking || $source->getPreventClickjacking();
2630
2631 $tocData = $this->getTOCData();
2632 $sourceTocData = $source->getTOCData();
2633 if ( $tocData !== null ) {
2634 if ( $sourceTocData !== null ) {
2635 // T327429: Section merging is broken, since it doesn't respect
2636 // global numbering, but there are tests which expect section
2637 // metadata to be concatenated.
2638 // There should eventually be a deprecation warning here.
2639 foreach ( $sourceTocData->getSections() as $s ) {
2640 $tocData->addSection( $s );
2641 }
2642 }
2643 } elseif ( $sourceTocData !== null ) {
2644 $this->setTOCData( $sourceTocData );
2645 }
2646
2647 // XXX: we don't want to concatenate title text, so first write wins.
2648 // We should use the first *modified* title text, but we don't have the original to check.
2649 if ( $this->mTitleText === null || $this->mTitleText === '' ) {
2650 $this->mTitleText = $source->mTitleText;
2651 }
2652
2653 // class names are stored in array keys
2654 $this->mWrapperDivClasses = self::mergeMap(
2655 $this->mWrapperDivClasses,
2656 $source->mWrapperDivClasses
2657 );
2658
2659 // NOTE: last write wins, same as within one ParserOutput
2660 $this->mIndicators = self::mergeMap( $this->mIndicators, $source->getIndicators() );
2661
2662 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
2663 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
2664 // kinds of extension data to be merged in different ways.
2665 $this->mExtensionData = self::mergeMapStrategy(
2666 $this->mExtensionData,
2667 $source->mExtensionData
2668 );
2669 }
2670
2671 /**
2672 * Merges dependency tracking metadata such as backlinks, images used, and extension data
2673 * from $source into this ParserOutput. This allows dependency tracking to be done for the
2674 * combined output of multiple content slots.
2675 *
2676 * @param ParserOutput $source
2677 */
2678 public function mergeTrackingMetaDataFrom( ParserOutput $source ): void {
2679 foreach ( $source->getLanguageLinks() as $ll ) {
2680 $this->addLanguageLink( $ll );
2681 }
2682 $this->mCategories = self::mergeMap( $this->mCategories, $source->getCategoryMap() );
2683 $this->mLinks = self::merge2D( $this->mLinks, $source->getLinks() );
2684 $this->mTemplates = self::merge2D( $this->mTemplates, $source->getTemplates() );
2685 $this->mTemplateIds = self::merge2D( $this->mTemplateIds, $source->getTemplateIds() );
2686 $this->mImages = self::mergeMap( $this->mImages, $source->getImages() );
2687 $this->mFileSearchOptions = self::mergeMap(
2688 $this->mFileSearchOptions,
2689 $source->getFileSearchOptions()
2690 );
2691 $this->mExternalLinks = self::mergeMap( $this->mExternalLinks, $source->getExternalLinks() );
2692 $this->mInterwikiLinks = self::merge2D(
2693 $this->mInterwikiLinks,
2694 $source->getInterwikiLinks()
2695 );
2696
2697 // TODO: add a $mergeStrategy parameter to setPageProperty to allow different
2698 // kinds of properties to be merged in different ways.
2699 // (Model this after ::appendJsConfigVar(); use ::mergeMapStrategy here)
2700 $this->mProperties = self::mergeMap( $this->mProperties, $source->getPageProperties() );
2701
2702 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
2703 $this->mExtensionData = self::mergeMapStrategy(
2704 $this->mExtensionData,
2705 $source->mExtensionData
2706 );
2707 }
2708
2709 /**
2710 * Adds the metadata collected in this ParserOutput to the supplied
2711 * ContentMetadataCollector. This is similar to ::mergeHtmlMetaDataFrom()
2712 * but in the opposite direction, since ParserOutput is read/write while
2713 * ContentMetadataCollector is write-only.
2714 *
2715 * @param ContentMetadataCollector $metadata
2716 * @since 1.38
2717 */
2718 public function collectMetadata( ContentMetadataCollector $metadata ): void {
2719 // Uniform handling of all boolean flags: they are OR'ed together.
2720 $flags = array_keys(
2721 $this->mFlags + array_flip( ParserOutputFlags::cases() )
2722 );
2723 foreach ( $flags as $name ) {
2724 if ( $this->getOutputFlag( $name ) ) {
2725 $metadata->setOutputFlag( $name );
2726 }
2727 }
2728
2729 // Uniform handling of string sets: they are unioned.
2730 // (This includes modules, style modes, and CSP src.)
2731 foreach ( ParserOutputStringSets::cases() as $name ) {
2732 $metadata->appendOutputStrings(
2733 $name, $this->getOutputStrings( $name )
2734 );
2735 }
2736
2737 foreach ( $this->mCategories as $cat => $key ) {
2738 // Numeric category strings are going to come out of the
2739 // `mCategories` array as ints; cast back to string.
2740 // Also convert back to a LinkTarget!
2741 $lt = TitleValue::tryNew( NS_CATEGORY, (string)$cat );
2742 $metadata->addCategory( $lt, $key );
2743 }
2744
2745 foreach ( $this->mLinks as $ns => $arr ) {
2746 foreach ( $arr as $dbk => $id ) {
2747 // Numeric titles are going to come out of the
2748 // `mLinks` array as ints; cast back to string.
2749 $lt = TitleValue::tryNew( $ns, (string)$dbk );
2750 $metadata->addLink( $lt, $id );
2751 }
2752 }
2753
2754 foreach ( $this->mInterwikiLinks as $prefix => $arr ) {
2755 foreach ( $arr as $dbk => $ignore ) {
2756 $lt = TitleValue::tryNew( NS_MAIN, (string)$dbk, '', $prefix );
2757 $metadata->addLink( $lt );
2758 }
2759 }
2760
2761 foreach ( $this->mLinksSpecial as $dbk => $ignore ) {
2762 // Numeric titles are going to come out of the
2763 // `mLinks` array as ints; cast back to string.
2764 $lt = TitleValue::tryNew( NS_SPECIAL, (string)$dbk );
2765 $metadata->addLink( $lt );
2766 }
2767
2768 foreach ( $this->mImages as $name => $ignore ) {
2769 // Numeric titles come out of mImages as ints.
2770 $lt = TitleValue::tryNew( NS_FILE, (string)$name );
2771 $props = $this->mFileSearchOptions[$name] ?? [];
2772 $metadata->addImage( $lt, $props['time'] ?? null, $props['sha1'] ?? null );
2773 }
2774
2775 foreach ( $this->mLanguageLinkMap as $lang => $title ) {
2776 if ( $title === '|' ) {
2777 continue; // T374736: not a valid language link
2778 }
2779 # language links can have fragments!
2780 [ $title, $frag ] = array_pad( explode( '#', $title, 2 ), 2, '' );
2781 $lt = TitleValue::tryNew( NS_MAIN, $title, $frag, (string)$lang );
2782 $metadata->addLanguageLink( $lt );
2783 }
2784
2785 foreach ( $this->mJsConfigVars as $key => $value ) {
2786 if ( is_array( $value ) && isset( $value[self::MW_MERGE_STRATEGY_KEY] ) ) {
2787 $strategy = $value[self::MW_MERGE_STRATEGY_KEY];
2788 foreach ( $value as $item => $ignore ) {
2789 if ( $item !== self::MW_MERGE_STRATEGY_KEY ) {
2790 $metadata->appendJsConfigVar( $key, $item, $strategy );
2791 }
2792 }
2793 } elseif ( $metadata instanceof ParserOutput &&
2794 array_key_exists( $key, $metadata->mJsConfigVars )
2795 ) {
2796 // This behavior is deprecated, will likely result in
2797 // incorrect output, and we'll eventually emit a
2798 // warning here---but at the moment this is usually
2799 // caused by limitations in Parsoid and/or use of
2800 // the ParserAfterParse hook: T303015#7770480
2801 $metadata->mJsConfigVars[$key] = $value;
2802 } else {
2803 $metadata->setJsConfigVar( $key, $value );
2804 }
2805 }
2806 foreach ( $this->mExtensionData as $key => $value ) {
2807 if ( is_array( $value ) && isset( $value[self::MW_MERGE_STRATEGY_KEY] ) ) {
2808 $strategy = $value[self::MW_MERGE_STRATEGY_KEY];
2809 foreach ( $value as $item => $ignore ) {
2810 if ( $item !== self::MW_MERGE_STRATEGY_KEY ) {
2811 $metadata->appendExtensionData( $key, $item, $strategy );
2812 }
2813 }
2814 } elseif ( $metadata instanceof ParserOutput &&
2815 array_key_exists( $key, $metadata->mExtensionData )
2816 ) {
2817 // This behavior is deprecated, will likely result in
2818 // incorrect output, and we'll eventually emit a
2819 // warning here---but at the moment this is usually
2820 // caused by limitations in Parsoid and/or use of
2821 // the ParserAfterParse hook: T303015#7770480
2822 $metadata->mExtensionData[$key] = $value;
2823 } else {
2824 $metadata->setExtensionData( $key, $value );
2825 }
2826 }
2827 foreach ( $this->mExternalLinks as $url => $ignore ) {
2828 $metadata->addExternalLink( $url );
2829 }
2830 foreach ( $this->mProperties as $prop => $value ) {
2831 if ( is_numeric( $value ) ) {
2832 $metadata->setNumericPageProperty( $prop, $value );
2833 } elseif ( is_string( $value ) ) {
2834 $metadata->setUnsortedPageProperty( $prop, $value );
2835 } else {
2836 // Deprecated, but there are still sites which call
2837 // ::setPageProperty() with "unusual" values (T374046)
2838 $metadata->setPageProperty( $prop, $value );
2839 }
2840 }
2841 foreach ( $this->mWarningMsgs as $msg => $args ) {
2842 $metadata->addWarningMsg( $msg, ...$args );
2843 }
2844 foreach ( $this->mLimitReportData as $key => $value ) {
2845 $metadata->setLimitReportData( $key, $value );
2846 }
2847 foreach ( $this->mIndicators as $id => $content ) {
2848 $metadata->setIndicator( $id, $content );
2849 }
2850
2851 // ParserOutput-only fields; maintained "behind the curtain"
2852 // since Parsoid doesn't have to know about them.
2853 //
2854 // In production use, the $metadata supplied to this method
2855 // will almost always be an instance of ParserOutput, passed to
2856 // Parsoid by core when parsing begins and returned to core by
2857 // Parsoid as a ContentMetadataCollector (Parsoid's name for
2858 // ParserOutput) when DataAccess::parseWikitext() is called.
2859 //
2860 // We may use still Parsoid's StubMetadataCollector for testing or
2861 // when running Parsoid in standalone mode, so forcing a downcast
2862 // here would lose some flexibility.
2863
2864 if ( $metadata instanceof ParserOutput ) {
2865 foreach ( $this->getUsedOptions() as $opt ) {
2866 $metadata->recordOption( $opt );
2867 }
2868 if ( $this->mCacheExpiry !== null ) {
2869 $metadata->updateCacheExpiry( $this->mCacheExpiry );
2870 }
2871 if ( $this->mCacheTime !== '' ) {
2872 $metadata->setCacheTime( $this->mCacheTime );
2873 }
2874 if ( $this->mCacheRevisionId !== null ) {
2875 $metadata->setCacheRevisionId( $this->mCacheRevisionId );
2876 }
2877 // T293514: We should use the first *modified* title text, but
2878 // we don't have the original to check.
2879 $otherTitle = $metadata->getTitleText();
2880 if ( $otherTitle === null || $otherTitle === '' ) {
2881 $metadata->setTitleText( $this->getTitleText() );
2882 }
2883 foreach ( $this->mTemplates as $ns => $arr ) {
2884 foreach ( $arr as $dbk => $page_id ) {
2885 $rev_id = $this->mTemplateIds[$ns][$dbk];
2886 $metadata->addTemplate( TitleValue::tryNew( $ns, (string)$dbk ), $page_id, $rev_id );
2887 }
2888 }
2889 }
2890 }
2891
2892 private static function mergeMixedList( array $a, array $b ): array {
2893 return array_unique( array_merge( $a, $b ), SORT_REGULAR );
2894 }
2895
2896 private static function mergeList( array $a, array $b ): array {
2897 return array_values( array_unique( array_merge( $a, $b ), SORT_REGULAR ) );
2898 }
2899
2900 private static function mergeMap( array $a, array $b ): array {
2901 return array_replace( $a, $b );
2902 }
2903
2904 private static function mergeMapStrategy( array $a, array $b ): array {
2905 foreach ( $b as $key => $bValue ) {
2906 if ( !array_key_exists( $key, $a ) ) {
2907 $a[$key] = $bValue;
2908 } elseif (
2909 is_array( $a[$key] ) &&
2910 isset( $a[$key][self::MW_MERGE_STRATEGY_KEY] ) &&
2911 isset( $bValue[self::MW_MERGE_STRATEGY_KEY] )
2912 ) {
2913 $strategy = $bValue[self::MW_MERGE_STRATEGY_KEY];
2914 if ( $strategy !== $a[$key][self::MW_MERGE_STRATEGY_KEY] ) {
2915 throw new InvalidArgumentException( "Conflicting merge strategy for $key" );
2916 }
2917 if ( $strategy === self::MW_MERGE_STRATEGY_UNION ) {
2918 // Note the array_merge is *not* safe to use here, because
2919 // the $bValue is expected to be a map from items to `true`.
2920 // If the item is a numeric string like '1' then array_merge
2921 // will convert it to an integer and renumber the array!
2922 $a[$key] = array_replace( $a[$key], $bValue );
2923 } else {
2924 throw new InvalidArgumentException( "Unknown merge strategy $strategy" );
2925 }
2926 } else {
2927 $valuesSame = ( $a[$key] === $bValue );
2928 if ( ( !$valuesSame ) &&
2929 is_object( $a[$key] ) &&
2930 is_object( $bValue )
2931 ) {
2932 $jsonCodec = MediaWikiServices::getInstance()->getJsonCodec();
2933 $valuesSame = ( $jsonCodec->serialize( $a[$key] ) === $jsonCodec->serialize( $bValue ) );
2934 }
2935 if ( !$valuesSame ) {
2936 // Silently replace for now; in the future will first emit
2937 // a deprecation warning, and then (later) throw.
2938 $a[$key] = $bValue;
2939 }
2940 }
2941 }
2942 return $a;
2943 }
2944
2945 private static function merge2D( array $a, array $b ): array {
2946 $values = [];
2947 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
2948
2949 foreach ( $keys as $k ) {
2950 if ( empty( $a[$k] ) ) {
2951 $values[$k] = $b[$k];
2952 } elseif ( empty( $b[$k] ) ) {
2953 $values[$k] = $a[$k];
2954 } elseif ( is_array( $a[$k] ) && is_array( $b[$k] ) ) {
2955 $values[$k] = array_replace( $a[$k], $b[$k] );
2956 } else {
2957 $values[$k] = $b[$k];
2958 }
2959 }
2960
2961 return $values;
2962 }
2963
2964 private static function useEachMinValue( array $a, array $b ): array {
2965 $values = [];
2966 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
2967
2968 foreach ( $keys as $k ) {
2969 $values[$k] = min( $a[$k] ?? INF, $b[$k] ?? INF );
2970 }
2971
2972 return $values;
2973 }
2974
2975 private static function useEachTotalValue( array $a, array $b ): array {
2976 $values = [];
2977 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
2978
2979 foreach ( $keys as $k ) {
2980 $values[$k] = ( $a[$k] ?? 0 ) + ( $b[$k] ?? 0 );
2981 }
2982
2983 return $values;
2984 }
2985
2986 private static function useMaxValue( $a, $b ) {
2987 if ( $a === null ) {
2988 return $b;
2989 }
2990
2991 if ( $b === null ) {
2992 return $a;
2993 }
2994
2995 return max( $a, $b );
2996 }
2997
2998 /**
2999 * Returns a JSON serializable structure representing this ParserOutput instance.
3000 * @see ::newFromJsonArray()
3001 *
3002 * @return array
3003 */
3004 public function toJsonArray(): array {
3005 // WARNING: When changing how this class is serialized, follow the instructions
3006 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
3007
3008 $data = [
3009 'Text' => $this->mRawText,
3010 'LanguageLinks' => $this->getLanguageLinks(),
3011 'Categories' => $this->mCategories,
3012 'Indicators' => $this->mIndicators,
3013 'TitleText' => $this->mTitleText,
3014 'Links' => $this->mLinks,
3015 'LinksSpecial' => $this->mLinksSpecial,
3016 'Templates' => $this->mTemplates,
3017 'TemplateIds' => $this->mTemplateIds,
3018 'Images' => $this->mImages,
3019 'FileSearchOptions' => $this->mFileSearchOptions,
3020 'ExternalLinks' => $this->mExternalLinks,
3021 'InterwikiLinks' => $this->mInterwikiLinks,
3022 'NewSection' => $this->mNewSection,
3023 'HideNewSection' => $this->mHideNewSection,
3024 'NoGallery' => $this->mNoGallery,
3025 'HeadItems' => $this->mHeadItems,
3026 'Modules' => array_keys( $this->mModuleSet ),
3027 'ModuleStyles' => array_keys( $this->mModuleStyleSet ),
3028 'JsConfigVars' => $this->mJsConfigVars,
3029 'Warnings' => $this->mWarnings,
3030 'Sections' => $this->getSections(),
3031 'Properties' => self::detectAndEncodeBinary( $this->mProperties ),
3032 'Timestamp' => $this->mTimestamp,
3033 'EnableOOUI' => $this->mEnableOOUI,
3034 'IndexPolicy' => $this->getIndexPolicy(),
3035 // may contain arbitrary structures!
3036 'ExtensionData' => $this->mExtensionData,
3037 'LimitReportData' => $this->mLimitReportData,
3038 'LimitReportJSData' => $this->mLimitReportJSData,
3039 'CacheMessage' => $this->mCacheMessage,
3040 'TimeProfile' => $this->mTimeProfile,
3041 'ParseStartTime' => [], // don't serialize this
3042 'PreventClickjacking' => $this->mPreventClickjacking,
3043 'ExtraScriptSrcs' => $this->mExtraScriptSrcs,
3044 'ExtraDefaultSrcs' => $this->mExtraDefaultSrcs,
3045 'ExtraStyleSrcs' => $this->mExtraStyleSrcs,
3046 'Flags' => $this->mFlags + (
3047 // backward-compatibility: distinguish "no sections" from
3048 // "sections not set" (Will be unnecessary after T327439.)
3049 $this->mTOCData === null ? [] : [ 'mw:toc-set' => true ]
3050 ),
3051 'SpeculativeRevId' => $this->mSpeculativeRevId,
3052 'SpeculativePageIdUsed' => $this->speculativePageIdUsed,
3053 'RevisionTimestampUsed' => $this->revisionTimestampUsed,
3054 'RevisionUsedSha1Base36' => $this->revisionUsedSha1Base36,
3055 'WrapperDivClasses' => $this->mWrapperDivClasses,
3056 ];
3057
3058 // Fill in missing fields from parents. Array addition does not override existing fields.
3059 $data += parent::toJsonArray();
3060
3061 // TODO: make more fields optional!
3062
3063 if ( $this->mMaxAdaptiveExpiry !== INF ) {
3064 // NOTE: JSON can't encode infinity!
3065 $data['MaxAdaptiveExpiry'] = $this->mMaxAdaptiveExpiry;
3066 }
3067
3068 if ( $this->mTOCData ) {
3069 // Temporarily add information from TOCData extension data
3070 // T327439: We should eventually make the entire mTOCData
3071 // serializable
3072 $toc = $this->mTOCData->jsonSerialize();
3073 if ( isset( $toc['extensionData'] ) ) {
3074 $data['TOCExtensionData'] = $toc['extensionData'];
3075 }
3076 }
3077
3078 return $data;
3079 }
3080
3081 public static function newFromJsonArray( array $json ): ParserOutput {
3082 $parserOutput = new ParserOutput();
3083 $parserOutput->initFromJson( $json );
3084 return $parserOutput;
3085 }
3086
3087 /** @inheritDoc */
3088 public static function jsonClassHintFor( string $keyName ) {
3089 return match ( $keyName ) {
3090 'TOCData' => Hint::build( TOCData::class, Hint::ONLY_FOR_DECODE ),
3091 'WarningMsgs' => Hint::build( MessageValue::class, Hint::LIST, Hint::ONLY_FOR_DECODE ),
3092 default => null,
3093 };
3094 }
3095
3096 /**
3097 * Initialize member fields from an array returned by jsonSerialize().
3098 * @param array $jsonData
3099 */
3100 protected function initFromJson( array $jsonData ): void {
3101 parent::initFromJson( $jsonData );
3102
3103 // WARNING: When changing how this class is serialized, follow the instructions
3104 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
3105 // (This includes changing default values when fields are missing.)
3106
3107 $this->mRawText = $jsonData['Text'];
3108 $this->mLanguageLinkMap = [];
3109 foreach ( ( $jsonData['LanguageLinks'] ?? [] ) as $l ) {
3110 $this->addLanguageLink( $l );
3111 }
3112 // Default values should match the property default values.
3113 $this->mCategories = $jsonData['Categories'] ?? [];
3114 $this->mIndicators = $jsonData['Indicators'] ?? [];
3115 $this->mTitleText = $jsonData['TitleText'] ?? '';
3116 $this->mLinks = $jsonData['Links'] ?? [];
3117 $this->mLinksSpecial = $jsonData['LinksSpecial'] ?? [];
3118 $this->mTemplates = $jsonData['Templates'] ?? [];
3119 $this->mTemplateIds = $jsonData['TemplateIds'] ?? [];
3120 $this->mImages = $jsonData['Images'] ?? [];
3121 $this->mFileSearchOptions = $jsonData['FileSearchOptions'] ?? [];
3122 $this->mExternalLinks = $jsonData['ExternalLinks'] ?? [];
3123 $this->mInterwikiLinks = $jsonData['InterwikiLinks'] ?? [];
3124 $this->mHeadItems = $jsonData['HeadItems'] ?? [];
3125 $this->mModuleSet = array_fill_keys( $jsonData['Modules'] ?? [], true );
3126 $this->mModuleStyleSet = array_fill_keys( $jsonData['ModuleStyles'] ?? [], true );
3127 $this->mJsConfigVars = $jsonData['JsConfigVars'] ?? [];
3128 $this->mWarnings = $jsonData['Warnings'] ?? [];
3129
3130 // Set flags stored as properties
3131 $this->mFlags = $jsonData['Flags'] ?? [];
3132 $this->mNoGallery = $jsonData['NoGallery'] ?? false;
3133 $this->mEnableOOUI = $jsonData['EnableOOUI'] ?? false;
3134 $this->setIndexPolicy( $jsonData['IndexPolicy'] ?? '' );
3135 $this->mNewSection = $jsonData['NewSection'] ?? false;
3136 $this->mHideNewSection = $jsonData['HideNewSection'] ?? false;
3137 $this->mPreventClickjacking = $jsonData['PreventClickjacking'] ?? false;
3138 // Set all generic output flags (whether stored as properties or not)
3139 // (This is effectively a logical-OR if these are also serialized
3140 // above.)
3141 foreach ( $jsonData['OutputFlags'] ?? [] as $flag ) {
3142 $this->setOutputFlag( $flag );
3143 }
3144
3145 if ( isset( $jsonData['TOCData'] ) ) {
3146 $this->mTOCData = $jsonData['TOCData'];
3147 // Backward-compatibility with old TOCData encoding (T327439)
3148 // emitted in MW < 1.45
3149 } elseif (
3150 ( $jsonData['Sections'] ?? [] ) !== [] ||
3151 // distinguish "no sections" from "sections not set"
3152 $this->getOutputFlag( 'mw:toc-set' )
3153 ) {
3154 $this->setSections( $jsonData['Sections'] ?? [] );
3155 unset( $this->mFlags['mw:toc-set'] );
3156 if ( isset( $jsonData['TOCExtensionData'] ) ) {
3157 $tocData = $this->getTOCData(); // created by setSections() above
3158 foreach ( $jsonData['TOCExtensionData'] as $key => $value ) {
3159 $tocData->setExtensionData( $key, $value );
3160 }
3161 }
3162 }
3163 $this->mProperties = self::detectAndDecodeBinary( $jsonData['Properties'] ?? [] );
3164 $this->mTimestamp = $jsonData['Timestamp'] ?? null;
3165 $this->mExtensionData = $jsonData['ExtensionData'] ?? [];
3166 $this->mLimitReportData = $jsonData['LimitReportData'] ?? [];
3167 $this->mLimitReportJSData = $jsonData['LimitReportJSData'] ?? [];
3168 $this->mCacheMessage = $jsonData['CacheMessage'] ?? '';
3169 $this->mParseStartTime = []; // invalid after reloading
3170 $this->mTimeProfile = $jsonData['TimeProfile'] ?? [];
3171 $this->mExtraScriptSrcs = $jsonData['ExtraScriptSrcs'] ?? [];
3172 $this->mExtraDefaultSrcs = $jsonData['ExtraDefaultSrcs'] ?? [];
3173 $this->mExtraStyleSrcs = $jsonData['ExtraStyleSrcs'] ?? [];
3174 $this->mSpeculativeRevId = $jsonData['SpeculativeRevId'] ?? null;
3175 $this->speculativePageIdUsed = $jsonData['SpeculativePageIdUsed'] ?? null;
3176 $this->revisionTimestampUsed = $jsonData['RevisionTimestampUsed'] ?? null;
3177 $this->revisionUsedSha1Base36 = $jsonData['RevisionUsedSha1Base36'] ?? null;
3178 $this->mWrapperDivClasses = $jsonData['WrapperDivClasses'] ?? [];
3179 $this->mMaxAdaptiveExpiry = $jsonData['MaxAdaptiveExpiry'] ?? INF;
3180 }
3181
3182 /**
3183 * Finds any non-utf8 strings in the given array and replaces them with
3184 * an associative array that wraps a base64 encoded version of the data.
3185 * Inverse of detectAndDecodeBinary().
3186 *
3187 * @param array $properties
3188 *
3189 * @return array
3190 */
3191 private static function detectAndEncodeBinary( array $properties ) {
3192 foreach ( $properties as $key => $value ) {
3193 if ( is_string( $value ) ) {
3194 if ( !mb_detect_encoding( $value, 'UTF-8', true ) ) {
3195 $properties[$key] = [
3196 // T313818: This key name conflicts with JsonCodec
3197 '_type_' => 'string',
3198 '_encoding_' => 'base64',
3199 '_data_' => base64_encode( $value ),
3200 ];
3201 }
3202 }
3203 }
3204
3205 return $properties;
3206 }
3207
3208 /**
3209 * Finds any associative arrays that represent encoded binary strings, and
3210 * replaces them with the decoded binary data.
3211 *
3212 * @param array $properties
3213 *
3214 * @return array
3215 */
3216 private static function detectAndDecodeBinary( array $properties ) {
3217 foreach ( $properties as $key => $value ) {
3218 if ( is_array( $value ) && isset( $value['_encoding_'] ) ) {
3219 if ( $value['_encoding_'] === 'base64' ) {
3220 $properties[$key] = base64_decode( $value['_data_'] );
3221 }
3222 }
3223 }
3224
3225 return $properties;
3226 }
3227
3228 public function __wakeup() {
3229 $oldAliases = [
3230 // This was the pre-namespace name of the class, which is still
3231 // used in pre-1.42 serialized objects.
3232 'ParserOutput',
3233 ];
3234 // Backwards compatibility, pre 1.36
3235 $priorAccessedOptions = $this->getGhostFieldValue( 'mAccessedOptions', ...$oldAliases );
3236 if ( $priorAccessedOptions ) {
3237 $this->mParseUsedOptions = $priorAccessedOptions;
3238 }
3239 // Backwards compatibility, pre 1.39
3240 $priorIndexPolicy = $this->getGhostFieldValue( 'mIndexPolicy', ...$oldAliases );
3241 if ( $priorIndexPolicy ) {
3242 $this->setIndexPolicy( $priorIndexPolicy );
3243 }
3244 // Backwards compatibility, pre 1.40
3245 $mSections = $this->getGhostFieldValue( 'mSections', ...$oldAliases );
3246 if ( $mSections !== null && $mSections !== [] ) {
3247 $this->setSections( $mSections );
3248 }
3249 // Backwards compatibility, pre 1.42
3250 $mModules = $this->getGhostFieldValue( 'mModules', ...$oldAliases );
3251 if ( $mModules !== null && $mModules !== [] ) {
3252 $this->addModules( $mModules );
3253 }
3254 // Backwards compatibility, pre 1.42
3255 $mModuleStyles = $this->getGhostFieldValue( 'mModuleStyles', ...$oldAliases );
3256 if ( $mModuleStyles !== null && $mModuleStyles !== [] ) {
3257 $this->addModuleStyles( $mModuleStyles );
3258 }
3259 // Backwards compatibility, pre 1.42
3260 $mText = $this->getGhostFieldValue( 'mText', ...$oldAliases );
3261 if ( $mText !== null ) {
3262 $this->setRawText( $mText );
3263 }
3264 // Backwards compatibility, pre 1.42
3265 $ll = $this->getGhostFieldValue( 'mLanguageLinks', ...$oldAliases );
3266 if ( $ll !== null && $ll !== [] ) {
3267 foreach ( $ll as $l ) {
3268 $this->addLanguageLink( $l );
3269 }
3270 }
3271 // Backward compatibility with private fields, pre 1.42
3272 $oldPrivateFields = [
3273 'mRawText',
3274 'mCategories',
3275 'mIndicators',
3276 'mTitleText',
3277 'mLinks',
3278 'mLinksSpecial',
3279 'mTemplates',
3280 'mTemplateIds',
3281 'mImages',
3282 'mFileSearchOptions',
3283 'mExternalLinks',
3284 'mInterwikiLinks',
3285 'mNewSection',
3286 'mHideNewSection',
3287 'mNoGallery',
3288 'mHeadItems',
3289 'mModuleSet',
3290 'mModuleStyleSet',
3291 'mJsConfigVars',
3292 'mWarnings',
3293 'mWarningMsgs',
3294 'mTOCData',
3295 'mProperties',
3296 'mTimestamp',
3297 'mEnableOOUI',
3298 'mIndexSet',
3299 'mNoIndexSet',
3300 'mExtensionData',
3301 'mLimitReportData',
3302 'mLimitReportJSData',
3303 'mCacheMessage',
3304 'mParseStartTime',
3305 'mTimeProfile',
3306 'mPreventClickjacking',
3307 'mExtraScriptSrcs',
3308 'mExtraDefaultSrcs',
3309 'mExtraStyleSrcs',
3310 'mFlags',
3311 'mSpeculativeRevId',
3312 'speculativePageIdUsed',
3313 'revisionTimestampUsed',
3314 'revisionUsedSha1Base36',
3315 'mWrapperDivClasses',
3316 'mMaxAdaptiveExpiry',
3317 ];
3318 foreach ( $oldPrivateFields as $f ) {
3319 $this->restoreAliasedGhostField( $f, ...$oldAliases );
3320 }
3321 $this->clearParseStartTime();
3322 }
3323
3324 public function __clone() {
3325 // It seems that very little of this object needs to be explicitly deep-cloned
3326 // while keeping copies reasonably separated.
3327 // Most of the non-scalar properties of this object are either
3328 // - (potentially multi-nested) arrays of scalars (which get deep-cloned), or
3329 // - arrays that may contain arbitrary elements (which don't necessarily get
3330 // deep-cloned), but for which no particular care elsewhere is given to
3331 // copying their references around (e.g. mJsConfigVars).
3332 // Hence, we are not going out of our way to ensure that the references to innermost
3333 // objects that may appear in a ParserOutput are unique. If that becomes the
3334 // expectation at any point, this method will require updating as well.
3335 // The exception is TOCData (which is an object), which we clone explicitly.
3336 if ( $this->mTOCData ) {
3337 $this->mTOCData = clone $this->mTOCData;
3338 }
3339 }
3340
3341 /**
3342 * Returns the content holder text of the ParserOutput.
3343 * This will eventually be replaced by something like getContentHolder()->getText() when we have a
3344 * ContentHolder/HtmlHolder class.
3345 * @internal
3346 * @unstable
3347 * @return string
3348 */
3349 public function getContentHolderText(): string {
3350 return $this->getRawText();
3351 }
3352
3353 /**
3354 * Sets the content holder text of the ParserOutput.
3355 * This will eventually be replaced by something like getContentHolder()->setText() when we have a
3356 * ContentHolder/HtmlHolder class.
3357 * @internal
3358 * @unstable
3359 */
3360 public function setContentHolderText( string $s ): void {
3361 $this->setRawText( $s );
3362 }
3363
3364 public function __get( $name ) {
3365 if ( property_exists( get_called_class(), $name ) ) {
3366 // Direct access to a public property, deprecated.
3367 wfDeprecatedMsg( "ParserOutput::{$name} public read access deprecated", '1.38' );
3368 return $this->$name;
3369 } elseif ( property_exists( $this, $name ) ) {
3370 // Dynamic property access, deprecated.
3371 wfDeprecatedMsg( "ParserOutput::{$name} dynamic property read access deprecated", '1.38' );
3372 return $this->$name;
3373 } else {
3374 trigger_error( "Inaccessible property via __get(): $name" );
3375 return null;
3376 }
3377 }
3378
3379 public function __set( $name, $value ) {
3380 if ( property_exists( get_called_class(), $name ) ) {
3381 // Direct access to a public property, deprecated.
3382 wfDeprecatedMsg( "ParserOutput::$name public write access deprecated", '1.38' );
3383 $this->$name = $value;
3384 } else {
3385 // Dynamic property access, deprecated.
3386 wfDeprecatedMsg( "ParserOutput::$name dynamic property write access deprecated", '1.38' );
3387 $this->$name = $value;
3388 }
3389 }
3390 }
3391
3392 /** @deprecated class alias since 1.42 */
3393 class_alias( ParserOutput::class, 'ParserOutput' );