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