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
24 class ParserOutput
extends CacheTime
{
26 * Feature flag to indicate to extensions that MediaWiki core supports and
27 * uses getText() stateless transforms.
29 const SUPPORTS_STATELESS_TRANSFORMS
= 1;
32 * @var string $mText The output text
37 * @var array $mLanguageLinks List of the full text of language links,
38 * in the order they appear.
40 public $mLanguageLinks;
43 * @var array $mCategoriesMap of category names to sort keys
48 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
50 public $mIndicators = [];
53 * @var string $mTitleText Title text of the chosen language variant, as HTML.
58 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
64 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
67 public $mTemplates = [];
70 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
73 public $mTemplateIds = [];
76 * @var array $mImages DB keys of the images used, in the array key only
81 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
83 public $mFileSearchOptions = [];
86 * @var array $mExternalLinks External link URLs, in the key only.
88 public $mExternalLinks = [];
91 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
92 * for the inline interwiki links in the document.
94 public $mInterwikiLinks = [];
97 * @var bool $mNewSection Show a new section link?
99 public $mNewSection = false;
102 * @var bool $mHideNewSection Hide the new section link?
104 public $mHideNewSection = false;
107 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
109 public $mNoGallery = false;
112 * @var array $mHeadItems Items to put in the <head> section
114 public $mHeadItems = [];
117 * @var array $mModules Modules to be loaded by ResourceLoader
119 public $mModules = [];
122 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
124 public $mModuleScripts = [];
127 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
129 public $mModuleStyles = [];
132 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
134 public $mJsConfigVars = [];
137 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
139 public $mOutputHooks = [];
142 * @var array $mWarnings Warning text to be returned to the user.
143 * Wikitext formatted, in the key only.
145 public $mWarnings = [];
148 * @var array $mSections Table of contents
150 public $mSections = [];
153 * @deprecated since 1.31 Use getText() options.
154 * @var bool $mEditSectionTokens prefix/suffix markers if edit sections were output as tokens.
156 public $mEditSectionTokens = true;
159 * @var array $mProperties Name/value pairs to be cached in the DB.
161 public $mProperties = [];
164 * @var string $mTOCHTML HTML of the TOC.
166 public $mTOCHTML = '';
169 * @var string $mTimestamp Timestamp of the revision.
174 * @deprecated since 1.31 Use getText() options.
175 * @var bool $mTOCEnabled Whether TOC should be shown, can't override __NOTOC__.
177 public $mTOCEnabled = true;
180 * @var bool $mEnableOOUI Whether OOUI should be enabled.
182 public $mEnableOOUI = false;
185 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
187 private $mIndexPolicy = '';
190 * @var array $mAccessedOptions List of ParserOptions (stored in the keys).
192 private $mAccessedOptions = [];
195 * @var array $mExtensionData extra data used by extensions.
197 private $mExtensionData = [];
200 * @var array $mLimitReportData Parser limit report data.
202 private $mLimitReportData = [];
204 /** @var array Parser limit report data for JSON */
205 private $mLimitReportJSData = [];
208 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
210 private $mParseStartTime = [];
213 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
215 private $mPreventClickjacking = false;
218 * @var array $mFlags Generic flags.
220 private $mFlags = [];
222 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
223 private $mSpeculativeRevId;
225 /** @var int Upper bound of expiry based on parse duration */
226 private $mMaxAdaptiveExpiry = INF
;
228 const EDITSECTION_REGEX
=
229 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
231 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
232 // Current values imply that m=3933.333333 and b=-333.333333
233 // See https://www.nngroup.com/articles/website-response-times/
234 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
235 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
236 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
237 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
238 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
240 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
241 $unused = false, $titletext = ''
243 $this->mText
= $text;
244 $this->mLanguageLinks
= $languageLinks;
245 $this->mCategories
= $categoryLinks;
246 $this->mTitleText
= $titletext;
250 * Get the cacheable text with <mw:editsection> markers still in it. The
251 * return value is suitable for writing back via setText() but is not valid
252 * for display to the user.
257 public function getRawText() {
262 * Get the output HTML
264 * @param array $options (since 1.31) Transformations to apply to the HTML
265 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
266 * to generate one and `__NOTOC__` wasn't used. Default is true,
267 * but might be statefully overridden.
268 * - enableSectionEditLinks: (bool) Include section edit links, assuming
269 * section edit link tokens are present in the HTML. Default is true,
270 * but might be statefully overridden.
271 * @return string HTML
273 public function getText( $options = [] ) {
274 if ( !array_key_exists( 'allowTOC', $options ) && empty( $this->mTOCEnabled
) ) {
275 wfDeprecated( 'ParserOutput stateful allowTOC', '1.31' );
278 // Note that while $this->mEditSectionTokens formerly defaulted to false,
279 // ParserOptions->getEditSection() defaults to true and Parser copies
280 // that to us so true makes more sense as the stateless default.
281 if ( !array_key_exists( 'enableSectionEditLinks', $options ) && !$this->mEditSectionTokens
) {
282 wfDeprecated( 'ParserOutput stateful enableSectionEditLinks', '1.31' );
286 // empty() here because old cached versions might lack the field somehow.
287 // In that situation, the historical behavior (possibly buggy) is to remove the TOC.
288 'allowTOC' => !empty( $this->mTOCEnabled
),
289 'enableSectionEditLinks' => $this->mEditSectionTokens
,
291 $text = $this->mText
;
293 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
295 if ( $options['enableSectionEditLinks'] ) {
296 $text = preg_replace_callback(
297 self
::EDITSECTION_REGEX
,
299 global $wgOut, $wgLang;
300 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
301 $editsectionSection = htmlspecialchars_decode( $m[2] );
302 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
304 if ( !is_object( $editsectionPage ) ) {
305 throw new MWException( "Bad parser output text." );
308 $skin = $wgOut->getSkin();
309 return call_user_func_array(
310 [ $skin, 'doEditSectionLink' ],
311 [ $editsectionPage, $editsectionSection,
312 $editsectionContent, $wgLang->getCode() ]
318 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
321 if ( $options['allowTOC'] ) {
322 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
324 $text = preg_replace(
325 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
338 public function setSpeculativeRevIdUsed( $id ) {
339 $this->mSpeculativeRevId
= $id;
346 public function getSpeculativeRevIdUsed() {
347 return $this->mSpeculativeRevId
;
350 public function &getLanguageLinks() {
351 return $this->mLanguageLinks
;
354 public function getInterwikiLinks() {
355 return $this->mInterwikiLinks
;
358 public function getCategoryLinks() {
359 return array_keys( $this->mCategories
);
362 public function &getCategories() {
363 return $this->mCategories
;
370 public function getIndicators() {
371 return $this->mIndicators
;
374 public function getTitleText() {
375 return $this->mTitleText
;
378 public function getSections() {
379 return $this->mSections
;
383 * @deprecated since 1.31 Use getText() options.
385 public function getEditSectionTokens() {
386 return $this->mEditSectionTokens
;
389 public function &getLinks() {
390 return $this->mLinks
;
393 public function &getTemplates() {
394 return $this->mTemplates
;
397 public function &getTemplateIds() {
398 return $this->mTemplateIds
;
401 public function &getImages() {
402 return $this->mImages
;
405 public function &getFileSearchOptions() {
406 return $this->mFileSearchOptions
;
409 public function &getExternalLinks() {
410 return $this->mExternalLinks
;
413 public function getNoGallery() {
414 return $this->mNoGallery
;
417 public function getHeadItems() {
418 return $this->mHeadItems
;
421 public function getModules() {
422 return $this->mModules
;
425 public function getModuleScripts() {
426 return $this->mModuleScripts
;
429 public function getModuleStyles() {
430 return $this->mModuleStyles
;
437 public function getJsConfigVars() {
438 return $this->mJsConfigVars
;
441 public function getOutputHooks() {
442 return (array)$this->mOutputHooks
;
445 public function getWarnings() {
446 return array_keys( $this->mWarnings
);
449 public function getIndexPolicy() {
450 return $this->mIndexPolicy
;
453 public function getTOCHTML() {
454 return $this->mTOCHTML
;
458 * @return string|null TS_MW timestamp of the revision content
460 public function getTimestamp() {
461 return $this->mTimestamp
;
464 public function getLimitReportData() {
465 return $this->mLimitReportData
;
468 public function getLimitReportJSData() {
469 return $this->mLimitReportJSData
;
473 * @deprecated since 1.31 Use getText() options.
475 public function getTOCEnabled() {
476 return $this->mTOCEnabled
;
479 public function getEnableOOUI() {
480 return $this->mEnableOOUI
;
483 public function setText( $text ) {
484 return wfSetVar( $this->mText
, $text );
487 public function setLanguageLinks( $ll ) {
488 return wfSetVar( $this->mLanguageLinks
, $ll );
491 public function setCategoryLinks( $cl ) {
492 return wfSetVar( $this->mCategories
, $cl );
495 public function setTitleText( $t ) {
496 return wfSetVar( $this->mTitleText
, $t );
499 public function setSections( $toc ) {
500 return wfSetVar( $this->mSections
, $toc );
504 * @deprecated since 1.31 Use getText() options.
506 public function setEditSectionTokens( $t ) {
507 return wfSetVar( $this->mEditSectionTokens
, $t );
510 public function setIndexPolicy( $policy ) {
511 return wfSetVar( $this->mIndexPolicy
, $policy );
514 public function setTOCHTML( $tochtml ) {
515 return wfSetVar( $this->mTOCHTML
, $tochtml );
518 public function setTimestamp( $timestamp ) {
519 return wfSetVar( $this->mTimestamp
, $timestamp );
523 * @deprecated since 1.31 Use getText() options.
525 public function setTOCEnabled( $flag ) {
526 return wfSetVar( $this->mTOCEnabled
, $flag );
529 public function addCategory( $c, $sort ) {
530 $this->mCategories
[$c] = $sort;
535 * @param string $content
538 public function setIndicator( $id, $content ) {
539 $this->mIndicators
[$id] = $content;
543 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
544 * object is added to.
547 * @param bool $enable If OOUI should be enabled or not
549 public function setEnableOOUI( $enable = false ) {
550 $this->mEnableOOUI
= $enable;
553 public function addLanguageLink( $t ) {
554 $this->mLanguageLinks
[] = $t;
557 public function addWarning( $s ) {
558 $this->mWarnings
[$s] = 1;
561 public function addOutputHook( $hook, $data = false ) {
562 $this->mOutputHooks
[] = [ $hook, $data ];
565 public function setNewSection( $value ) {
566 $this->mNewSection
= (bool)$value;
568 public function hideNewSection( $value ) {
569 $this->mHideNewSection
= (bool)$value;
571 public function getHideNewSection() {
572 return (bool)$this->mHideNewSection
;
574 public function getNewSection() {
575 return (bool)$this->mNewSection
;
579 * Checks, if a url is pointing to the own server
581 * @param string $internal The server to check against
582 * @param string $url The url to check
585 public static function isLinkInternal( $internal, $url ) {
586 return (bool)preg_match( '/^' .
587 # If server is proto relative, check also for http/https links
588 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
589 preg_quote( $internal, '/' ) .
590 # check for query/path/anchor or end of link in each case
596 public function addExternalLink( $url ) {
597 # We don't register links pointing to our own server, unless... :-)
598 global $wgServer, $wgRegisterInternalExternals;
600 # Replace unnecessary URL escape codes with the referenced character
601 # This prevents spammers from hiding links from the filters
602 $url = parser
::normalizeLinkUrl( $url );
604 $registerExternalLink = true;
605 if ( !$wgRegisterInternalExternals ) {
606 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
608 if ( $registerExternalLink ) {
609 $this->mExternalLinks
[$url] = 1;
614 * Record a local or interwiki inline link for saving in future link tables.
616 * @param Title $title
617 * @param int|null $id Optional known page_id so we can skip the lookup
619 public function addLink( Title
$title, $id = null ) {
620 if ( $title->isExternal() ) {
621 // Don't record interwikis in pagelinks
622 $this->addInterwikiLink( $title );
625 $ns = $title->getNamespace();
626 $dbk = $title->getDBkey();
627 if ( $ns == NS_MEDIA
) {
628 // Normalize this pseudo-alias if it makes it down here...
630 } elseif ( $ns == NS_SPECIAL
) {
631 // We don't record Special: links currently
632 // It might actually be wise to, but we'd need to do some normalization.
634 } elseif ( $dbk === '' ) {
635 // Don't record self links - [[#Foo]]
638 if ( !isset( $this->mLinks
[$ns] ) ) {
639 $this->mLinks
[$ns] = [];
641 if ( is_null( $id ) ) {
642 $id = $title->getArticleID();
644 $this->mLinks
[$ns][$dbk] = $id;
648 * Register a file dependency for this output
649 * @param string $name Title dbKey
650 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
651 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
654 public function addImage( $name, $timestamp = null, $sha1 = null ) {
655 $this->mImages
[$name] = 1;
656 if ( $timestamp !== null && $sha1 !== null ) {
657 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
662 * Register a template dependency for this output
663 * @param Title $title
664 * @param int $page_id
668 public function addTemplate( $title, $page_id, $rev_id ) {
669 $ns = $title->getNamespace();
670 $dbk = $title->getDBkey();
671 if ( !isset( $this->mTemplates
[$ns] ) ) {
672 $this->mTemplates
[$ns] = [];
674 $this->mTemplates
[$ns][$dbk] = $page_id;
675 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
676 $this->mTemplateIds
[$ns] = [];
678 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
682 * @param Title $title Title object, must be an interwiki link
683 * @throws MWException If given invalid input
685 public function addInterwikiLink( $title ) {
686 if ( !$title->isExternal() ) {
687 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
689 $prefix = $title->getInterwiki();
690 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
691 $this->mInterwikiLinks
[$prefix] = [];
693 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
697 * Add some text to the "<head>".
698 * If $tag is set, the section with that tag will only be included once
700 * @param string $section
701 * @param string|bool $tag
703 public function addHeadItem( $section, $tag = false ) {
704 if ( $tag !== false ) {
705 $this->mHeadItems
[$tag] = $section;
707 $this->mHeadItems
[] = $section;
711 public function addModules( $modules ) {
712 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
715 public function addModuleScripts( $modules ) {
716 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
719 public function addModuleStyles( $modules ) {
720 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
724 * Add one or more variables to be set in mw.config in JavaScript.
726 * @param string|array $keys Key or array of key/value pairs.
727 * @param mixed $value [optional] Value of the configuration variable.
730 public function addJsConfigVars( $keys, $value = null ) {
731 if ( is_array( $keys ) ) {
732 foreach ( $keys as $key => $value ) {
733 $this->mJsConfigVars
[$key] = $value;
738 $this->mJsConfigVars
[$keys] = $value;
742 * Copy items from the OutputPage object into this one
744 * @param OutputPage $out
746 public function addOutputPageMetadata( OutputPage
$out ) {
747 $this->addModules( $out->getModules() );
748 $this->addModuleScripts( $out->getModuleScripts() );
749 $this->addModuleStyles( $out->getModuleStyles() );
750 $this->addJsConfigVars( $out->getJsConfigVars() );
752 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
753 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
757 * Add a tracking category, getting the title from a system message,
758 * or print a debug message if the title is invalid.
760 * Any message used with this function should be registered so it will
761 * show up on Special:TrackingCategories. Core messages should be added
762 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
763 * should add to "TrackingCategories" in their extension.json.
765 * @todo Migrate some code to TrackingCategories
767 * @param string $msg Message key
768 * @param Title $title title of the page which is being tracked
769 * @return bool Whether the addition was successful
772 public function addTrackingCategory( $msg, $title ) {
773 if ( $title->isSpecialPage() ) {
774 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
778 // Important to parse with correct title (T33469)
779 $cat = wfMessage( $msg )
781 ->inContentLanguage()
784 # Allow tracking categories to be disabled by setting them to "-"
785 if ( $cat === '-' ) {
789 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
790 if ( $containerCategory ) {
791 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
794 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
800 * Override the title to be used for display
802 * @note this is assumed to have been validated
803 * (check equal normalisation, etc.)
805 * @note this is expected to be safe HTML,
806 * ready to be served to the client.
808 * @param string $text Desired title text
810 public function setDisplayTitle( $text ) {
811 $this->setTitleText( $text );
812 $this->setProperty( 'displaytitle', $text );
816 * Get the title to be used for display.
818 * As per the contract of setDisplayTitle(), this is safe HTML,
819 * ready to be served to the client.
821 * @return string HTML
823 public function getDisplayTitle() {
824 $t = $this->getTitleText();
832 * Fairly generic flag setter thingy.
833 * @param string $flag
835 public function setFlag( $flag ) {
836 $this->mFlags
[$flag] = true;
839 public function getFlag( $flag ) {
840 return isset( $this->mFlags
[$flag] );
844 * Set a property to be stored in the page_props database table.
846 * page_props is a key value store indexed by the page ID. This allows
847 * the parser to set a property on a page which can then be quickly
848 * retrieved given the page ID or via a DB join when given the page
851 * Since 1.23, page_props are also indexed by numeric value, to allow
852 * for efficient "top k" queries of pages wrt a given property.
854 * setProperty() is thus used to propagate properties from the parsed
855 * page to request contexts other than a page view of the currently parsed
858 * Some applications examples:
860 * * To implement hidden categories, hiding pages from category listings
861 * by storing a property.
863 * * Overriding the displayed article title.
864 * @see ParserOutput::setDisplayTitle()
866 * * To implement image tagging, for example displaying an icon on an
867 * image thumbnail to indicate that it is listed for deletion on
869 * This is not actually implemented, yet but would be pretty cool.
871 * @note Do not use setProperty() to set a property which is only used
872 * in a context where the ParserOutput object itself is already available,
873 * for example a normal page view. There is no need to save such a property
874 * in the database since the text is already parsed. You can just hook
875 * OutputPageParserOutput and get your data out of the ParserOutput object.
877 * If you are writing an extension where you want to set a property in the
878 * parser which is used by an OutputPageParserOutput hook, you have to
879 * associate the extension data directly with the ParserOutput object.
880 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
884 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
887 * And then later, in OutputPageParserOutput or similar:
891 * $output->getExtensionData( 'my_ext_foo' );
894 * In MediaWiki 1.20 and older, you have to use a custom member variable
895 * within the ParserOutput object:
899 * $parser->getOutput()->my_ext_foo = '...';
901 * @param string $name
902 * @param mixed $value
904 public function setProperty( $name, $value ) {
905 $this->mProperties
[$name] = $value;
909 * @param string $name The property name to look up.
911 * @return mixed|bool The value previously set using setProperty(). False if null or no value
912 * was set for the given property name.
914 * @note You need to use getProperties() to check for boolean and null properties.
916 public function getProperty( $name ) {
917 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
920 public function unsetProperty( $name ) {
921 unset( $this->mProperties
[$name] );
924 public function getProperties() {
925 if ( !isset( $this->mProperties
) ) {
926 $this->mProperties
= [];
928 return $this->mProperties
;
932 * Returns the options from its ParserOptions which have been taken
933 * into account to produce this output or false if not available.
936 public function getUsedOptions() {
937 if ( !isset( $this->mAccessedOptions
) ) {
940 return array_keys( $this->mAccessedOptions
);
944 * Tags a parser option for use in the cache key for this parser output.
945 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
946 * The information gathered here is available via getUsedOptions(),
947 * and is used by ParserCache::save().
949 * @see ParserCache::getKey
950 * @see ParserCache::save
951 * @see ParserOptions::addExtraKey
952 * @see ParserOptions::optionsHash
953 * @param string $option
955 public function recordOption( $option ) {
956 $this->mAccessedOptions
[$option] = true;
960 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
961 * the ParserOutput object for later use during page output. The data will be cached along with
962 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
965 * This method is provided to overcome the unsafe practice of attaching extra information to a
966 * ParserObject by directly assigning member variables.
968 * To use setExtensionData() to pass extension information from a hook inside the parser to a
969 * hook in the page output, use this in the parser hook:
973 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
976 * And then later, in OutputPageParserOutput or similar:
980 * $output->getExtensionData( 'my_ext_foo' );
983 * In MediaWiki 1.20 and older, you have to use a custom member variable
984 * within the ParserOutput object:
988 * $parser->getOutput()->my_ext_foo = '...';
993 * @param string $key The key for accessing the data. Extensions should take care to avoid
994 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
996 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
999 public function setExtensionData( $key, $value ) {
1000 if ( $value === null ) {
1001 unset( $this->mExtensionData
[$key] );
1003 $this->mExtensionData
[$key] = $value;
1008 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1009 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1013 * @param string $key The key to look up.
1015 * @return mixed|null The value previously set for the given key using setExtensionData()
1016 * or null if no value was set for this key.
1018 public function getExtensionData( $key ) {
1019 if ( isset( $this->mExtensionData
[$key] ) ) {
1020 return $this->mExtensionData
[$key];
1026 private static function getTimes( $clock = null ) {
1028 if ( !$clock ||
$clock === 'wall' ) {
1029 $ret['wall'] = microtime( true );
1031 if ( !$clock ||
$clock === 'cpu' ) {
1032 $ru = wfGetRusage();
1034 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1035 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1042 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1045 public function resetParseStartTime() {
1046 $this->mParseStartTime
= self
::getTimes();
1050 * Returns the time since resetParseStartTime() was last called
1052 * Clocks available are:
1053 * - wall: Wall clock time
1054 * - cpu: CPU time (requires getrusage)
1057 * @param string $clock
1058 * @return float|null
1060 public function getTimeSinceStart( $clock ) {
1061 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1065 $end = self
::getTimes( $clock );
1066 return $end[$clock] - $this->mParseStartTime
[$clock];
1070 * Sets parser limit report data for a key
1072 * The key is used as the prefix for various messages used for formatting:
1073 * - $key: The label for the field in the limit report
1074 * - $key-value-text: Message used to format the value in the "NewPP limit
1075 * report" HTML comment. If missing, uses $key-format.
1076 * - $key-value-html: Message used to format the value in the preview
1077 * limit report table. If missing, uses $key-format.
1078 * - $key-value: Message used to format the value. If missing, uses "$1".
1080 * Note that all values are interpreted as wikitext, and so should be
1081 * encoded with htmlspecialchars() as necessary, but should avoid complex
1082 * HTML for sanity of display in the "NewPP limit report" comment.
1085 * @param string $key Message key
1086 * @param mixed $value Appropriate for Message::params()
1088 public function setLimitReportData( $key, $value ) {
1089 $this->mLimitReportData
[$key] = $value;
1091 if ( is_array( $value ) ) {
1092 if ( array_keys( $value ) === [ 0, 1 ]
1093 && is_numeric( $value[0] )
1094 && is_numeric( $value[1] )
1096 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1104 if ( strpos( $key, '-' ) ) {
1105 list( $ns, $name ) = explode( '-', $key, 2 );
1106 $this->mLimitReportJSData
[$ns][$name] = $data;
1108 $this->mLimitReportJSData
[$key] = $data;
1113 * Check whether the cache TTL was lowered due to dynamic content
1115 * When content is determined by more than hard state (e.g. page edits),
1116 * such as template/file transclusions based on the current timestamp or
1117 * extension tags that generate lists based on queries, this return true.
1122 public function hasDynamicContent() {
1123 global $wgParserCacheExpireTime;
1125 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1129 * Get or set the prevent-clickjacking flag
1132 * @param bool|null $flag New flag value, or null to leave it unchanged
1133 * @return bool Old flag value
1135 public function preventClickjacking( $flag = null ) {
1136 return wfSetVar( $this->mPreventClickjacking
, $flag );
1140 * Lower the runtime adaptive TTL to at most this value
1145 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1146 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1147 $this->updateCacheExpiry( $ttl );
1151 * Call this when parsing is done to lower the TTL based on low parse times
1155 public function finalizeAdaptiveCacheExpiry() {
1156 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1160 $runtime = $this->getTimeSinceStart( 'wall' );
1161 if ( is_float( $runtime ) ) {
1162 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1163 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1164 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1165 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1168 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1169 $this->mMaxAdaptiveExpiry
1171 $this->updateCacheExpiry( $adaptiveTTL );
1175 public function __sleep() {
1177 array_keys( get_object_vars( $this ) ),
1178 [ 'mParseStartTime' ]