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