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