Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / includes / parser / ParserOutput.php
blob7bf848fb90929254258ad9b7c2e0cb7bdd78cda3
1 <?php
3 /**
4 * Output of the PHP parser.
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.
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.
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
21 * @file
22 * @ingroup Parser
24 class ParserOutput extends CacheTime {
25 /**
26 * @var string $mText The output text
28 public $mText;
30 /**
31 * @var array $mLanguageLinks List of the full text of language links,
32 * in the order they appear.
34 public $mLanguageLinks;
36 /**
37 * @var array $mCategoriesMap of category names to sort keys
39 public $mCategories;
41 /**
42 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
44 public $mIndicators = [];
46 /**
47 * @var string $mTitleText Title text of the chosen language variant, as HTML.
49 public $mTitleText;
51 /**
52 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
53 * ID=zero for broken.
55 public $mLinks = [];
57 /**
58 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
59 * ID=zero for broken.
61 public $mTemplates = [];
63 /**
64 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
65 * ID=zero for broken.
67 public $mTemplateIds = [];
69 /**
70 * @var array $mImages DB keys of the images used, in the array key only
72 public $mImages = [];
74 /**
75 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
77 public $mFileSearchOptions = [];
79 /**
80 * @var array $mExternalLinks External link URLs, in the key only.
82 public $mExternalLinks = [];
84 /**
85 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
86 * for the inline interwiki links in the document.
88 public $mInterwikiLinks = [];
90 /**
91 * @var bool $mNewSection Show a new section link?
93 public $mNewSection = false;
95 /**
96 * @var bool $mHideNewSection Hide the new section link?
98 public $mHideNewSection = false;
101 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
103 public $mNoGallery = false;
106 * @var array $mHeadItems Items to put in the <head> section
108 public $mHeadItems = [];
111 * @var array $mModules Modules to be loaded by ResourceLoader
113 public $mModules = [];
116 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
118 public $mModuleScripts = [];
121 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
123 public $mModuleStyles = [];
126 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
128 public $mJsConfigVars = [];
131 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
133 public $mOutputHooks = [];
136 * @var array $mWarnings Warning text to be returned to the user.
137 * Wikitext formatted, in the key only.
139 public $mWarnings = [];
142 * @var array $mSections Table of contents
144 public $mSections = [];
147 * @var bool $mEditSectionTokens prefix/suffix markers if edit sections were output as tokens.
149 public $mEditSectionTokens = false;
152 * @var array $mProperties Name/value pairs to be cached in the DB.
154 public $mProperties = [];
157 * @var string $mTOCHTML HTML of the TOC.
159 public $mTOCHTML = '';
162 * @var string $mTimestamp Timestamp of the revision.
164 public $mTimestamp;
167 * @var bool $mTOCEnabled Whether TOC should be shown, can't override __NOTOC__.
169 public $mTOCEnabled = true;
172 * @var bool $mEnableOOUI Whether OOUI should be enabled.
174 public $mEnableOOUI = false;
177 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
179 private $mIndexPolicy = '';
182 * @var array $mAccessedOptions List of ParserOptions (stored in the keys).
184 private $mAccessedOptions = [];
187 * @var array $mExtensionData extra data used by extensions.
189 private $mExtensionData = [];
192 * @var array $mLimitReportData Parser limit report data.
194 private $mLimitReportData = [];
196 /** @var array Parser limit report data for JSON */
197 private $mLimitReportJSData = [];
200 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
202 private $mParseStartTime = [];
205 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
207 private $mPreventClickjacking = false;
210 * @var array $mFlags Generic flags.
212 private $mFlags = [];
214 /** @var integer|null Assumed rev ID for {{REVISIONID}} if no revision is set */
215 private $mSpeculativeRevId;
217 /** @var integer Upper bound of expiry based on parse duration */
218 private $mMaxAdaptiveExpiry = INF;
220 const EDITSECTION_REGEX =
221 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
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)
232 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
233 $unused = false, $titletext = ''
235 $this->mText = $text;
236 $this->mLanguageLinks = $languageLinks;
237 $this->mCategories = $categoryLinks;
238 $this->mTitleText = $titletext;
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.
246 * @since 1.27
248 public function getRawText() {
249 return $this->mText;
252 public function getText() {
253 $text = $this->mText;
254 if ( $this->mEditSectionTokens ) {
255 $text = preg_replace_callback(
256 ParserOutput::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;
263 if ( !is_object( $editsectionPage ) ) {
264 throw new MWException( "Bad parser output text." );
267 $skin = $wgOut->getSkin();
268 return call_user_func_array(
269 [ $skin, 'doEditSectionLink' ],
270 [ $editsectionPage, $editsectionSection,
271 $editsectionContent, $wgLang->getCode() ]
274 $text
276 } else {
277 $text = preg_replace( ParserOutput::EDITSECTION_REGEX, '', $text );
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',
287 $text
290 return $text;
294 * @param integer $id
295 * @since 1.28
297 public function setSpeculativeRevIdUsed( $id ) {
298 $this->mSpeculativeRevId = $id;
301 /** @since 1.28 */
302 public function getSpeculativeRevIdUsed() {
303 return $this->mSpeculativeRevId;
306 public function &getLanguageLinks() {
307 return $this->mLanguageLinks;
310 public function getInterwikiLinks() {
311 return $this->mInterwikiLinks;
314 public function getCategoryLinks() {
315 return array_keys( $this->mCategories );
318 public function &getCategories() {
319 return $this->mCategories;
323 * @since 1.25
325 public function getIndicators() {
326 return $this->mIndicators;
329 public function getTitleText() {
330 return $this->mTitleText;
333 public function getSections() {
334 return $this->mSections;
337 public function getEditSectionTokens() {
338 return $this->mEditSectionTokens;
341 public function &getLinks() {
342 return $this->mLinks;
345 public function &getTemplates() {
346 return $this->mTemplates;
349 public function &getTemplateIds() {
350 return $this->mTemplateIds;
353 public function &getImages() {
354 return $this->mImages;
357 public function &getFileSearchOptions() {
358 return $this->mFileSearchOptions;
361 public function &getExternalLinks() {
362 return $this->mExternalLinks;
365 public function getNoGallery() {
366 return $this->mNoGallery;
369 public function getHeadItems() {
370 return $this->mHeadItems;
373 public function getModules() {
374 return $this->mModules;
377 public function getModuleScripts() {
378 return $this->mModuleScripts;
381 public function getModuleStyles() {
382 return $this->mModuleStyles;
385 /** @since 1.23 */
386 public function getJsConfigVars() {
387 return $this->mJsConfigVars;
390 public function getOutputHooks() {
391 return (array)$this->mOutputHooks;
394 public function getWarnings() {
395 return array_keys( $this->mWarnings );
398 public function getIndexPolicy() {
399 return $this->mIndexPolicy;
402 public function getTOCHTML() {
403 return $this->mTOCHTML;
407 * @return string|null TS_MW timestamp of the revision content
409 public function getTimestamp() {
410 return $this->mTimestamp;
413 public function getLimitReportData() {
414 return $this->mLimitReportData;
417 public function getLimitReportJSData() {
418 return $this->mLimitReportJSData;
421 public function getTOCEnabled() {
422 return $this->mTOCEnabled;
425 public function getEnableOOUI() {
426 return $this->mEnableOOUI;
429 public function setText( $text ) {
430 return wfSetVar( $this->mText, $text );
433 public function setLanguageLinks( $ll ) {
434 return wfSetVar( $this->mLanguageLinks, $ll );
437 public function setCategoryLinks( $cl ) {
438 return wfSetVar( $this->mCategories, $cl );
441 public function setTitleText( $t ) {
442 return wfSetVar( $this->mTitleText, $t );
445 public function setSections( $toc ) {
446 return wfSetVar( $this->mSections, $toc );
449 public function setEditSectionTokens( $t ) {
450 return wfSetVar( $this->mEditSectionTokens, $t );
453 public function setIndexPolicy( $policy ) {
454 return wfSetVar( $this->mIndexPolicy, $policy );
457 public function setTOCHTML( $tochtml ) {
458 return wfSetVar( $this->mTOCHTML, $tochtml );
461 public function setTimestamp( $timestamp ) {
462 return wfSetVar( $this->mTimestamp, $timestamp );
465 public function setTOCEnabled( $flag ) {
466 return wfSetVar( $this->mTOCEnabled, $flag );
469 public function addCategory( $c, $sort ) {
470 $this->mCategories[$c] = $sort;
474 * @since 1.25
476 public function setIndicator( $id, $content ) {
477 $this->mIndicators[$id] = $content;
481 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
482 * object is added to.
484 * @since 1.26
485 * @param bool $enable If OOUI should be enabled or not
487 public function setEnableOOUI( $enable = false ) {
488 $this->mEnableOOUI = $enable;
491 public function addLanguageLink( $t ) {
492 $this->mLanguageLinks[] = $t;
495 public function addWarning( $s ) {
496 $this->mWarnings[$s] = 1;
499 public function addOutputHook( $hook, $data = false ) {
500 $this->mOutputHooks[] = [ $hook, $data ];
503 public function setNewSection( $value ) {
504 $this->mNewSection = (bool)$value;
506 public function hideNewSection( $value ) {
507 $this->mHideNewSection = (bool)$value;
509 public function getHideNewSection() {
510 return (bool)$this->mHideNewSection;
512 public function getNewSection() {
513 return (bool)$this->mNewSection;
517 * Checks, if a url is pointing to the own server
519 * @param string $internal The server to check against
520 * @param string $url The url to check
521 * @return bool
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
534 public function addExternalLink( $url ) {
535 # We don't register links pointing to our own server, unless... :-)
536 global $wgServer, $wgRegisterInternalExternals;
538 $registerExternalLink = true;
539 if ( !$wgRegisterInternalExternals ) {
540 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
542 if ( $registerExternalLink ) {
543 $this->mExternalLinks[$url] = 1;
548 * Record a local or interwiki inline link for saving in future link tables.
550 * @param Title $title
551 * @param int|null $id Optional known page_id so we can skip the lookup
553 public function addLink( Title $title, $id = null ) {
554 if ( $title->isExternal() ) {
555 // Don't record interwikis in pagelinks
556 $this->addInterwikiLink( $title );
557 return;
559 $ns = $title->getNamespace();
560 $dbk = $title->getDBkey();
561 if ( $ns == NS_MEDIA ) {
562 // Normalize this pseudo-alias if it makes it down here...
563 $ns = NS_FILE;
564 } elseif ( $ns == NS_SPECIAL ) {
565 // We don't record Special: links currently
566 // It might actually be wise to, but we'd need to do some normalization.
567 return;
568 } elseif ( $dbk === '' ) {
569 // Don't record self links - [[#Foo]]
570 return;
572 if ( !isset( $this->mLinks[$ns] ) ) {
573 $this->mLinks[$ns] = [];
575 if ( is_null( $id ) ) {
576 $id = $title->getArticleID();
578 $this->mLinks[$ns][$dbk] = $id;
582 * Register a file dependency for this output
583 * @param string $name Title dbKey
584 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
585 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
586 * @return void
588 public function addImage( $name, $timestamp = null, $sha1 = null ) {
589 $this->mImages[$name] = 1;
590 if ( $timestamp !== null && $sha1 !== null ) {
591 $this->mFileSearchOptions[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
596 * Register a template dependency for this output
597 * @param Title $title
598 * @param int $page_id
599 * @param int $rev_id
600 * @return void
602 public function addTemplate( $title, $page_id, $rev_id ) {
603 $ns = $title->getNamespace();
604 $dbk = $title->getDBkey();
605 if ( !isset( $this->mTemplates[$ns] ) ) {
606 $this->mTemplates[$ns] = [];
608 $this->mTemplates[$ns][$dbk] = $page_id;
609 if ( !isset( $this->mTemplateIds[$ns] ) ) {
610 $this->mTemplateIds[$ns] = [];
612 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
616 * @param Title $title Title object, must be an interwiki link
617 * @throws MWException If given invalid input
619 public function addInterwikiLink( $title ) {
620 if ( !$title->isExternal() ) {
621 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
623 $prefix = $title->getInterwiki();
624 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
625 $this->mInterwikiLinks[$prefix] = [];
627 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
631 * Add some text to the "<head>".
632 * If $tag is set, the section with that tag will only be included once
633 * in a given page.
634 * @param string $section
635 * @param string|bool $tag
637 public function addHeadItem( $section, $tag = false ) {
638 if ( $tag !== false ) {
639 $this->mHeadItems[$tag] = $section;
640 } else {
641 $this->mHeadItems[] = $section;
645 public function addModules( $modules ) {
646 $this->mModules = array_merge( $this->mModules, (array)$modules );
649 public function addModuleScripts( $modules ) {
650 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
653 public function addModuleStyles( $modules ) {
654 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
658 * Add one or more variables to be set in mw.config in JavaScript.
660 * @param string|array $keys Key or array of key/value pairs.
661 * @param mixed $value [optional] Value of the configuration variable.
662 * @since 1.23
664 public function addJsConfigVars( $keys, $value = null ) {
665 if ( is_array( $keys ) ) {
666 foreach ( $keys as $key => $value ) {
667 $this->mJsConfigVars[$key] = $value;
669 return;
672 $this->mJsConfigVars[$keys] = $value;
676 * Copy items from the OutputPage object into this one
678 * @param OutputPage $out
680 public function addOutputPageMetadata( OutputPage $out ) {
681 $this->addModules( $out->getModules() );
682 $this->addModuleScripts( $out->getModuleScripts() );
683 $this->addModuleStyles( $out->getModuleStyles() );
684 $this->addJsConfigVars( $out->getJsConfigVars() );
686 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
687 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
691 * Add a tracking category, getting the title from a system message,
692 * or print a debug message if the title is invalid.
694 * Any message used with this function should be registered so it will
695 * show up on Special:TrackingCategories. Core messages should be added
696 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
697 * should add to "TrackingCategories" in their extension.json.
699 * @param string $msg Message key
700 * @param Title $title title of the page which is being tracked
701 * @return bool Whether the addition was successful
702 * @since 1.25
704 public function addTrackingCategory( $msg, $title ) {
705 if ( $title->getNamespace() === NS_SPECIAL ) {
706 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
707 return false;
710 // Important to parse with correct title (bug 31469)
711 $cat = wfMessage( $msg )
712 ->title( $title )
713 ->inContentLanguage()
714 ->text();
716 # Allow tracking categories to be disabled by setting them to "-"
717 if ( $cat === '-' ) {
718 return false;
721 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
722 if ( $containerCategory ) {
723 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
724 return true;
725 } else {
726 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
727 return false;
732 * Override the title to be used for display
734 * @note this is assumed to have been validated
735 * (check equal normalisation, etc.)
737 * @note this is expected to be safe HTML,
738 * ready to be served to the client.
740 * @param string $text Desired title text
742 public function setDisplayTitle( $text ) {
743 $this->setTitleText( $text );
744 $this->setProperty( 'displaytitle', $text );
748 * Get the title to be used for display.
750 * As per the contract of setDisplayTitle(), this is safe HTML,
751 * ready to be served to the client.
753 * @return string HTML
755 public function getDisplayTitle() {
756 $t = $this->getTitleText();
757 if ( $t === '' ) {
758 return false;
760 return $t;
764 * Fairly generic flag setter thingy.
765 * @param string $flag
767 public function setFlag( $flag ) {
768 $this->mFlags[$flag] = true;
771 public function getFlag( $flag ) {
772 return isset( $this->mFlags[$flag] );
776 * Set a property to be stored in the page_props database table.
778 * page_props is a key value store indexed by the page ID. This allows
779 * the parser to set a property on a page which can then be quickly
780 * retrieved given the page ID or via a DB join when given the page
781 * title.
783 * Since 1.23, page_props are also indexed by numeric value, to allow
784 * for efficient "top k" queries of pages wrt a given property.
786 * setProperty() is thus used to propagate properties from the parsed
787 * page to request contexts other than a page view of the currently parsed
788 * article.
790 * Some applications examples:
792 * * To implement hidden categories, hiding pages from category listings
793 * by storing a property.
795 * * Overriding the displayed article title.
796 * @see ParserOutput::setDisplayTitle()
798 * * To implement image tagging, for example displaying an icon on an
799 * image thumbnail to indicate that it is listed for deletion on
800 * Wikimedia Commons.
801 * This is not actually implemented, yet but would be pretty cool.
803 * @note Do not use setProperty() to set a property which is only used
804 * in a context where the ParserOutput object itself is already available,
805 * for example a normal page view. There is no need to save such a property
806 * in the database since the text is already parsed. You can just hook
807 * OutputPageParserOutput and get your data out of the ParserOutput object.
809 * If you are writing an extension where you want to set a property in the
810 * parser which is used by an OutputPageParserOutput hook, you have to
811 * associate the extension data directly with the ParserOutput object.
812 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
814 * @par Example:
815 * @code
816 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
817 * @endcode
819 * And then later, in OutputPageParserOutput or similar:
821 * @par Example:
822 * @code
823 * $output->getExtensionData( 'my_ext_foo' );
824 * @endcode
826 * In MediaWiki 1.20 and older, you have to use a custom member variable
827 * within the ParserOutput object:
829 * @par Example:
830 * @code
831 * $parser->getOutput()->my_ext_foo = '...';
832 * @endcode
834 public function setProperty( $name, $value ) {
835 $this->mProperties[$name] = $value;
839 * @param string $name The property name to look up.
841 * @return mixed|bool The value previously set using setProperty(). False if null or no value
842 * was set for the given property name.
844 * @note You need to use getProperties() to check for boolean and null properties.
846 public function getProperty( $name ) {
847 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
850 public function unsetProperty( $name ) {
851 unset( $this->mProperties[$name] );
854 public function getProperties() {
855 if ( !isset( $this->mProperties ) ) {
856 $this->mProperties = [];
858 return $this->mProperties;
862 * Returns the options from its ParserOptions which have been taken
863 * into account to produce this output or false if not available.
864 * @return array
866 public function getUsedOptions() {
867 if ( !isset( $this->mAccessedOptions ) ) {
868 return [];
870 return array_keys( $this->mAccessedOptions );
874 * Tags a parser option for use in the cache key for this parser output.
875 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
876 * The information gathered here is available via getUsedOptions(),
877 * and is used by ParserCache::save().
879 * @see ParserCache::getKey
880 * @see ParserCache::save
881 * @see ParserOptions::addExtraKey
882 * @see ParserOptions::optionsHash
883 * @param string $option
885 public function recordOption( $option ) {
886 $this->mAccessedOptions[$option] = true;
890 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
891 * the ParserOutput object for later use during page output. The data will be cached along with
892 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
893 * database.
895 * This method is provided to overcome the unsafe practice of attaching extra information to a
896 * ParserObject by directly assigning member variables.
898 * To use setExtensionData() to pass extension information from a hook inside the parser to a
899 * hook in the page output, use this in the parser hook:
901 * @par Example:
902 * @code
903 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
904 * @endcode
906 * And then later, in OutputPageParserOutput or similar:
908 * @par Example:
909 * @code
910 * $output->getExtensionData( 'my_ext_foo' );
911 * @endcode
913 * In MediaWiki 1.20 and older, you have to use a custom member variable
914 * within the ParserOutput object:
916 * @par Example:
917 * @code
918 * $parser->getOutput()->my_ext_foo = '...';
919 * @endcode
921 * @since 1.21
923 * @param string $key The key for accessing the data. Extensions should take care to avoid
924 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
926 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
927 * the value.
929 public function setExtensionData( $key, $value ) {
930 if ( $value === null ) {
931 unset( $this->mExtensionData[$key] );
932 } else {
933 $this->mExtensionData[$key] = $value;
938 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
939 * Typically, such data would be set while parsing the page, e.g. by a parser function.
941 * @since 1.21
943 * @param string $key The key to look up.
945 * @return mixed|null The value previously set for the given key using setExtensionData()
946 * or null if no value was set for this key.
948 public function getExtensionData( $key ) {
949 if ( isset( $this->mExtensionData[$key] ) ) {
950 return $this->mExtensionData[$key];
953 return null;
956 private static function getTimes( $clock = null ) {
957 $ret = [];
958 if ( !$clock || $clock === 'wall' ) {
959 $ret['wall'] = microtime( true );
961 if ( !$clock || $clock === 'cpu' ) {
962 $ru = wfGetRusage();
963 if ( $ru ) {
964 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
965 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
968 return $ret;
972 * Resets the parse start timestamps for future calls to getTimeSinceStart()
973 * @since 1.22
975 public function resetParseStartTime() {
976 $this->mParseStartTime = self::getTimes();
980 * Returns the time since resetParseStartTime() was last called
982 * Clocks available are:
983 * - wall: Wall clock time
984 * - cpu: CPU time (requires getrusage)
986 * @since 1.22
987 * @param string $clock
988 * @return float|null
990 public function getTimeSinceStart( $clock ) {
991 if ( !isset( $this->mParseStartTime[$clock] ) ) {
992 return null;
995 $end = self::getTimes( $clock );
996 return $end[$clock] - $this->mParseStartTime[$clock];
1000 * Sets parser limit report data for a key
1002 * The key is used as the prefix for various messages used for formatting:
1003 * - $key: The label for the field in the limit report
1004 * - $key-value-text: Message used to format the value in the "NewPP limit
1005 * report" HTML comment. If missing, uses $key-format.
1006 * - $key-value-html: Message used to format the value in the preview
1007 * limit report table. If missing, uses $key-format.
1008 * - $key-value: Message used to format the value. If missing, uses "$1".
1010 * Note that all values are interpreted as wikitext, and so should be
1011 * encoded with htmlspecialchars() as necessary, but should avoid complex
1012 * HTML for sanity of display in the "NewPP limit report" comment.
1014 * @since 1.22
1015 * @param string $key Message key
1016 * @param mixed $value Appropriate for Message::params()
1018 public function setLimitReportData( $key, $value ) {
1019 $this->mLimitReportData[$key] = $value;
1021 if ( is_array( $value ) ) {
1022 if ( array_keys( $value ) === [ 0, 1 ]
1023 && is_numeric( $value[0] )
1024 && is_numeric( $value[1] )
1026 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1027 } else {
1028 $data = $value;
1030 } else {
1031 $data = $value;
1034 if ( strpos( $key, '-' ) ) {
1035 list( $ns, $name ) = explode( '-', $key, 2 );
1036 $this->mLimitReportJSData[$ns][$name] = $data;
1037 } else {
1038 $this->mLimitReportJSData[$key] = $data;
1043 * Check whether the cache TTL was lowered due to dynamic content
1045 * When content is determined by more than hard state (e.g. page edits),
1046 * such as template/file transclusions based on the current timestamp or
1047 * extension tags that generate lists based on queries, this return true.
1049 * @return bool
1050 * @since 1.25
1052 public function hasDynamicContent() {
1053 global $wgParserCacheExpireTime;
1055 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1059 * Get or set the prevent-clickjacking flag
1061 * @since 1.24
1062 * @param bool|null $flag New flag value, or null to leave it unchanged
1063 * @return bool Old flag value
1065 public function preventClickjacking( $flag = null ) {
1066 return wfSetVar( $this->mPreventClickjacking, $flag );
1070 * Lower the runtime adaptive TTL to at most this value
1072 * @param integer $ttl
1073 * @since 1.28
1075 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1076 $this->mMaxAdaptiveExpiry = min( $ttl, $this->mMaxAdaptiveExpiry );
1077 $this->updateCacheExpiry( $ttl );
1081 * Call this when parsing is done to lower the TTL based on low parse times
1083 * @since 1.28
1085 public function finalizeAdaptiveCacheExpiry() {
1086 if ( is_infinite( $this->mMaxAdaptiveExpiry ) ) {
1087 return; // not set
1090 $runtime = $this->getTimeSinceStart( 'wall' );
1091 if ( is_float( $runtime ) ) {
1092 $slope = ( self::SLOW_AR_TTL - self::FAST_AR_TTL )
1093 / ( self::PARSE_SLOW_SEC - self::PARSE_FAST_SEC );
1094 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1095 $point = self::SLOW_AR_TTL - self::PARSE_SLOW_SEC * $slope;
1097 $adaptiveTTL = min(
1098 max( $slope * $runtime + $point, self::MIN_AR_TTL ),
1099 $this->mMaxAdaptiveExpiry
1101 $this->updateCacheExpiry( $adaptiveTTL );
1105 public function __sleep() {
1106 return array_diff(
1107 array_keys( get_object_vars( $this ) ),
1108 [ 'mParseStartTime' ]