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