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