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