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