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