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 // @todo Warn if !array_key_exists( 'allowTOC', $options ) && empty( $this->mTOCEnabled )
276 // @todo Warn if !array_key_exists( 'enableSectionEditLinks', $options )
277 // && !$this->mEditSectionTokens
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.
283 // empty() here because old cached versions might lack the field somehow.
284 // In that situation, the historical behavior (possibly buggy) is to remove the TOC.
285 'allowTOC' => !empty( $this->mTOCEnabled
),
286 'enableSectionEditLinks' => $this->mEditSectionTokens
,
288 $text = $this->mText
;
290 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
292 if ( $options['enableSectionEditLinks'] ) {
293 $text = preg_replace_callback(
294 self
::EDITSECTION_REGEX
,
296 global $wgOut, $wgLang;
297 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
298 $editsectionSection = htmlspecialchars_decode( $m[2] );
299 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
301 if ( !is_object( $editsectionPage ) ) {
302 throw new MWException( "Bad parser output text." );
305 $skin = $wgOut->getSkin();
306 return call_user_func_array(
307 [ $skin, 'doEditSectionLink' ],
308 [ $editsectionPage, $editsectionSection,
309 $editsectionContent, $wgLang->getCode() ]
315 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
318 if ( $options['allowTOC'] ) {
319 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
321 $text = preg_replace(
322 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
335 public function setSpeculativeRevIdUsed( $id ) {
336 $this->mSpeculativeRevId
= $id;
343 public function getSpeculativeRevIdUsed() {
344 return $this->mSpeculativeRevId
;
347 public function &getLanguageLinks() {
348 return $this->mLanguageLinks
;
351 public function getInterwikiLinks() {
352 return $this->mInterwikiLinks
;
355 public function getCategoryLinks() {
356 return array_keys( $this->mCategories
);
359 public function &getCategories() {
360 return $this->mCategories
;
367 public function getIndicators() {
368 return $this->mIndicators
;
371 public function getTitleText() {
372 return $this->mTitleText
;
375 public function getSections() {
376 return $this->mSections
;
380 * @deprecated since 1.31 Use getText() options.
382 public function getEditSectionTokens() {
383 return $this->mEditSectionTokens
;
386 public function &getLinks() {
387 return $this->mLinks
;
390 public function &getTemplates() {
391 return $this->mTemplates
;
394 public function &getTemplateIds() {
395 return $this->mTemplateIds
;
398 public function &getImages() {
399 return $this->mImages
;
402 public function &getFileSearchOptions() {
403 return $this->mFileSearchOptions
;
406 public function &getExternalLinks() {
407 return $this->mExternalLinks
;
410 public function getNoGallery() {
411 return $this->mNoGallery
;
414 public function getHeadItems() {
415 return $this->mHeadItems
;
418 public function getModules() {
419 return $this->mModules
;
422 public function getModuleScripts() {
423 return $this->mModuleScripts
;
426 public function getModuleStyles() {
427 return $this->mModuleStyles
;
434 public function getJsConfigVars() {
435 return $this->mJsConfigVars
;
438 public function getOutputHooks() {
439 return (array)$this->mOutputHooks
;
442 public function getWarnings() {
443 return array_keys( $this->mWarnings
);
446 public function getIndexPolicy() {
447 return $this->mIndexPolicy
;
450 public function getTOCHTML() {
451 return $this->mTOCHTML
;
455 * @return string|null TS_MW timestamp of the revision content
457 public function getTimestamp() {
458 return $this->mTimestamp
;
461 public function getLimitReportData() {
462 return $this->mLimitReportData
;
465 public function getLimitReportJSData() {
466 return $this->mLimitReportJSData
;
470 * @deprecated since 1.31 Use getText() options.
472 public function getTOCEnabled() {
473 return $this->mTOCEnabled
;
476 public function getEnableOOUI() {
477 return $this->mEnableOOUI
;
480 public function setText( $text ) {
481 return wfSetVar( $this->mText
, $text );
484 public function setLanguageLinks( $ll ) {
485 return wfSetVar( $this->mLanguageLinks
, $ll );
488 public function setCategoryLinks( $cl ) {
489 return wfSetVar( $this->mCategories
, $cl );
492 public function setTitleText( $t ) {
493 return wfSetVar( $this->mTitleText
, $t );
496 public function setSections( $toc ) {
497 return wfSetVar( $this->mSections
, $toc );
501 * @deprecated since 1.31 Use getText() options.
503 public function setEditSectionTokens( $t ) {
504 return wfSetVar( $this->mEditSectionTokens
, $t );
507 public function setIndexPolicy( $policy ) {
508 return wfSetVar( $this->mIndexPolicy
, $policy );
511 public function setTOCHTML( $tochtml ) {
512 return wfSetVar( $this->mTOCHTML
, $tochtml );
515 public function setTimestamp( $timestamp ) {
516 return wfSetVar( $this->mTimestamp
, $timestamp );
520 * @deprecated since 1.31 Use getText() options.
522 public function setTOCEnabled( $flag ) {
523 return wfSetVar( $this->mTOCEnabled
, $flag );
526 public function addCategory( $c, $sort ) {
527 $this->mCategories
[$c] = $sort;
532 * @param string $content
535 public function setIndicator( $id, $content ) {
536 $this->mIndicators
[$id] = $content;
540 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
541 * object is added to.
544 * @param bool $enable If OOUI should be enabled or not
546 public function setEnableOOUI( $enable = false ) {
547 $this->mEnableOOUI
= $enable;
550 public function addLanguageLink( $t ) {
551 $this->mLanguageLinks
[] = $t;
554 public function addWarning( $s ) {
555 $this->mWarnings
[$s] = 1;
558 public function addOutputHook( $hook, $data = false ) {
559 $this->mOutputHooks
[] = [ $hook, $data ];
562 public function setNewSection( $value ) {
563 $this->mNewSection
= (bool)$value;
565 public function hideNewSection( $value ) {
566 $this->mHideNewSection
= (bool)$value;
568 public function getHideNewSection() {
569 return (bool)$this->mHideNewSection
;
571 public function getNewSection() {
572 return (bool)$this->mNewSection
;
576 * Checks, if a url is pointing to the own server
578 * @param string $internal The server to check against
579 * @param string $url The url to check
582 public static function isLinkInternal( $internal, $url ) {
583 return (bool)preg_match( '/^' .
584 # If server is proto relative, check also for http/https links
585 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
586 preg_quote( $internal, '/' ) .
587 # check for query/path/anchor or end of link in each case
593 public function addExternalLink( $url ) {
594 # We don't register links pointing to our own server, unless... :-)
595 global $wgServer, $wgRegisterInternalExternals;
597 # Replace unnecessary URL escape codes with the referenced character
598 # This prevents spammers from hiding links from the filters
599 $url = Parser
::normalizeLinkUrl( $url );
601 $registerExternalLink = true;
602 if ( !$wgRegisterInternalExternals ) {
603 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
605 if ( $registerExternalLink ) {
606 $this->mExternalLinks
[$url] = 1;
611 * Record a local or interwiki inline link for saving in future link tables.
613 * @param Title $title
614 * @param int|null $id Optional known page_id so we can skip the lookup
616 public function addLink( Title
$title, $id = null ) {
617 if ( $title->isExternal() ) {
618 // Don't record interwikis in pagelinks
619 $this->addInterwikiLink( $title );
622 $ns = $title->getNamespace();
623 $dbk = $title->getDBkey();
624 if ( $ns == NS_MEDIA
) {
625 // Normalize this pseudo-alias if it makes it down here...
627 } elseif ( $ns == NS_SPECIAL
) {
628 // We don't record Special: links currently
629 // It might actually be wise to, but we'd need to do some normalization.
631 } elseif ( $dbk === '' ) {
632 // Don't record self links - [[#Foo]]
635 if ( !isset( $this->mLinks
[$ns] ) ) {
636 $this->mLinks
[$ns] = [];
638 if ( is_null( $id ) ) {
639 $id = $title->getArticleID();
641 $this->mLinks
[$ns][$dbk] = $id;
645 * Register a file dependency for this output
646 * @param string $name Title dbKey
647 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
648 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
651 public function addImage( $name, $timestamp = null, $sha1 = null ) {
652 $this->mImages
[$name] = 1;
653 if ( $timestamp !== null && $sha1 !== null ) {
654 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
659 * Register a template dependency for this output
660 * @param Title $title
661 * @param int $page_id
665 public function addTemplate( $title, $page_id, $rev_id ) {
666 $ns = $title->getNamespace();
667 $dbk = $title->getDBkey();
668 if ( !isset( $this->mTemplates
[$ns] ) ) {
669 $this->mTemplates
[$ns] = [];
671 $this->mTemplates
[$ns][$dbk] = $page_id;
672 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
673 $this->mTemplateIds
[$ns] = [];
675 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
679 * @param Title $title Title object, must be an interwiki link
680 * @throws MWException If given invalid input
682 public function addInterwikiLink( $title ) {
683 if ( !$title->isExternal() ) {
684 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
686 $prefix = $title->getInterwiki();
687 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
688 $this->mInterwikiLinks
[$prefix] = [];
690 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
694 * Add some text to the "<head>".
695 * If $tag is set, the section with that tag will only be included once
697 * @param string $section
698 * @param string|bool $tag
700 public function addHeadItem( $section, $tag = false ) {
701 if ( $tag !== false ) {
702 $this->mHeadItems
[$tag] = $section;
704 $this->mHeadItems
[] = $section;
708 public function addModules( $modules ) {
709 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
712 public function addModuleScripts( $modules ) {
713 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
716 public function addModuleStyles( $modules ) {
717 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
721 * Add one or more variables to be set in mw.config in JavaScript.
723 * @param string|array $keys Key or array of key/value pairs.
724 * @param mixed $value [optional] Value of the configuration variable.
727 public function addJsConfigVars( $keys, $value = null ) {
728 if ( is_array( $keys ) ) {
729 foreach ( $keys as $key => $value ) {
730 $this->mJsConfigVars
[$key] = $value;
735 $this->mJsConfigVars
[$keys] = $value;
739 * Copy items from the OutputPage object into this one
741 * @param OutputPage $out
743 public function addOutputPageMetadata( OutputPage
$out ) {
744 $this->addModules( $out->getModules() );
745 $this->addModuleScripts( $out->getModuleScripts() );
746 $this->addModuleStyles( $out->getModuleStyles() );
747 $this->addJsConfigVars( $out->getJsConfigVars() );
749 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
750 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
754 * Add a tracking category, getting the title from a system message,
755 * or print a debug message if the title is invalid.
757 * Any message used with this function should be registered so it will
758 * show up on Special:TrackingCategories. Core messages should be added
759 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
760 * should add to "TrackingCategories" in their extension.json.
762 * @todo Migrate some code to TrackingCategories
764 * @param string $msg Message key
765 * @param Title $title title of the page which is being tracked
766 * @return bool Whether the addition was successful
769 public function addTrackingCategory( $msg, $title ) {
770 if ( $title->isSpecialPage() ) {
771 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
775 // Important to parse with correct title (T33469)
776 $cat = wfMessage( $msg )
778 ->inContentLanguage()
781 # Allow tracking categories to be disabled by setting them to "-"
782 if ( $cat === '-' ) {
786 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
787 if ( $containerCategory ) {
788 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
791 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
797 * Override the title to be used for display
799 * @note this is assumed to have been validated
800 * (check equal normalisation, etc.)
802 * @note this is expected to be safe HTML,
803 * ready to be served to the client.
805 * @param string $text Desired title text
807 public function setDisplayTitle( $text ) {
808 $this->setTitleText( $text );
809 $this->setProperty( 'displaytitle', $text );
813 * Get the title to be used for display.
815 * As per the contract of setDisplayTitle(), this is safe HTML,
816 * ready to be served to the client.
818 * @return string HTML
820 public function getDisplayTitle() {
821 $t = $this->getTitleText();
829 * Fairly generic flag setter thingy.
830 * @param string $flag
832 public function setFlag( $flag ) {
833 $this->mFlags
[$flag] = true;
836 public function getFlag( $flag ) {
837 return isset( $this->mFlags
[$flag] );
841 * Set a property to be stored in the page_props database table.
843 * page_props is a key value store indexed by the page ID. This allows
844 * the parser to set a property on a page which can then be quickly
845 * retrieved given the page ID or via a DB join when given the page
848 * Since 1.23, page_props are also indexed by numeric value, to allow
849 * for efficient "top k" queries of pages wrt a given property.
851 * setProperty() is thus used to propagate properties from the parsed
852 * page to request contexts other than a page view of the currently parsed
855 * Some applications examples:
857 * * To implement hidden categories, hiding pages from category listings
858 * by storing a property.
860 * * Overriding the displayed article title.
861 * @see ParserOutput::setDisplayTitle()
863 * * To implement image tagging, for example displaying an icon on an
864 * image thumbnail to indicate that it is listed for deletion on
866 * This is not actually implemented, yet but would be pretty cool.
868 * @note Do not use setProperty() to set a property which is only used
869 * in a context where the ParserOutput object itself is already available,
870 * for example a normal page view. There is no need to save such a property
871 * in the database since the text is already parsed. You can just hook
872 * OutputPageParserOutput and get your data out of the ParserOutput object.
874 * If you are writing an extension where you want to set a property in the
875 * parser which is used by an OutputPageParserOutput hook, you have to
876 * associate the extension data directly with the ParserOutput object.
877 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
881 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
884 * And then later, in OutputPageParserOutput or similar:
888 * $output->getExtensionData( 'my_ext_foo' );
891 * In MediaWiki 1.20 and older, you have to use a custom member variable
892 * within the ParserOutput object:
896 * $parser->getOutput()->my_ext_foo = '...';
898 * @param string $name
899 * @param mixed $value
901 public function setProperty( $name, $value ) {
902 $this->mProperties
[$name] = $value;
906 * @param string $name The property name to look up.
908 * @return mixed|bool The value previously set using setProperty(). False if null or no value
909 * was set for the given property name.
911 * @note You need to use getProperties() to check for boolean and null properties.
913 public function getProperty( $name ) {
914 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
917 public function unsetProperty( $name ) {
918 unset( $this->mProperties
[$name] );
921 public function getProperties() {
922 if ( !isset( $this->mProperties
) ) {
923 $this->mProperties
= [];
925 return $this->mProperties
;
929 * Returns the options from its ParserOptions which have been taken
930 * into account to produce this output or false if not available.
933 public function getUsedOptions() {
934 if ( !isset( $this->mAccessedOptions
) ) {
937 return array_keys( $this->mAccessedOptions
);
941 * Tags a parser option for use in the cache key for this parser output.
942 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
943 * The information gathered here is available via getUsedOptions(),
944 * and is used by ParserCache::save().
946 * @see ParserCache::getKey
947 * @see ParserCache::save
948 * @see ParserOptions::addExtraKey
949 * @see ParserOptions::optionsHash
950 * @param string $option
952 public function recordOption( $option ) {
953 $this->mAccessedOptions
[$option] = true;
957 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
958 * the ParserOutput object for later use during page output. The data will be cached along with
959 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
962 * This method is provided to overcome the unsafe practice of attaching extra information to a
963 * ParserObject by directly assigning member variables.
965 * To use setExtensionData() to pass extension information from a hook inside the parser to a
966 * hook in the page output, use this in the parser hook:
970 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
973 * And then later, in OutputPageParserOutput or similar:
977 * $output->getExtensionData( 'my_ext_foo' );
980 * In MediaWiki 1.20 and older, you have to use a custom member variable
981 * within the ParserOutput object:
985 * $parser->getOutput()->my_ext_foo = '...';
990 * @param string $key The key for accessing the data. Extensions should take care to avoid
991 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
993 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
996 public function setExtensionData( $key, $value ) {
997 if ( $value === null ) {
998 unset( $this->mExtensionData
[$key] );
1000 $this->mExtensionData
[$key] = $value;
1005 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1006 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1010 * @param string $key The key to look up.
1012 * @return mixed|null The value previously set for the given key using setExtensionData()
1013 * or null if no value was set for this key.
1015 public function getExtensionData( $key ) {
1016 if ( isset( $this->mExtensionData
[$key] ) ) {
1017 return $this->mExtensionData
[$key];
1023 private static function getTimes( $clock = null ) {
1025 if ( !$clock ||
$clock === 'wall' ) {
1026 $ret['wall'] = microtime( true );
1028 if ( !$clock ||
$clock === 'cpu' ) {
1029 $ru = wfGetRusage();
1031 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1032 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1039 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1042 public function resetParseStartTime() {
1043 $this->mParseStartTime
= self
::getTimes();
1047 * Returns the time since resetParseStartTime() was last called
1049 * Clocks available are:
1050 * - wall: Wall clock time
1051 * - cpu: CPU time (requires getrusage)
1054 * @param string $clock
1055 * @return float|null
1057 public function getTimeSinceStart( $clock ) {
1058 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1062 $end = self
::getTimes( $clock );
1063 return $end[$clock] - $this->mParseStartTime
[$clock];
1067 * Sets parser limit report data for a key
1069 * The key is used as the prefix for various messages used for formatting:
1070 * - $key: The label for the field in the limit report
1071 * - $key-value-text: Message used to format the value in the "NewPP limit
1072 * report" HTML comment. If missing, uses $key-format.
1073 * - $key-value-html: Message used to format the value in the preview
1074 * limit report table. If missing, uses $key-format.
1075 * - $key-value: Message used to format the value. If missing, uses "$1".
1077 * Note that all values are interpreted as wikitext, and so should be
1078 * encoded with htmlspecialchars() as necessary, but should avoid complex
1079 * HTML for sanity of display in the "NewPP limit report" comment.
1082 * @param string $key Message key
1083 * @param mixed $value Appropriate for Message::params()
1085 public function setLimitReportData( $key, $value ) {
1086 $this->mLimitReportData
[$key] = $value;
1088 if ( is_array( $value ) ) {
1089 if ( array_keys( $value ) === [ 0, 1 ]
1090 && is_numeric( $value[0] )
1091 && is_numeric( $value[1] )
1093 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1101 if ( strpos( $key, '-' ) ) {
1102 list( $ns, $name ) = explode( '-', $key, 2 );
1103 $this->mLimitReportJSData
[$ns][$name] = $data;
1105 $this->mLimitReportJSData
[$key] = $data;
1110 * Check whether the cache TTL was lowered due to dynamic content
1112 * When content is determined by more than hard state (e.g. page edits),
1113 * such as template/file transclusions based on the current timestamp or
1114 * extension tags that generate lists based on queries, this return true.
1119 public function hasDynamicContent() {
1120 global $wgParserCacheExpireTime;
1122 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1126 * Get or set the prevent-clickjacking flag
1129 * @param bool|null $flag New flag value, or null to leave it unchanged
1130 * @return bool Old flag value
1132 public function preventClickjacking( $flag = null ) {
1133 return wfSetVar( $this->mPreventClickjacking
, $flag );
1137 * Lower the runtime adaptive TTL to at most this value
1142 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1143 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1144 $this->updateCacheExpiry( $ttl );
1148 * Call this when parsing is done to lower the TTL based on low parse times
1152 public function finalizeAdaptiveCacheExpiry() {
1153 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1157 $runtime = $this->getTimeSinceStart( 'wall' );
1158 if ( is_float( $runtime ) ) {
1159 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1160 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1161 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1162 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1165 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1166 $this->mMaxAdaptiveExpiry
1168 $this->updateCacheExpiry( $adaptiveTTL );
1172 public function __sleep() {
1174 array_keys( get_object_vars( $this ) ),
1175 [ 'mParseStartTime' ]