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