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