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 flags to indicate to extensions that MediaWiki core supports and
27 * uses getText() stateless transforms.
29 const SUPPORTS_STATELESS_TRANSFORMS
= 1;
30 const SUPPORTS_UNWRAP_TRANSFORM
= 1;
33 * @var string $mText The output text
38 * @var array $mLanguageLinks List of the full text of language links,
39 * in the order they appear.
41 public $mLanguageLinks;
44 * @var array $mCategoriesMap of category names to sort keys
49 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
51 public $mIndicators = [];
54 * @var string $mTitleText Title text of the chosen language variant, as HTML.
59 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
65 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
68 public $mTemplates = [];
71 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
74 public $mTemplateIds = [];
77 * @var array $mImages DB keys of the images used, in the array key only
82 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
84 public $mFileSearchOptions = [];
87 * @var array $mExternalLinks External link URLs, in the key only.
89 public $mExternalLinks = [];
92 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
93 * for the inline interwiki links in the document.
95 public $mInterwikiLinks = [];
98 * @var bool $mNewSection Show a new section link?
100 public $mNewSection = false;
103 * @var bool $mHideNewSection Hide the new section link?
105 public $mHideNewSection = false;
108 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
110 public $mNoGallery = false;
113 * @var array $mHeadItems Items to put in the <head> section
115 public $mHeadItems = [];
118 * @var array $mModules Modules to be loaded by ResourceLoader
120 public $mModules = [];
123 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
125 public $mModuleScripts = [];
128 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
130 public $mModuleStyles = [];
133 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
135 public $mJsConfigVars = [];
138 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
140 public $mOutputHooks = [];
143 * @var array $mWarnings Warning text to be returned to the user.
144 * Wikitext formatted, in the key only.
146 public $mWarnings = [];
149 * @var array $mSections Table of contents
151 public $mSections = [];
154 * @deprecated since 1.31 Use getText() options.
155 * @var bool $mEditSectionTokens prefix/suffix markers if edit sections were output as tokens.
157 public $mEditSectionTokens = true;
160 * @var array $mProperties Name/value pairs to be cached in the DB.
162 public $mProperties = [];
165 * @var string $mTOCHTML HTML of the TOC.
167 public $mTOCHTML = '';
170 * @var string $mTimestamp Timestamp of the revision.
175 * @deprecated since 1.31 Use getText() options.
176 * @var bool $mTOCEnabled Whether TOC should be shown, can't override __NOTOC__.
178 public $mTOCEnabled = true;
181 * @var bool $mEnableOOUI Whether OOUI should be enabled.
183 public $mEnableOOUI = false;
186 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
188 private $mIndexPolicy = '';
191 * @var array $mAccessedOptions List of ParserOptions (stored in the keys).
193 private $mAccessedOptions = [];
196 * @var array $mExtensionData extra data used by extensions.
198 private $mExtensionData = [];
201 * @var array $mLimitReportData Parser limit report data.
203 private $mLimitReportData = [];
205 /** @var array Parser limit report data for JSON */
206 private $mLimitReportJSData = [];
209 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
211 private $mParseStartTime = [];
214 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
216 private $mPreventClickjacking = false;
219 * @var array $mFlags Generic flags.
221 private $mFlags = [];
223 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
224 private $mSpeculativeRevId;
226 /** @var int Upper bound of expiry based on parse duration */
227 private $mMaxAdaptiveExpiry = INF
;
229 const EDITSECTION_REGEX
=
230 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
232 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
233 // Current values imply that m=3933.333333 and b=-333.333333
234 // See https://www.nngroup.com/articles/website-response-times/
235 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
236 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
237 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
238 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
239 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
241 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
242 $unused = false, $titletext = ''
244 $this->mText
= $text;
245 $this->mLanguageLinks
= $languageLinks;
246 $this->mCategories
= $categoryLinks;
247 $this->mTitleText
= $titletext;
251 * Get the cacheable text with <mw:editsection> markers still in it. The
252 * return value is suitable for writing back via setText() but is not valid
253 * for display to the user.
258 public function getRawText() {
263 * Get the output HTML
265 * @param array $options (since 1.31) Transformations to apply to the HTML
266 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
267 * to generate one and `__NOTOC__` wasn't used. Default is true,
268 * but might be statefully overridden.
269 * - enableSectionEditLinks: (bool) Include section edit links, assuming
270 * section edit link tokens are present in the HTML. Default is true,
271 * but might be statefully overridden.
272 * - unwrap: (bool) Remove a wrapping mw-parser-output div. Default is false.
273 * @return string HTML
275 public function getText( $options = [] ) {
276 // @todo Warn if !array_key_exists( 'allowTOC', $options ) && empty( $this->mTOCEnabled )
278 // @todo Warn if !array_key_exists( 'enableSectionEditLinks', $options )
279 // && !$this->mEditSectionTokens
280 // Note that while $this->mEditSectionTokens formerly defaulted to false,
281 // ParserOptions->getEditSection() defaults to true and Parser copies
282 // that to us so true makes more sense as the stateless default.
285 // empty() here because old cached versions might lack the field somehow.
286 // In that situation, the historical behavior (possibly buggy) is to remove the TOC.
287 'allowTOC' => !empty( $this->mTOCEnabled
),
288 'enableSectionEditLinks' => $this->mEditSectionTokens
,
291 $text = $this->mText
;
293 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
295 if ( $options['unwrap'] !== false ) {
296 $start = Html
::openElement( 'div', [
297 'class' => 'mw-parser-output'
299 $startLen = strlen( $start );
300 $end = Html
::closeElement( 'div' );
301 $endLen = strlen( $end );
303 if ( substr( $text, 0, $startLen ) === $start && substr( $text, -$endLen ) === $end ) {
304 $text = substr( $text, $startLen, -$endLen );
308 if ( $options['enableSectionEditLinks'] ) {
309 $text = preg_replace_callback(
310 self
::EDITSECTION_REGEX
,
312 global $wgOut, $wgLang;
313 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
314 $editsectionSection = htmlspecialchars_decode( $m[2] );
315 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
317 if ( !is_object( $editsectionPage ) ) {
318 throw new MWException( "Bad parser output text." );
321 $skin = $wgOut->getSkin();
322 return call_user_func_array(
323 [ $skin, 'doEditSectionLink' ],
324 [ $editsectionPage, $editsectionSection,
325 $editsectionContent, $wgLang->getCode() ]
331 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
334 if ( $options['allowTOC'] ) {
335 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
337 $text = preg_replace(
338 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
351 public function setSpeculativeRevIdUsed( $id ) {
352 $this->mSpeculativeRevId
= $id;
359 public function getSpeculativeRevIdUsed() {
360 return $this->mSpeculativeRevId
;
363 public function &getLanguageLinks() {
364 return $this->mLanguageLinks
;
367 public function getInterwikiLinks() {
368 return $this->mInterwikiLinks
;
371 public function getCategoryLinks() {
372 return array_keys( $this->mCategories
);
375 public function &getCategories() {
376 return $this->mCategories
;
383 public function getIndicators() {
384 return $this->mIndicators
;
387 public function getTitleText() {
388 return $this->mTitleText
;
391 public function getSections() {
392 return $this->mSections
;
396 * @deprecated since 1.31 Use getText() options.
398 public function getEditSectionTokens() {
399 return $this->mEditSectionTokens
;
402 public function &getLinks() {
403 return $this->mLinks
;
406 public function &getTemplates() {
407 return $this->mTemplates
;
410 public function &getTemplateIds() {
411 return $this->mTemplateIds
;
414 public function &getImages() {
415 return $this->mImages
;
418 public function &getFileSearchOptions() {
419 return $this->mFileSearchOptions
;
422 public function &getExternalLinks() {
423 return $this->mExternalLinks
;
426 public function getNoGallery() {
427 return $this->mNoGallery
;
430 public function getHeadItems() {
431 return $this->mHeadItems
;
434 public function getModules() {
435 return $this->mModules
;
438 public function getModuleScripts() {
439 return $this->mModuleScripts
;
442 public function getModuleStyles() {
443 return $this->mModuleStyles
;
450 public function getJsConfigVars() {
451 return $this->mJsConfigVars
;
454 public function getOutputHooks() {
455 return (array)$this->mOutputHooks
;
458 public function getWarnings() {
459 return array_keys( $this->mWarnings
);
462 public function getIndexPolicy() {
463 return $this->mIndexPolicy
;
466 public function getTOCHTML() {
467 return $this->mTOCHTML
;
471 * @return string|null TS_MW timestamp of the revision content
473 public function getTimestamp() {
474 return $this->mTimestamp
;
477 public function getLimitReportData() {
478 return $this->mLimitReportData
;
481 public function getLimitReportJSData() {
482 return $this->mLimitReportJSData
;
486 * @deprecated since 1.31 Use getText() options.
488 public function getTOCEnabled() {
489 return $this->mTOCEnabled
;
492 public function getEnableOOUI() {
493 return $this->mEnableOOUI
;
496 public function setText( $text ) {
497 return wfSetVar( $this->mText
, $text );
500 public function setLanguageLinks( $ll ) {
501 return wfSetVar( $this->mLanguageLinks
, $ll );
504 public function setCategoryLinks( $cl ) {
505 return wfSetVar( $this->mCategories
, $cl );
508 public function setTitleText( $t ) {
509 return wfSetVar( $this->mTitleText
, $t );
512 public function setSections( $toc ) {
513 return wfSetVar( $this->mSections
, $toc );
517 * @deprecated since 1.31 Use getText() options.
519 public function setEditSectionTokens( $t ) {
520 return wfSetVar( $this->mEditSectionTokens
, $t );
523 public function setIndexPolicy( $policy ) {
524 return wfSetVar( $this->mIndexPolicy
, $policy );
527 public function setTOCHTML( $tochtml ) {
528 return wfSetVar( $this->mTOCHTML
, $tochtml );
531 public function setTimestamp( $timestamp ) {
532 return wfSetVar( $this->mTimestamp
, $timestamp );
536 * @deprecated since 1.31 Use getText() options.
538 public function setTOCEnabled( $flag ) {
539 return wfSetVar( $this->mTOCEnabled
, $flag );
542 public function addCategory( $c, $sort ) {
543 $this->mCategories
[$c] = $sort;
548 * @param string $content
551 public function setIndicator( $id, $content ) {
552 $this->mIndicators
[$id] = $content;
556 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
557 * object is added to.
560 * @param bool $enable If OOUI should be enabled or not
562 public function setEnableOOUI( $enable = false ) {
563 $this->mEnableOOUI
= $enable;
566 public function addLanguageLink( $t ) {
567 $this->mLanguageLinks
[] = $t;
570 public function addWarning( $s ) {
571 $this->mWarnings
[$s] = 1;
574 public function addOutputHook( $hook, $data = false ) {
575 $this->mOutputHooks
[] = [ $hook, $data ];
578 public function setNewSection( $value ) {
579 $this->mNewSection
= (bool)$value;
581 public function hideNewSection( $value ) {
582 $this->mHideNewSection
= (bool)$value;
584 public function getHideNewSection() {
585 return (bool)$this->mHideNewSection
;
587 public function getNewSection() {
588 return (bool)$this->mNewSection
;
592 * Checks, if a url is pointing to the own server
594 * @param string $internal The server to check against
595 * @param string $url The url to check
598 public static function isLinkInternal( $internal, $url ) {
599 return (bool)preg_match( '/^' .
600 # If server is proto relative, check also for http/https links
601 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
602 preg_quote( $internal, '/' ) .
603 # check for query/path/anchor or end of link in each case
609 public function addExternalLink( $url ) {
610 # We don't register links pointing to our own server, unless... :-)
611 global $wgServer, $wgRegisterInternalExternals;
613 # Replace unnecessary URL escape codes with the referenced character
614 # This prevents spammers from hiding links from the filters
615 $url = Parser
::normalizeLinkUrl( $url );
617 $registerExternalLink = true;
618 if ( !$wgRegisterInternalExternals ) {
619 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
621 if ( $registerExternalLink ) {
622 $this->mExternalLinks
[$url] = 1;
627 * Record a local or interwiki inline link for saving in future link tables.
629 * @param Title $title
630 * @param int|null $id Optional known page_id so we can skip the lookup
632 public function addLink( Title
$title, $id = null ) {
633 if ( $title->isExternal() ) {
634 // Don't record interwikis in pagelinks
635 $this->addInterwikiLink( $title );
638 $ns = $title->getNamespace();
639 $dbk = $title->getDBkey();
640 if ( $ns == NS_MEDIA
) {
641 // Normalize this pseudo-alias if it makes it down here...
643 } elseif ( $ns == NS_SPECIAL
) {
644 // We don't record Special: links currently
645 // It might actually be wise to, but we'd need to do some normalization.
647 } elseif ( $dbk === '' ) {
648 // Don't record self links - [[#Foo]]
651 if ( !isset( $this->mLinks
[$ns] ) ) {
652 $this->mLinks
[$ns] = [];
654 if ( is_null( $id ) ) {
655 $id = $title->getArticleID();
657 $this->mLinks
[$ns][$dbk] = $id;
661 * Register a file dependency for this output
662 * @param string $name Title dbKey
663 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
664 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
667 public function addImage( $name, $timestamp = null, $sha1 = null ) {
668 $this->mImages
[$name] = 1;
669 if ( $timestamp !== null && $sha1 !== null ) {
670 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
675 * Register a template dependency for this output
676 * @param Title $title
677 * @param int $page_id
681 public function addTemplate( $title, $page_id, $rev_id ) {
682 $ns = $title->getNamespace();
683 $dbk = $title->getDBkey();
684 if ( !isset( $this->mTemplates
[$ns] ) ) {
685 $this->mTemplates
[$ns] = [];
687 $this->mTemplates
[$ns][$dbk] = $page_id;
688 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
689 $this->mTemplateIds
[$ns] = [];
691 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
695 * @param Title $title Title object, must be an interwiki link
696 * @throws MWException If given invalid input
698 public function addInterwikiLink( $title ) {
699 if ( !$title->isExternal() ) {
700 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
702 $prefix = $title->getInterwiki();
703 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
704 $this->mInterwikiLinks
[$prefix] = [];
706 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
710 * Add some text to the "<head>".
711 * If $tag is set, the section with that tag will only be included once
713 * @param string $section
714 * @param string|bool $tag
716 public function addHeadItem( $section, $tag = false ) {
717 if ( $tag !== false ) {
718 $this->mHeadItems
[$tag] = $section;
720 $this->mHeadItems
[] = $section;
724 public function addModules( $modules ) {
725 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
728 public function addModuleScripts( $modules ) {
729 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
732 public function addModuleStyles( $modules ) {
733 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
737 * Add one or more variables to be set in mw.config in JavaScript.
739 * @param string|array $keys Key or array of key/value pairs.
740 * @param mixed $value [optional] Value of the configuration variable.
743 public function addJsConfigVars( $keys, $value = null ) {
744 if ( is_array( $keys ) ) {
745 foreach ( $keys as $key => $value ) {
746 $this->mJsConfigVars
[$key] = $value;
751 $this->mJsConfigVars
[$keys] = $value;
755 * Copy items from the OutputPage object into this one
757 * @param OutputPage $out
759 public function addOutputPageMetadata( OutputPage
$out ) {
760 $this->addModules( $out->getModules() );
761 $this->addModuleScripts( $out->getModuleScripts() );
762 $this->addModuleStyles( $out->getModuleStyles() );
763 $this->addJsConfigVars( $out->getJsConfigVars() );
765 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
766 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
770 * Add a tracking category, getting the title from a system message,
771 * or print a debug message if the title is invalid.
773 * Any message used with this function should be registered so it will
774 * show up on Special:TrackingCategories. Core messages should be added
775 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
776 * should add to "TrackingCategories" in their extension.json.
778 * @todo Migrate some code to TrackingCategories
780 * @param string $msg Message key
781 * @param Title $title title of the page which is being tracked
782 * @return bool Whether the addition was successful
785 public function addTrackingCategory( $msg, $title ) {
786 if ( $title->isSpecialPage() ) {
787 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
791 // Important to parse with correct title (T33469)
792 $cat = wfMessage( $msg )
794 ->inContentLanguage()
797 # Allow tracking categories to be disabled by setting them to "-"
798 if ( $cat === '-' ) {
802 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
803 if ( $containerCategory ) {
804 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
807 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
813 * Override the title to be used for display
815 * @note this is assumed to have been validated
816 * (check equal normalisation, etc.)
818 * @note this is expected to be safe HTML,
819 * ready to be served to the client.
821 * @param string $text Desired title text
823 public function setDisplayTitle( $text ) {
824 $this->setTitleText( $text );
825 $this->setProperty( 'displaytitle', $text );
829 * Get the title to be used for display.
831 * As per the contract of setDisplayTitle(), this is safe HTML,
832 * ready to be served to the client.
834 * @return string HTML
836 public function getDisplayTitle() {
837 $t = $this->getTitleText();
845 * Fairly generic flag setter thingy.
846 * @param string $flag
848 public function setFlag( $flag ) {
849 $this->mFlags
[$flag] = true;
852 public function getFlag( $flag ) {
853 return isset( $this->mFlags
[$flag] );
857 * Set a property to be stored in the page_props database table.
859 * page_props is a key value store indexed by the page ID. This allows
860 * the parser to set a property on a page which can then be quickly
861 * retrieved given the page ID or via a DB join when given the page
864 * Since 1.23, page_props are also indexed by numeric value, to allow
865 * for efficient "top k" queries of pages wrt a given property.
867 * setProperty() is thus used to propagate properties from the parsed
868 * page to request contexts other than a page view of the currently parsed
871 * Some applications examples:
873 * * To implement hidden categories, hiding pages from category listings
874 * by storing a property.
876 * * Overriding the displayed article title.
877 * @see ParserOutput::setDisplayTitle()
879 * * To implement image tagging, for example displaying an icon on an
880 * image thumbnail to indicate that it is listed for deletion on
882 * This is not actually implemented, yet but would be pretty cool.
884 * @note Do not use setProperty() to set a property which is only used
885 * in a context where the ParserOutput object itself is already available,
886 * for example a normal page view. There is no need to save such a property
887 * in the database since the text is already parsed. You can just hook
888 * OutputPageParserOutput and get your data out of the ParserOutput object.
890 * If you are writing an extension where you want to set a property in the
891 * parser which is used by an OutputPageParserOutput hook, you have to
892 * associate the extension data directly with the ParserOutput object.
893 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
897 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
900 * And then later, in OutputPageParserOutput or similar:
904 * $output->getExtensionData( 'my_ext_foo' );
907 * In MediaWiki 1.20 and older, you have to use a custom member variable
908 * within the ParserOutput object:
912 * $parser->getOutput()->my_ext_foo = '...';
914 * @param string $name
915 * @param mixed $value
917 public function setProperty( $name, $value ) {
918 $this->mProperties
[$name] = $value;
922 * @param string $name The property name to look up.
924 * @return mixed|bool The value previously set using setProperty(). False if null or no value
925 * was set for the given property name.
927 * @note You need to use getProperties() to check for boolean and null properties.
929 public function getProperty( $name ) {
930 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
933 public function unsetProperty( $name ) {
934 unset( $this->mProperties
[$name] );
937 public function getProperties() {
938 if ( !isset( $this->mProperties
) ) {
939 $this->mProperties
= [];
941 return $this->mProperties
;
945 * Returns the options from its ParserOptions which have been taken
946 * into account to produce this output or false if not available.
949 public function getUsedOptions() {
950 if ( !isset( $this->mAccessedOptions
) ) {
953 return array_keys( $this->mAccessedOptions
);
957 * Tags a parser option for use in the cache key for this parser output.
958 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
959 * The information gathered here is available via getUsedOptions(),
960 * and is used by ParserCache::save().
962 * @see ParserCache::getKey
963 * @see ParserCache::save
964 * @see ParserOptions::addExtraKey
965 * @see ParserOptions::optionsHash
966 * @param string $option
968 public function recordOption( $option ) {
969 $this->mAccessedOptions
[$option] = true;
973 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
974 * the ParserOutput object for later use during page output. The data will be cached along with
975 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
978 * This method is provided to overcome the unsafe practice of attaching extra information to a
979 * ParserObject by directly assigning member variables.
981 * To use setExtensionData() to pass extension information from a hook inside the parser to a
982 * hook in the page output, use this in the parser hook:
986 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
989 * And then later, in OutputPageParserOutput or similar:
993 * $output->getExtensionData( 'my_ext_foo' );
996 * In MediaWiki 1.20 and older, you have to use a custom member variable
997 * within the ParserOutput object:
1001 * $parser->getOutput()->my_ext_foo = '...';
1006 * @param string $key The key for accessing the data. Extensions should take care to avoid
1007 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1009 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1012 public function setExtensionData( $key, $value ) {
1013 if ( $value === null ) {
1014 unset( $this->mExtensionData
[$key] );
1016 $this->mExtensionData
[$key] = $value;
1021 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1022 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1026 * @param string $key The key to look up.
1028 * @return mixed|null The value previously set for the given key using setExtensionData()
1029 * or null if no value was set for this key.
1031 public function getExtensionData( $key ) {
1032 if ( isset( $this->mExtensionData
[$key] ) ) {
1033 return $this->mExtensionData
[$key];
1039 private static function getTimes( $clock = null ) {
1041 if ( !$clock ||
$clock === 'wall' ) {
1042 $ret['wall'] = microtime( true );
1044 if ( !$clock ||
$clock === 'cpu' ) {
1045 $ru = wfGetRusage();
1047 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1048 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1055 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1058 public function resetParseStartTime() {
1059 $this->mParseStartTime
= self
::getTimes();
1063 * Returns the time since resetParseStartTime() was last called
1065 * Clocks available are:
1066 * - wall: Wall clock time
1067 * - cpu: CPU time (requires getrusage)
1070 * @param string $clock
1071 * @return float|null
1073 public function getTimeSinceStart( $clock ) {
1074 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1078 $end = self
::getTimes( $clock );
1079 return $end[$clock] - $this->mParseStartTime
[$clock];
1083 * Sets parser limit report data for a key
1085 * The key is used as the prefix for various messages used for formatting:
1086 * - $key: The label for the field in the limit report
1087 * - $key-value-text: Message used to format the value in the "NewPP limit
1088 * report" HTML comment. If missing, uses $key-format.
1089 * - $key-value-html: Message used to format the value in the preview
1090 * limit report table. If missing, uses $key-format.
1091 * - $key-value: Message used to format the value. If missing, uses "$1".
1093 * Note that all values are interpreted as wikitext, and so should be
1094 * encoded with htmlspecialchars() as necessary, but should avoid complex
1095 * HTML for sanity of display in the "NewPP limit report" comment.
1098 * @param string $key Message key
1099 * @param mixed $value Appropriate for Message::params()
1101 public function setLimitReportData( $key, $value ) {
1102 $this->mLimitReportData
[$key] = $value;
1104 if ( is_array( $value ) ) {
1105 if ( array_keys( $value ) === [ 0, 1 ]
1106 && is_numeric( $value[0] )
1107 && is_numeric( $value[1] )
1109 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1117 if ( strpos( $key, '-' ) ) {
1118 list( $ns, $name ) = explode( '-', $key, 2 );
1119 $this->mLimitReportJSData
[$ns][$name] = $data;
1121 $this->mLimitReportJSData
[$key] = $data;
1126 * Check whether the cache TTL was lowered due to dynamic content
1128 * When content is determined by more than hard state (e.g. page edits),
1129 * such as template/file transclusions based on the current timestamp or
1130 * extension tags that generate lists based on queries, this return true.
1135 public function hasDynamicContent() {
1136 global $wgParserCacheExpireTime;
1138 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1142 * Get or set the prevent-clickjacking flag
1145 * @param bool|null $flag New flag value, or null to leave it unchanged
1146 * @return bool Old flag value
1148 public function preventClickjacking( $flag = null ) {
1149 return wfSetVar( $this->mPreventClickjacking
, $flag );
1153 * Lower the runtime adaptive TTL to at most this value
1158 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1159 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1160 $this->updateCacheExpiry( $ttl );
1164 * Call this when parsing is done to lower the TTL based on low parse times
1168 public function finalizeAdaptiveCacheExpiry() {
1169 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1173 $runtime = $this->getTimeSinceStart( 'wall' );
1174 if ( is_float( $runtime ) ) {
1175 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1176 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1177 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1178 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1181 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1182 $this->mMaxAdaptiveExpiry
1184 $this->updateCacheExpiry( $adaptiveTTL );
1188 public function __sleep() {
1190 array_keys( get_object_vars( $this ) ),
1191 [ 'mParseStartTime' ]