Remove Revision::getRevisionText from ApiQueryDeletedrevs
[lhc/web/wiklou.git] / includes / parser / ParserOutput.php
1 <?php
2
3 /**
4 * Output of the PHP parser.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Parser
23 */
24
25 class ParserOutput extends CacheTime {
26 /**
27 * Feature flags to indicate to extensions that MediaWiki core supports and
28 * uses getText() stateless transforms.
29 *
30 * @since 1.31
31 */
32 const SUPPORTS_STATELESS_TRANSFORMS = 1;
33
34 /**
35 * @since 1.31
36 */
37 const SUPPORTS_UNWRAP_TRANSFORM = 1;
38
39 /**
40 * @var string|null $mText The output text
41 */
42 public $mText = null;
43
44 /**
45 * @var array $mLanguageLinks List of the full text of language links,
46 * in the order they appear.
47 */
48 public $mLanguageLinks;
49
50 /**
51 * @var array $mCategories Map of category names to sort keys
52 */
53 public $mCategories;
54
55 /**
56 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
57 */
58 public $mIndicators = [];
59
60 /**
61 * @var string $mTitleText Title text of the chosen language variant, as HTML.
62 */
63 public $mTitleText;
64
65 /**
66 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
67 * ID=zero for broken.
68 */
69 public $mLinks = [];
70
71 /**
72 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
73 * ID=zero for broken.
74 */
75 public $mTemplates = [];
76
77 /**
78 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
79 * ID=zero for broken.
80 */
81 public $mTemplateIds = [];
82
83 /**
84 * @var array $mImages DB keys of the images used, in the array key only
85 */
86 public $mImages = [];
87
88 /**
89 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
90 */
91 public $mFileSearchOptions = [];
92
93 /**
94 * @var array $mExternalLinks External link URLs, in the key only.
95 */
96 public $mExternalLinks = [];
97
98 /**
99 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
100 * for the inline interwiki links in the document.
101 */
102 public $mInterwikiLinks = [];
103
104 /**
105 * @var bool $mNewSection Show a new section link?
106 */
107 public $mNewSection = false;
108
109 /**
110 * @var bool $mHideNewSection Hide the new section link?
111 */
112 public $mHideNewSection = false;
113
114 /**
115 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
116 */
117 public $mNoGallery = false;
118
119 /**
120 * @var array $mHeadItems Items to put in the <head> section
121 */
122 public $mHeadItems = [];
123
124 /**
125 * @var array $mModules Modules to be loaded by ResourceLoader
126 */
127 public $mModules = [];
128
129 /**
130 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
131 */
132 public $mModuleStyles = [];
133
134 /**
135 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
136 */
137 public $mJsConfigVars = [];
138
139 /**
140 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
141 */
142 public $mOutputHooks = [];
143
144 /**
145 * @var array $mWarnings Warning text to be returned to the user.
146 * Wikitext formatted, in the key only.
147 */
148 public $mWarnings = [];
149
150 /**
151 * @var array $mSections Table of contents
152 */
153 public $mSections = [];
154
155 /**
156 * @var array $mProperties Name/value pairs to be cached in the DB.
157 */
158 public $mProperties = [];
159
160 /**
161 * @var string $mTOCHTML HTML of the TOC.
162 */
163 public $mTOCHTML = '';
164
165 /**
166 * @var string $mTimestamp Timestamp of the revision.
167 */
168 public $mTimestamp;
169
170 /**
171 * @var bool $mEnableOOUI Whether OOUI should be enabled.
172 */
173 public $mEnableOOUI = false;
174
175 /**
176 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
177 */
178 private $mIndexPolicy = '';
179
180 /**
181 * @var true[] $mAccessedOptions List of ParserOptions (stored in the keys).
182 */
183 private $mAccessedOptions = [];
184
185 /**
186 * @var array $mExtensionData extra data used by extensions.
187 */
188 private $mExtensionData = [];
189
190 /**
191 * @var array $mLimitReportData Parser limit report data.
192 */
193 private $mLimitReportData = [];
194
195 /** @var array Parser limit report data for JSON */
196 private $mLimitReportJSData = [];
197
198 /**
199 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
200 */
201 private $mParseStartTime = [];
202
203 /**
204 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
205 */
206 private $mPreventClickjacking = false;
207
208 /**
209 * @var array $mFlags Generic flags.
210 */
211 private $mFlags = [];
212
213 /** @var string[] */
214 private static $speculativeFields = [
215 'speculativePageIdUsed',
216 'mSpeculativeRevId',
217 'revisionTimestampUsed'
218 ];
219
220 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
221 private $mSpeculativeRevId;
222 /** @var int|null Assumed page ID for {{PAGEID}} if no revision is set */
223 private $speculativePageIdUsed;
224 /** @var int|null Assumed rev timestamp for {{REVISIONTIMESTAMP}} if no revision is set */
225 private $revisionTimestampUsed;
226
227 /** @var string|null SHA-1 base 36 hash of any self-transclusion */
228 private $revisionUsedSha1Base36;
229
230 /** string CSS classes to use for the wrapping div, stored in the array keys.
231 * If no class is given, no wrapper is added.
232 */
233 private $mWrapperDivClasses = [];
234
235 /** @var int Upper bound of expiry based on parse duration */
236 private $mMaxAdaptiveExpiry = INF;
237
238 const EDITSECTION_REGEX =
239 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
240
241 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
242 // Current values imply that m=3933.333333 and b=-333.333333
243 // See https://www.nngroup.com/articles/website-response-times/
244 const PARSE_FAST_SEC = 0.100; // perceived "fast" page parse
245 const PARSE_SLOW_SEC = 1.0; // perceived "slow" page parse
246 const FAST_AR_TTL = 60; // adaptive TTL for "fast" pages
247 const SLOW_AR_TTL = 3600; // adaptive TTL for "slow" pages
248 const MIN_AR_TTL = 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
249
250 /**
251 * @param string|null $text HTML. Use null to indicate that this ParserOutput contains only
252 * meta-data, and the HTML output is undetermined, as opposed to empty. Passing null
253 * here causes hasText() to return false.
254 * @param array $languageLinks
255 * @param array $categoryLinks
256 * @param bool $unused
257 * @param string $titletext
258 */
259 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
260 $unused = false, $titletext = ''
261 ) {
262 $this->mText = $text;
263 $this->mLanguageLinks = $languageLinks;
264 $this->mCategories = $categoryLinks;
265 $this->mTitleText = $titletext;
266 }
267
268 /**
269 * Returns true if text was passed to the constructor, or set using setText(). Returns false
270 * if null was passed to the $text parameter of the constructor to indicate that this
271 * ParserOutput only contains meta-data, and the HTML output is undetermined.
272 *
273 * @since 1.32
274 *
275 * @return bool Whether this ParserOutput contains rendered text. If this returns false, the
276 * ParserOutput contains meta-data only.
277 */
278 public function hasText() {
279 return ( $this->mText !== null );
280 }
281
282 /**
283 * Get the cacheable text with <mw:editsection> markers still in it. The
284 * return value is suitable for writing back via setText() but is not valid
285 * for display to the user.
286 *
287 * @return string
288 * @since 1.27
289 */
290 public function getRawText() {
291 if ( $this->mText === null ) {
292 throw new LogicException( 'This ParserOutput contains no text!' );
293 }
294
295 return $this->mText;
296 }
297
298 /**
299 * Get the output HTML
300 *
301 * @param array $options (since 1.31) Transformations to apply to the HTML
302 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
303 * to generate one and `__NOTOC__` wasn't used. Default is true,
304 * but might be statefully overridden.
305 * - enableSectionEditLinks: (bool) Include section edit links, assuming
306 * section edit link tokens are present in the HTML. Default is true,
307 * but might be statefully overridden.
308 * - unwrap: (bool) Return text without a wrapper div. Default is false,
309 * meaning a wrapper div will be added if getWrapperDivClass() returns
310 * a non-empty string.
311 * - wrapperDivClass: (string) Wrap the output in a div and apply the given
312 * CSS class to that div. This overrides the output of getWrapperDivClass().
313 * Setting this to an empty string has the same effect as 'unwrap' => true.
314 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
315 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
316 * value of the attribute: all but the first will be replaced by `<link
317 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
318 * the scheme-specific-part of the href is the (percent-encoded) value
319 * of the `data-mw-deduplicate` attribute.
320 * @return string HTML
321 * @return-taint escaped
322 */
323 public function getText( $options = [] ) {
324 $options += [
325 'allowTOC' => true,
326 'enableSectionEditLinks' => true,
327 'unwrap' => false,
328 'deduplicateStyles' => true,
329 'wrapperDivClass' => $this->getWrapperDivClass(),
330 ];
331 $text = $this->getRawText();
332
333 Hooks::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
334
335 if ( $options['wrapperDivClass'] !== '' && !$options['unwrap'] ) {
336 $text = Html::rawElement( 'div', [ 'class' => $options['wrapperDivClass'] ], $text );
337 }
338
339 if ( $options['enableSectionEditLinks'] ) {
340 $text = preg_replace_callback(
341 self::EDITSECTION_REGEX,
342 function ( $m ) {
343 $editsectionPage = Title::newFromText( htmlspecialchars_decode( $m[1] ) );
344 $editsectionSection = htmlspecialchars_decode( $m[2] );
345 $editsectionContent = isset( $m[4] ) ? Sanitizer::decodeCharReferences( $m[3] ) : null;
346
347 if ( !is_object( $editsectionPage ) ) {
348 throw new MWException( "Bad parser output text." );
349 }
350
351 $context = RequestContext::getMain();
352 return $context->getSkin()->doEditSectionLink(
353 $editsectionPage,
354 $editsectionSection,
355 $editsectionContent,
356 $context->getLanguage()
357 );
358 },
359 $text
360 );
361 } else {
362 $text = preg_replace( self::EDITSECTION_REGEX, '', $text );
363 }
364
365 if ( $options['allowTOC'] ) {
366 $text = str_replace( [ Parser::TOC_START, Parser::TOC_END ], '', $text );
367 } else {
368 $text = preg_replace(
369 '#' . preg_quote( Parser::TOC_START, '#' ) . '.*?' . preg_quote( Parser::TOC_END, '#' ) . '#s',
370 '',
371 $text
372 );
373 }
374
375 if ( $options['deduplicateStyles'] ) {
376 $seen = [];
377 $text = preg_replace_callback(
378 '#<style\s+([^>]*data-mw-deduplicate\s*=[^>]*)>.*?</style>#s',
379 function ( $m ) use ( &$seen ) {
380 $attr = Sanitizer::decodeTagAttributes( $m[1] );
381 if ( !isset( $attr['data-mw-deduplicate'] ) ) {
382 return $m[0];
383 }
384
385 $key = $attr['data-mw-deduplicate'];
386 if ( !isset( $seen[$key] ) ) {
387 $seen[$key] = true;
388 return $m[0];
389 }
390
391 // We were going to use an empty <style> here, but there
392 // was concern that would be too much overhead for browsers.
393 // So let's hope a <link> with a non-standard rel and href isn't
394 // going to be misinterpreted or mangled by any subsequent processing.
395 return Html::element( 'link', [
396 'rel' => 'mw-deduplicated-inline-style',
397 'href' => "mw-data:" . wfUrlencode( $key ),
398 ] );
399 },
400 $text
401 );
402 }
403
404 // Hydrate slot section header placeholders generated by RevisionRenderer.
405 $text = preg_replace_callback(
406 '#<mw:slotheader>(.*?)</mw:slotheader>#',
407 function ( $m ) {
408 $role = htmlspecialchars_decode( $m[1] );
409 // TODO: map to message, using the interface language. Set lang="xyz" accordingly.
410 $headerText = $role;
411 return $headerText;
412 },
413 $text
414 );
415 return $text;
416 }
417
418 /**
419 * Add a CSS class to use for the wrapping div. If no class is given, no wrapper is added.
420 *
421 * @param string $class
422 */
423 public function addWrapperDivClass( $class ) {
424 $this->mWrapperDivClasses[$class] = true;
425 }
426
427 /**
428 * Clears the CSS class to use for the wrapping div, effectively disabling the wrapper div
429 * until addWrapperDivClass() is called.
430 */
431 public function clearWrapperDivClass() {
432 $this->mWrapperDivClasses = [];
433 }
434
435 /**
436 * Returns the class (or classes) to be used with the wrapper div for this otuput.
437 * If there is no wrapper class given, no wrapper div should be added.
438 * The wrapper div is added automatically by getText().
439 *
440 * @return string
441 */
442 public function getWrapperDivClass() {
443 return implode( ' ', array_keys( $this->mWrapperDivClasses ) );
444 }
445
446 /**
447 * @param int $id
448 * @since 1.28
449 */
450 public function setSpeculativeRevIdUsed( $id ) {
451 $this->mSpeculativeRevId = $id;
452 }
453
454 /**
455 * @return int|null
456 * @since 1.28
457 */
458 public function getSpeculativeRevIdUsed() {
459 return $this->mSpeculativeRevId;
460 }
461
462 /**
463 * @param int $id
464 * @since 1.34
465 */
466 public function setSpeculativePageIdUsed( $id ) {
467 $this->speculativePageIdUsed = $id;
468 }
469
470 /**
471 * @return int|null
472 * @since 1.34
473 */
474 public function getSpeculativePageIdUsed() {
475 return $this->speculativePageIdUsed;
476 }
477
478 /**
479 * @param string $timestamp TS_MW timestamp
480 * @since 1.34
481 */
482 public function setRevisionTimestampUsed( $timestamp ) {
483 $this->revisionTimestampUsed = $timestamp;
484 }
485
486 /**
487 * @return string|null TS_MW timestamp or null if not used
488 * @since 1.34
489 */
490 public function getRevisionTimestampUsed() {
491 return $this->revisionTimestampUsed;
492 }
493
494 /**
495 * @param string $hash Lowercase SHA-1 base 36 hash
496 * @since 1.34
497 */
498 public function setRevisionUsedSha1Base36( $hash ) {
499 if ( $hash === null ) {
500 return; // e.g. RevisionRecord::getSha1() returned null
501 }
502
503 if (
504 $this->revisionUsedSha1Base36 !== null &&
505 $this->revisionUsedSha1Base36 !== $hash
506 ) {
507 $this->revisionUsedSha1Base36 = ''; // mismatched
508 } else {
509 $this->revisionUsedSha1Base36 = $hash;
510 }
511 }
512
513 /**
514 * @return string|null Lowercase SHA-1 base 36 hash, null if unused, or "" on inconsistency
515 * @since 1.34
516 */
517 public function getRevisionUsedSha1Base36() {
518 return $this->revisionUsedSha1Base36;
519 }
520
521 public function &getLanguageLinks() {
522 return $this->mLanguageLinks;
523 }
524
525 public function getInterwikiLinks() {
526 return $this->mInterwikiLinks;
527 }
528
529 public function getCategoryLinks() {
530 return array_keys( $this->mCategories );
531 }
532
533 public function &getCategories() {
534 return $this->mCategories;
535 }
536
537 /**
538 * @return array
539 * @since 1.25
540 */
541 public function getIndicators() {
542 return $this->mIndicators;
543 }
544
545 public function getTitleText() {
546 return $this->mTitleText;
547 }
548
549 public function getSections() {
550 return $this->mSections;
551 }
552
553 public function &getLinks() {
554 return $this->mLinks;
555 }
556
557 public function &getTemplates() {
558 return $this->mTemplates;
559 }
560
561 public function &getTemplateIds() {
562 return $this->mTemplateIds;
563 }
564
565 public function &getImages() {
566 return $this->mImages;
567 }
568
569 public function &getFileSearchOptions() {
570 return $this->mFileSearchOptions;
571 }
572
573 public function &getExternalLinks() {
574 return $this->mExternalLinks;
575 }
576
577 public function setNoGallery( $value ) {
578 $this->mNoGallery = (bool)$value;
579 }
580
581 public function getNoGallery() {
582 return $this->mNoGallery;
583 }
584
585 public function getHeadItems() {
586 return $this->mHeadItems;
587 }
588
589 public function getModules() {
590 return $this->mModules;
591 }
592
593 public function getModuleStyles() {
594 return $this->mModuleStyles;
595 }
596
597 /**
598 * @return array
599 * @since 1.23
600 */
601 public function getJsConfigVars() {
602 return $this->mJsConfigVars;
603 }
604
605 public function getOutputHooks() {
606 return (array)$this->mOutputHooks;
607 }
608
609 public function getWarnings() {
610 return array_keys( $this->mWarnings );
611 }
612
613 public function getIndexPolicy() {
614 return $this->mIndexPolicy;
615 }
616
617 public function getTOCHTML() {
618 return $this->mTOCHTML;
619 }
620
621 /**
622 * @return string|null TS_MW timestamp of the revision content
623 */
624 public function getTimestamp() {
625 return $this->mTimestamp;
626 }
627
628 public function getLimitReportData() {
629 return $this->mLimitReportData;
630 }
631
632 public function getLimitReportJSData() {
633 return $this->mLimitReportJSData;
634 }
635
636 public function getEnableOOUI() {
637 return $this->mEnableOOUI;
638 }
639
640 public function setText( $text ) {
641 return wfSetVar( $this->mText, $text );
642 }
643
644 public function setLanguageLinks( $ll ) {
645 return wfSetVar( $this->mLanguageLinks, $ll );
646 }
647
648 public function setCategoryLinks( $cl ) {
649 return wfSetVar( $this->mCategories, $cl );
650 }
651
652 public function setTitleText( $t ) {
653 return wfSetVar( $this->mTitleText, $t );
654 }
655
656 public function setSections( $toc ) {
657 return wfSetVar( $this->mSections, $toc );
658 }
659
660 public function setIndexPolicy( $policy ) {
661 return wfSetVar( $this->mIndexPolicy, $policy );
662 }
663
664 public function setTOCHTML( $tochtml ) {
665 return wfSetVar( $this->mTOCHTML, $tochtml );
666 }
667
668 public function setTimestamp( $timestamp ) {
669 return wfSetVar( $this->mTimestamp, $timestamp );
670 }
671
672 public function addCategory( $c, $sort ) {
673 $this->mCategories[$c] = $sort;
674 }
675
676 /**
677 * @param string $id
678 * @param string $content
679 * @since 1.25
680 */
681 public function setIndicator( $id, $content ) {
682 $this->mIndicators[$id] = $content;
683 }
684
685 /**
686 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
687 * object is added to.
688 *
689 * @since 1.26
690 * @param bool $enable If OOUI should be enabled or not
691 */
692 public function setEnableOOUI( $enable = false ) {
693 $this->mEnableOOUI = $enable;
694 }
695
696 public function addLanguageLink( $t ) {
697 $this->mLanguageLinks[] = $t;
698 }
699
700 public function addWarning( $s ) {
701 $this->mWarnings[$s] = 1;
702 }
703
704 public function addOutputHook( $hook, $data = false ) {
705 $this->mOutputHooks[] = [ $hook, $data ];
706 }
707
708 public function setNewSection( $value ) {
709 $this->mNewSection = (bool)$value;
710 }
711
712 public function hideNewSection( $value ) {
713 $this->mHideNewSection = (bool)$value;
714 }
715
716 public function getHideNewSection() {
717 return (bool)$this->mHideNewSection;
718 }
719
720 public function getNewSection() {
721 return (bool)$this->mNewSection;
722 }
723
724 /**
725 * Checks, if a url is pointing to the own server
726 *
727 * @param string $internal The server to check against
728 * @param string $url The url to check
729 * @return bool
730 */
731 public static function isLinkInternal( $internal, $url ) {
732 return (bool)preg_match( '/^' .
733 # If server is proto relative, check also for http/https links
734 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
735 preg_quote( $internal, '/' ) .
736 # check for query/path/anchor or end of link in each case
737 '(?:[\?\/\#]|$)/i',
738 $url
739 );
740 }
741
742 public function addExternalLink( $url ) {
743 # We don't register links pointing to our own server, unless... :-)
744 global $wgServer, $wgRegisterInternalExternals;
745
746 # Replace unnecessary URL escape codes with the referenced character
747 # This prevents spammers from hiding links from the filters
748 $url = Parser::normalizeLinkUrl( $url );
749
750 $registerExternalLink = true;
751 if ( !$wgRegisterInternalExternals ) {
752 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
753 }
754 if ( $registerExternalLink ) {
755 $this->mExternalLinks[$url] = 1;
756 }
757 }
758
759 /**
760 * Record a local or interwiki inline link for saving in future link tables.
761 *
762 * @param Title $title
763 * @param int|null $id Optional known page_id so we can skip the lookup
764 */
765 public function addLink( Title $title, $id = null ) {
766 if ( $title->isExternal() ) {
767 // Don't record interwikis in pagelinks
768 $this->addInterwikiLink( $title );
769 return;
770 }
771 $ns = $title->getNamespace();
772 $dbk = $title->getDBkey();
773 if ( $ns == NS_MEDIA ) {
774 // Normalize this pseudo-alias if it makes it down here...
775 $ns = NS_FILE;
776 } elseif ( $ns == NS_SPECIAL ) {
777 // We don't record Special: links currently
778 // It might actually be wise to, but we'd need to do some normalization.
779 return;
780 } elseif ( $dbk === '' ) {
781 // Don't record self links - [[#Foo]]
782 return;
783 }
784 if ( !isset( $this->mLinks[$ns] ) ) {
785 $this->mLinks[$ns] = [];
786 }
787 if ( is_null( $id ) ) {
788 $id = $title->getArticleID();
789 }
790 $this->mLinks[$ns][$dbk] = $id;
791 }
792
793 /**
794 * Register a file dependency for this output
795 * @param string $name Title dbKey
796 * @param string|false|null $timestamp MW timestamp of file creation (or false if non-existing)
797 * @param string|false|null $sha1 Base 36 SHA-1 of file (or false if non-existing)
798 */
799 public function addImage( $name, $timestamp = null, $sha1 = null ) {
800 $this->mImages[$name] = 1;
801 if ( $timestamp !== null && $sha1 !== null ) {
802 $this->mFileSearchOptions[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
803 }
804 }
805
806 /**
807 * Register a template dependency for this output
808 * @param Title $title
809 * @param int $page_id
810 * @param int $rev_id
811 */
812 public function addTemplate( $title, $page_id, $rev_id ) {
813 $ns = $title->getNamespace();
814 $dbk = $title->getDBkey();
815 if ( !isset( $this->mTemplates[$ns] ) ) {
816 $this->mTemplates[$ns] = [];
817 }
818 $this->mTemplates[$ns][$dbk] = $page_id;
819 if ( !isset( $this->mTemplateIds[$ns] ) ) {
820 $this->mTemplateIds[$ns] = [];
821 }
822 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
823 }
824
825 /**
826 * @param Title $title Title object, must be an interwiki link
827 * @throws MWException If given invalid input
828 */
829 public function addInterwikiLink( $title ) {
830 if ( !$title->isExternal() ) {
831 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
832 }
833 $prefix = $title->getInterwiki();
834 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
835 $this->mInterwikiLinks[$prefix] = [];
836 }
837 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
838 }
839
840 /**
841 * Add some text to the "<head>".
842 * If $tag is set, the section with that tag will only be included once
843 * in a given page.
844 * @param string $section
845 * @param string|bool $tag
846 */
847 public function addHeadItem( $section, $tag = false ) {
848 if ( $tag !== false ) {
849 $this->mHeadItems[$tag] = $section;
850 } else {
851 $this->mHeadItems[] = $section;
852 }
853 }
854
855 /**
856 * @see OutputPage::addModules
857 */
858 public function addModules( $modules ) {
859 $this->mModules = array_merge( $this->mModules, (array)$modules );
860 }
861
862 /**
863 * @see OutputPage::addModuleStyles
864 */
865 public function addModuleStyles( $modules ) {
866 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
867 }
868
869 /**
870 * Add one or more variables to be set in mw.config in JavaScript.
871 *
872 * @param string|array $keys Key or array of key/value pairs.
873 * @param mixed|null $value [optional] Value of the configuration variable.
874 * @since 1.23
875 */
876 public function addJsConfigVars( $keys, $value = null ) {
877 if ( is_array( $keys ) ) {
878 foreach ( $keys as $key => $value ) {
879 $this->mJsConfigVars[$key] = $value;
880 }
881 return;
882 }
883
884 $this->mJsConfigVars[$keys] = $value;
885 }
886
887 /**
888 * Copy items from the OutputPage object into this one
889 *
890 * @param OutputPage $out
891 */
892 public function addOutputPageMetadata( OutputPage $out ) {
893 $this->addModules( $out->getModules() );
894 $this->addModuleStyles( $out->getModuleStyles() );
895 $this->addJsConfigVars( $out->getJsConfigVars() );
896
897 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
898 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
899 }
900
901 /**
902 * Add a tracking category, getting the title from a system message,
903 * or print a debug message if the title is invalid.
904 *
905 * Any message used with this function should be registered so it will
906 * show up on Special:TrackingCategories. Core messages should be added
907 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
908 * should add to "TrackingCategories" in their extension.json.
909 *
910 * @todo Migrate some code to TrackingCategories
911 *
912 * @param string $msg Message key
913 * @param Title $title title of the page which is being tracked
914 * @return bool Whether the addition was successful
915 * @since 1.25
916 */
917 public function addTrackingCategory( $msg, $title ) {
918 if ( $title->isSpecialPage() ) {
919 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
920 return false;
921 }
922
923 // Important to parse with correct title (T33469)
924 $cat = wfMessage( $msg )
925 ->title( $title )
926 ->inContentLanguage()
927 ->text();
928
929 # Allow tracking categories to be disabled by setting them to "-"
930 if ( $cat === '-' ) {
931 return false;
932 }
933
934 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
935 if ( $containerCategory ) {
936 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
937 return true;
938 } else {
939 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
940 return false;
941 }
942 }
943
944 /**
945 * Override the title to be used for display
946 *
947 * @note this is assumed to have been validated
948 * (check equal normalisation, etc.)
949 *
950 * @note this is expected to be safe HTML,
951 * ready to be served to the client.
952 *
953 * @param string $text Desired title text
954 */
955 public function setDisplayTitle( $text ) {
956 $this->setTitleText( $text );
957 $this->setProperty( 'displaytitle', $text );
958 }
959
960 /**
961 * Get the title to be used for display.
962 *
963 * As per the contract of setDisplayTitle(), this is safe HTML,
964 * ready to be served to the client.
965 *
966 * @return string HTML
967 */
968 public function getDisplayTitle() {
969 $t = $this->getTitleText();
970 if ( $t === '' ) {
971 return false;
972 }
973 return $t;
974 }
975
976 /**
977 * Attach a flag to the output so that it can be checked later to handle special cases
978 *
979 * @param string $flag
980 */
981 public function setFlag( $flag ) {
982 $this->mFlags[$flag] = true;
983 }
984
985 /**
986 * @param string $flag
987 * @return bool Whether the given flag was set to signify a special case
988 */
989 public function getFlag( $flag ) {
990 return isset( $this->mFlags[$flag] );
991 }
992
993 /**
994 * @return string[] List of flags signifying special cases
995 * @since 1.34
996 */
997 public function getAllFlags() {
998 return array_keys( $this->mFlags );
999 }
1000
1001 /**
1002 * Set a property to be stored in the page_props database table.
1003 *
1004 * page_props is a key value store indexed by the page ID. This allows
1005 * the parser to set a property on a page which can then be quickly
1006 * retrieved given the page ID or via a DB join when given the page
1007 * title.
1008 *
1009 * Since 1.23, page_props are also indexed by numeric value, to allow
1010 * for efficient "top k" queries of pages wrt a given property.
1011 *
1012 * setProperty() is thus used to propagate properties from the parsed
1013 * page to request contexts other than a page view of the currently parsed
1014 * article.
1015 *
1016 * Some applications examples:
1017 *
1018 * * To implement hidden categories, hiding pages from category listings
1019 * by storing a property.
1020 *
1021 * * Overriding the displayed article title (ParserOutput::setDisplayTitle()).
1022 *
1023 * * To implement image tagging, for example displaying an icon on an
1024 * image thumbnail to indicate that it is listed for deletion on
1025 * Wikimedia Commons.
1026 * This is not actually implemented, yet but would be pretty cool.
1027 *
1028 * @note Do not use setProperty() to set a property which is only used
1029 * in a context where the ParserOutput object itself is already available,
1030 * for example a normal page view. There is no need to save such a property
1031 * in the database since the text is already parsed. You can just hook
1032 * OutputPageParserOutput and get your data out of the ParserOutput object.
1033 *
1034 * If you are writing an extension where you want to set a property in the
1035 * parser which is used by an OutputPageParserOutput hook, you have to
1036 * associate the extension data directly with the ParserOutput object.
1037 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
1038 *
1039 * @par Example:
1040 * @code
1041 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1042 * @endcode
1043 *
1044 * And then later, in OutputPageParserOutput or similar:
1045 *
1046 * @par Example:
1047 * @code
1048 * $output->getExtensionData( 'my_ext_foo' );
1049 * @endcode
1050 *
1051 * In MediaWiki 1.20 and older, you have to use a custom member variable
1052 * within the ParserOutput object:
1053 *
1054 * @par Example:
1055 * @code
1056 * $parser->getOutput()->my_ext_foo = '...';
1057 * @endcode
1058 * @param string $name
1059 * @param mixed $value
1060 */
1061 public function setProperty( $name, $value ) {
1062 $this->mProperties[$name] = $value;
1063 }
1064
1065 /**
1066 * @param string $name The property name to look up.
1067 *
1068 * @return mixed|bool The value previously set using setProperty(). False if null or no value
1069 * was set for the given property name.
1070 *
1071 * @note You need to use getProperties() to check for boolean and null properties.
1072 */
1073 public function getProperty( $name ) {
1074 return $this->mProperties[$name] ?? false;
1075 }
1076
1077 public function unsetProperty( $name ) {
1078 unset( $this->mProperties[$name] );
1079 }
1080
1081 public function getProperties() {
1082 if ( !isset( $this->mProperties ) ) {
1083 $this->mProperties = [];
1084 }
1085 return $this->mProperties;
1086 }
1087
1088 /**
1089 * Returns the options from its ParserOptions which have been taken
1090 * into account to produce this output.
1091 * @return string[]
1092 */
1093 public function getUsedOptions() {
1094 if ( !isset( $this->mAccessedOptions ) ) {
1095 return [];
1096 }
1097 return array_keys( $this->mAccessedOptions );
1098 }
1099
1100 /**
1101 * Tags a parser option for use in the cache key for this parser output.
1102 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
1103 * The information gathered here is available via getUsedOptions(),
1104 * and is used by ParserCache::save().
1105 *
1106 * @see ParserCache::getKey
1107 * @see ParserCache::save
1108 * @see ParserOptions::addExtraKey
1109 * @see ParserOptions::optionsHash
1110 * @param string $option
1111 */
1112 public function recordOption( $option ) {
1113 $this->mAccessedOptions[$option] = true;
1114 }
1115
1116 /**
1117 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
1118 * the ParserOutput object for later use during page output. The data will be cached along with
1119 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1120 * database.
1121 *
1122 * This method is provided to overcome the unsafe practice of attaching extra information to a
1123 * ParserObject by directly assigning member variables.
1124 *
1125 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1126 * hook in the page output, use this in the parser hook:
1127 *
1128 * @par Example:
1129 * @code
1130 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1131 * @endcode
1132 *
1133 * And then later, in OutputPageParserOutput or similar:
1134 *
1135 * @par Example:
1136 * @code
1137 * $output->getExtensionData( 'my_ext_foo' );
1138 * @endcode
1139 *
1140 * In MediaWiki 1.20 and older, you have to use a custom member variable
1141 * within the ParserOutput object:
1142 *
1143 * @par Example:
1144 * @code
1145 * $parser->getOutput()->my_ext_foo = '...';
1146 * @endcode
1147 *
1148 * @since 1.21
1149 *
1150 * @param string $key The key for accessing the data. Extensions should take care to avoid
1151 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1152 *
1153 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1154 * the value.
1155 */
1156 public function setExtensionData( $key, $value ) {
1157 if ( $value === null ) {
1158 unset( $this->mExtensionData[$key] );
1159 } else {
1160 $this->mExtensionData[$key] = $value;
1161 }
1162 }
1163
1164 /**
1165 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1166 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1167 *
1168 * @since 1.21
1169 *
1170 * @param string $key The key to look up.
1171 *
1172 * @return mixed|null The value previously set for the given key using setExtensionData()
1173 * or null if no value was set for this key.
1174 */
1175 public function getExtensionData( $key ) {
1176 return $this->mExtensionData[$key] ?? null;
1177 }
1178
1179 private static function getTimes( $clock = null ) {
1180 $ret = [];
1181 if ( !$clock || $clock === 'wall' ) {
1182 $ret['wall'] = microtime( true );
1183 }
1184 if ( !$clock || $clock === 'cpu' ) {
1185 $ru = wfGetRusage();
1186 if ( $ru ) {
1187 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
1188 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
1189 }
1190 }
1191 return $ret;
1192 }
1193
1194 /**
1195 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1196 * @since 1.22
1197 */
1198 public function resetParseStartTime() {
1199 $this->mParseStartTime = self::getTimes();
1200 }
1201
1202 /**
1203 * Returns the time since resetParseStartTime() was last called
1204 *
1205 * Clocks available are:
1206 * - wall: Wall clock time
1207 * - cpu: CPU time (requires getrusage)
1208 *
1209 * @since 1.22
1210 * @param string $clock
1211 * @return float|null
1212 */
1213 public function getTimeSinceStart( $clock ) {
1214 if ( !isset( $this->mParseStartTime[$clock] ) ) {
1215 return null;
1216 }
1217
1218 $end = self::getTimes( $clock );
1219 return $end[$clock] - $this->mParseStartTime[$clock];
1220 }
1221
1222 /**
1223 * Sets parser limit report data for a key
1224 *
1225 * The key is used as the prefix for various messages used for formatting:
1226 * - $key: The label for the field in the limit report
1227 * - $key-value-text: Message used to format the value in the "NewPP limit
1228 * report" HTML comment. If missing, uses $key-format.
1229 * - $key-value-html: Message used to format the value in the preview
1230 * limit report table. If missing, uses $key-format.
1231 * - $key-value: Message used to format the value. If missing, uses "$1".
1232 *
1233 * Note that all values are interpreted as wikitext, and so should be
1234 * encoded with htmlspecialchars() as necessary, but should avoid complex
1235 * HTML for sanity of display in the "NewPP limit report" comment.
1236 *
1237 * @since 1.22
1238 * @param string $key Message key
1239 * @param mixed $value Appropriate for Message::params()
1240 */
1241 public function setLimitReportData( $key, $value ) {
1242 $this->mLimitReportData[$key] = $value;
1243
1244 if ( is_array( $value ) ) {
1245 if ( array_keys( $value ) === [ 0, 1 ]
1246 && is_numeric( $value[0] )
1247 && is_numeric( $value[1] )
1248 ) {
1249 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1250 } else {
1251 $data = $value;
1252 }
1253 } else {
1254 $data = $value;
1255 }
1256
1257 if ( strpos( $key, '-' ) ) {
1258 list( $ns, $name ) = explode( '-', $key, 2 );
1259 $this->mLimitReportJSData[$ns][$name] = $data;
1260 } else {
1261 $this->mLimitReportJSData[$key] = $data;
1262 }
1263 }
1264
1265 /**
1266 * Check whether the cache TTL was lowered due to dynamic content
1267 *
1268 * When content is determined by more than hard state (e.g. page edits),
1269 * such as template/file transclusions based on the current timestamp or
1270 * extension tags that generate lists based on queries, this return true.
1271 *
1272 * @return bool
1273 * @since 1.25
1274 */
1275 public function hasDynamicContent() {
1276 global $wgParserCacheExpireTime;
1277
1278 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1279 }
1280
1281 /**
1282 * Get or set the prevent-clickjacking flag
1283 *
1284 * @since 1.24
1285 * @param bool|null $flag New flag value, or null to leave it unchanged
1286 * @return bool Old flag value
1287 */
1288 public function preventClickjacking( $flag = null ) {
1289 return wfSetVar( $this->mPreventClickjacking, $flag );
1290 }
1291
1292 /**
1293 * Lower the runtime adaptive TTL to at most this value
1294 *
1295 * @param int $ttl
1296 * @since 1.28
1297 */
1298 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1299 $this->mMaxAdaptiveExpiry = min( $ttl, $this->mMaxAdaptiveExpiry );
1300 $this->updateCacheExpiry( $ttl );
1301 }
1302
1303 /**
1304 * Call this when parsing is done to lower the TTL based on low parse times
1305 *
1306 * @since 1.28
1307 */
1308 public function finalizeAdaptiveCacheExpiry() {
1309 if ( is_infinite( $this->mMaxAdaptiveExpiry ) ) {
1310 return; // not set
1311 }
1312
1313 $runtime = $this->getTimeSinceStart( 'wall' );
1314 if ( is_float( $runtime ) ) {
1315 $slope = ( self::SLOW_AR_TTL - self::FAST_AR_TTL )
1316 / ( self::PARSE_SLOW_SEC - self::PARSE_FAST_SEC );
1317 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1318 $point = self::SLOW_AR_TTL - self::PARSE_SLOW_SEC * $slope;
1319
1320 $adaptiveTTL = min(
1321 max( $slope * $runtime + $point, self::MIN_AR_TTL ),
1322 $this->mMaxAdaptiveExpiry
1323 );
1324 $this->updateCacheExpiry( $adaptiveTTL );
1325 }
1326 }
1327
1328 public function __sleep() {
1329 return array_filter( array_keys( get_object_vars( $this ) ),
1330 function ( $field ) {
1331 if ( $field === 'mParseStartTime' ) {
1332 return false;
1333 } elseif ( strpos( $field, "\0" ) !== false ) {
1334 // Unserializing unknown private fields in HHVM causes
1335 // member variables with nulls in their names (T229366)
1336 return false;
1337 } else {
1338 return true;
1339 }
1340 }
1341 );
1342 }
1343
1344 /**
1345 * Merges internal metadata such as flags, accessed options, and profiling info
1346 * from $source into this ParserOutput. This should be used whenever the state of $source
1347 * has any impact on the state of this ParserOutput.
1348 *
1349 * @param ParserOutput $source
1350 */
1351 public function mergeInternalMetaDataFrom( ParserOutput $source ) {
1352 $this->mOutputHooks = self::mergeList( $this->mOutputHooks, $source->getOutputHooks() );
1353 $this->mWarnings = self::mergeMap( $this->mWarnings, $source->mWarnings ); // don't use getter
1354 $this->mTimestamp = $this->useMaxValue( $this->mTimestamp, $source->getTimestamp() );
1355
1356 foreach ( self::$speculativeFields as $field ) {
1357 if ( $this->$field && $source->$field && $this->$field !== $source->$field ) {
1358 wfLogWarning( __METHOD__ . ": inconsistent '$field' properties!" );
1359 }
1360 $this->$field = $this->useMaxValue( $this->$field, $source->$field );
1361 }
1362
1363 $this->mParseStartTime = $this->useEachMinValue(
1364 $this->mParseStartTime,
1365 $source->mParseStartTime
1366 );
1367
1368 $this->mFlags = self::mergeMap( $this->mFlags, $source->mFlags );
1369 $this->mAccessedOptions = self::mergeMap( $this->mAccessedOptions, $source->mAccessedOptions );
1370
1371 // TODO: maintain per-slot limit reports!
1372 if ( empty( $this->mLimitReportData ) ) {
1373 $this->mLimitReportData = $source->mLimitReportData;
1374 }
1375 if ( empty( $this->mLimitReportJSData ) ) {
1376 $this->mLimitReportJSData = $source->mLimitReportJSData;
1377 }
1378 }
1379
1380 /**
1381 * Merges HTML metadata such as head items, JS config vars, and HTTP cache control info
1382 * from $source into this ParserOutput. This should be used whenever the HTML in $source
1383 * has been somehow mered into the HTML of this ParserOutput.
1384 *
1385 * @param ParserOutput $source
1386 */
1387 public function mergeHtmlMetaDataFrom( ParserOutput $source ) {
1388 // HTML and HTTP
1389 $this->mHeadItems = self::mergeMixedList( $this->mHeadItems, $source->getHeadItems() );
1390 $this->mModules = self::mergeList( $this->mModules, $source->getModules() );
1391 $this->mModuleStyles = self::mergeList( $this->mModuleStyles, $source->getModuleStyles() );
1392 $this->mJsConfigVars = self::mergeMap( $this->mJsConfigVars, $source->getJsConfigVars() );
1393 $this->mMaxAdaptiveExpiry = min( $this->mMaxAdaptiveExpiry, $source->mMaxAdaptiveExpiry );
1394
1395 // "noindex" always wins!
1396 if ( $this->mIndexPolicy === 'noindex' || $source->mIndexPolicy === 'noindex' ) {
1397 $this->mIndexPolicy = 'noindex';
1398 } elseif ( $this->mIndexPolicy !== 'index' ) {
1399 $this->mIndexPolicy = $source->mIndexPolicy;
1400 }
1401
1402 // Skin control
1403 $this->mNewSection = $this->mNewSection || $source->getNewSection();
1404 $this->mHideNewSection = $this->mHideNewSection || $source->getHideNewSection();
1405 $this->mNoGallery = $this->mNoGallery || $source->getNoGallery();
1406 $this->mEnableOOUI = $this->mEnableOOUI || $source->getEnableOOUI();
1407 $this->mPreventClickjacking = $this->mPreventClickjacking || $source->preventClickjacking();
1408
1409 // TODO: we'll have to be smarter about this!
1410 $this->mSections = array_merge( $this->mSections, $source->getSections() );
1411 $this->mTOCHTML .= $source->mTOCHTML;
1412
1413 // XXX: we don't want to concatenate title text, so first write wins.
1414 // We should use the first *modified* title text, but we don't have the original to check.
1415 if ( $this->mTitleText === null || $this->mTitleText === '' ) {
1416 $this->mTitleText = $source->mTitleText;
1417 }
1418
1419 // class names are stored in array keys
1420 $this->mWrapperDivClasses = self::mergeMap(
1421 $this->mWrapperDivClasses,
1422 $source->mWrapperDivClasses
1423 );
1424
1425 // NOTE: last write wins, same as within one ParserOutput
1426 $this->mIndicators = self::mergeMap( $this->mIndicators, $source->getIndicators() );
1427
1428 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1429 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1430 // kinds of extension data to be merged in different ways.
1431 $this->mExtensionData = self::mergeMap(
1432 $this->mExtensionData,
1433 $source->mExtensionData
1434 );
1435 }
1436
1437 /**
1438 * Merges dependency tracking metadata such as backlinks, images used, and extension data
1439 * from $source into this ParserOutput. This allows dependency tracking to be done for the
1440 * combined output of multiple content slots.
1441 *
1442 * @param ParserOutput $source
1443 */
1444 public function mergeTrackingMetaDataFrom( ParserOutput $source ) {
1445 $this->mLanguageLinks = self::mergeList( $this->mLanguageLinks, $source->getLanguageLinks() );
1446 $this->mCategories = self::mergeMap( $this->mCategories, $source->getCategories() );
1447 $this->mLinks = self::merge2D( $this->mLinks, $source->getLinks() );
1448 $this->mTemplates = self::merge2D( $this->mTemplates, $source->getTemplates() );
1449 $this->mTemplateIds = self::merge2D( $this->mTemplateIds, $source->getTemplateIds() );
1450 $this->mImages = self::mergeMap( $this->mImages, $source->getImages() );
1451 $this->mFileSearchOptions = self::mergeMap(
1452 $this->mFileSearchOptions,
1453 $source->getFileSearchOptions()
1454 );
1455 $this->mExternalLinks = self::mergeMap( $this->mExternalLinks, $source->getExternalLinks() );
1456 $this->mInterwikiLinks = self::merge2D(
1457 $this->mInterwikiLinks,
1458 $source->getInterwikiLinks()
1459 );
1460
1461 // TODO: add a $mergeStrategy parameter to setProperty to allow different
1462 // kinds of properties to be merged in different ways.
1463 $this->mProperties = self::mergeMap( $this->mProperties, $source->getProperties() );
1464
1465 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1466 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1467 // kinds of extension data to be merged in different ways.
1468 $this->mExtensionData = self::mergeMap(
1469 $this->mExtensionData,
1470 $source->mExtensionData
1471 );
1472 }
1473
1474 private static function mergeMixedList( array $a, array $b ) {
1475 return array_unique( array_merge( $a, $b ), SORT_REGULAR );
1476 }
1477
1478 private static function mergeList( array $a, array $b ) {
1479 return array_values( array_unique( array_merge( $a, $b ), SORT_REGULAR ) );
1480 }
1481
1482 private static function mergeMap( array $a, array $b ) {
1483 return array_replace( $a, $b );
1484 }
1485
1486 private static function merge2D( array $a, array $b ) {
1487 $values = [];
1488 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1489
1490 foreach ( $keys as $k ) {
1491 if ( empty( $a[$k] ) ) {
1492 $values[$k] = $b[$k];
1493 } elseif ( empty( $b[$k] ) ) {
1494 $values[$k] = $a[$k];
1495 } elseif ( is_array( $a[$k] ) && is_array( $b[$k] ) ) {
1496 $values[$k] = array_replace( $a[$k], $b[$k] );
1497 } else {
1498 $values[$k] = $b[$k];
1499 }
1500 }
1501
1502 return $values;
1503 }
1504
1505 private static function useEachMinValue( array $a, array $b ) {
1506 $values = [];
1507 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1508
1509 foreach ( $keys as $k ) {
1510 if ( is_array( $a[$k] ?? null ) && is_array( $b[$k] ?? null ) ) {
1511 $values[$k] = self::useEachMinValue( $a[$k], $b[$k] );
1512 } else {
1513 $values[$k] = self::useMinValue( $a[$k] ?? null, $b[$k] ?? null );
1514 }
1515 }
1516
1517 return $values;
1518 }
1519
1520 private static function useMinValue( $a, $b ) {
1521 if ( $a === null ) {
1522 return $b;
1523 }
1524
1525 if ( $b === null ) {
1526 return $a;
1527 }
1528
1529 return min( $a, $b );
1530 }
1531
1532 private static function useMaxValue( $a, $b ) {
1533 if ( $a === null ) {
1534 return $b;
1535 }
1536
1537 if ( $b === null ) {
1538 return $a;
1539 }
1540
1541 return max( $a, $b );
1542 }
1543
1544 }