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