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 if ( !array_key_exists( 'allowTOC', $options ) && empty( $this->mTOCEnabled
) ) {
277 wfDeprecated( 'ParserOutput stateful allowTOC', '1.31' );
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.
283 if ( !array_key_exists( 'enableSectionEditLinks', $options ) && !$this->mEditSectionTokens
) {
284 wfDeprecated( 'ParserOutput stateful enableSectionEditLinks', '1.31' );
288 // empty() here because old cached versions might lack the field somehow.
289 // In that situation, the historical behavior (possibly buggy) is to remove the TOC.
290 'allowTOC' => !empty( $this->mTOCEnabled
),
291 'enableSectionEditLinks' => $this->mEditSectionTokens
,
294 $text = $this->mText
;
296 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
298 if ( $options['unwrap'] !== false ) {
299 $start = Html
::openElement( 'div', [
300 'class' => 'mw-parser-output'
302 $startLen = strlen( $start );
303 $end = Html
::closeElement( 'div' );
304 $endLen = strlen( $end );
306 if ( substr( $text, 0, $startLen ) === $start && substr( $text, -$endLen ) === $end ) {
307 $text = substr( $text, $startLen, -$endLen );
311 if ( $options['enableSectionEditLinks'] ) {
312 $text = preg_replace_callback(
313 self
::EDITSECTION_REGEX
,
315 global $wgOut, $wgLang;
316 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
317 $editsectionSection = htmlspecialchars_decode( $m[2] );
318 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
320 if ( !is_object( $editsectionPage ) ) {
321 throw new MWException( "Bad parser output text." );
324 $skin = $wgOut->getSkin();
325 return call_user_func_array(
326 [ $skin, 'doEditSectionLink' ],
327 [ $editsectionPage, $editsectionSection,
328 $editsectionContent, $wgLang->getCode() ]
334 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
337 if ( $options['allowTOC'] ) {
338 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
340 $text = preg_replace(
341 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
354 public function setSpeculativeRevIdUsed( $id ) {
355 $this->mSpeculativeRevId
= $id;
362 public function getSpeculativeRevIdUsed() {
363 return $this->mSpeculativeRevId
;
366 public function &getLanguageLinks() {
367 return $this->mLanguageLinks
;
370 public function getInterwikiLinks() {
371 return $this->mInterwikiLinks
;
374 public function getCategoryLinks() {
375 return array_keys( $this->mCategories
);
378 public function &getCategories() {
379 return $this->mCategories
;
386 public function getIndicators() {
387 return $this->mIndicators
;
390 public function getTitleText() {
391 return $this->mTitleText
;
394 public function getSections() {
395 return $this->mSections
;
399 * @deprecated since 1.31 Use getText() options.
401 public function getEditSectionTokens() {
402 return $this->mEditSectionTokens
;
405 public function &getLinks() {
406 return $this->mLinks
;
409 public function &getTemplates() {
410 return $this->mTemplates
;
413 public function &getTemplateIds() {
414 return $this->mTemplateIds
;
417 public function &getImages() {
418 return $this->mImages
;
421 public function &getFileSearchOptions() {
422 return $this->mFileSearchOptions
;
425 public function &getExternalLinks() {
426 return $this->mExternalLinks
;
429 public function getNoGallery() {
430 return $this->mNoGallery
;
433 public function getHeadItems() {
434 return $this->mHeadItems
;
437 public function getModules() {
438 return $this->mModules
;
441 public function getModuleScripts() {
442 return $this->mModuleScripts
;
445 public function getModuleStyles() {
446 return $this->mModuleStyles
;
453 public function getJsConfigVars() {
454 return $this->mJsConfigVars
;
457 public function getOutputHooks() {
458 return (array)$this->mOutputHooks
;
461 public function getWarnings() {
462 return array_keys( $this->mWarnings
);
465 public function getIndexPolicy() {
466 return $this->mIndexPolicy
;
469 public function getTOCHTML() {
470 return $this->mTOCHTML
;
474 * @return string|null TS_MW timestamp of the revision content
476 public function getTimestamp() {
477 return $this->mTimestamp
;
480 public function getLimitReportData() {
481 return $this->mLimitReportData
;
484 public function getLimitReportJSData() {
485 return $this->mLimitReportJSData
;
489 * @deprecated since 1.31 Use getText() options.
491 public function getTOCEnabled() {
492 return $this->mTOCEnabled
;
495 public function getEnableOOUI() {
496 return $this->mEnableOOUI
;
499 public function setText( $text ) {
500 return wfSetVar( $this->mText
, $text );
503 public function setLanguageLinks( $ll ) {
504 return wfSetVar( $this->mLanguageLinks
, $ll );
507 public function setCategoryLinks( $cl ) {
508 return wfSetVar( $this->mCategories
, $cl );
511 public function setTitleText( $t ) {
512 return wfSetVar( $this->mTitleText
, $t );
515 public function setSections( $toc ) {
516 return wfSetVar( $this->mSections
, $toc );
520 * @deprecated since 1.31 Use getText() options.
522 public function setEditSectionTokens( $t ) {
523 return wfSetVar( $this->mEditSectionTokens
, $t );
526 public function setIndexPolicy( $policy ) {
527 return wfSetVar( $this->mIndexPolicy
, $policy );
530 public function setTOCHTML( $tochtml ) {
531 return wfSetVar( $this->mTOCHTML
, $tochtml );
534 public function setTimestamp( $timestamp ) {
535 return wfSetVar( $this->mTimestamp
, $timestamp );
539 * @deprecated since 1.31 Use getText() options.
541 public function setTOCEnabled( $flag ) {
542 return wfSetVar( $this->mTOCEnabled
, $flag );
545 public function addCategory( $c, $sort ) {
546 $this->mCategories
[$c] = $sort;
551 * @param string $content
554 public function setIndicator( $id, $content ) {
555 $this->mIndicators
[$id] = $content;
559 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
560 * object is added to.
563 * @param bool $enable If OOUI should be enabled or not
565 public function setEnableOOUI( $enable = false ) {
566 $this->mEnableOOUI
= $enable;
569 public function addLanguageLink( $t ) {
570 $this->mLanguageLinks
[] = $t;
573 public function addWarning( $s ) {
574 $this->mWarnings
[$s] = 1;
577 public function addOutputHook( $hook, $data = false ) {
578 $this->mOutputHooks
[] = [ $hook, $data ];
581 public function setNewSection( $value ) {
582 $this->mNewSection
= (bool)$value;
584 public function hideNewSection( $value ) {
585 $this->mHideNewSection
= (bool)$value;
587 public function getHideNewSection() {
588 return (bool)$this->mHideNewSection
;
590 public function getNewSection() {
591 return (bool)$this->mNewSection
;
595 * Checks, if a url is pointing to the own server
597 * @param string $internal The server to check against
598 * @param string $url The url to check
601 public static function isLinkInternal( $internal, $url ) {
602 return (bool)preg_match( '/^' .
603 # If server is proto relative, check also for http/https links
604 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
605 preg_quote( $internal, '/' ) .
606 # check for query/path/anchor or end of link in each case
612 public function addExternalLink( $url ) {
613 # We don't register links pointing to our own server, unless... :-)
614 global $wgServer, $wgRegisterInternalExternals;
616 # Replace unnecessary URL escape codes with the referenced character
617 # This prevents spammers from hiding links from the filters
618 $url = Parser
::normalizeLinkUrl( $url );
620 $registerExternalLink = true;
621 if ( !$wgRegisterInternalExternals ) {
622 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
624 if ( $registerExternalLink ) {
625 $this->mExternalLinks
[$url] = 1;
630 * Record a local or interwiki inline link for saving in future link tables.
632 * @param Title $title
633 * @param int|null $id Optional known page_id so we can skip the lookup
635 public function addLink( Title
$title, $id = null ) {
636 if ( $title->isExternal() ) {
637 // Don't record interwikis in pagelinks
638 $this->addInterwikiLink( $title );
641 $ns = $title->getNamespace();
642 $dbk = $title->getDBkey();
643 if ( $ns == NS_MEDIA
) {
644 // Normalize this pseudo-alias if it makes it down here...
646 } elseif ( $ns == NS_SPECIAL
) {
647 // We don't record Special: links currently
648 // It might actually be wise to, but we'd need to do some normalization.
650 } elseif ( $dbk === '' ) {
651 // Don't record self links - [[#Foo]]
654 if ( !isset( $this->mLinks
[$ns] ) ) {
655 $this->mLinks
[$ns] = [];
657 if ( is_null( $id ) ) {
658 $id = $title->getArticleID();
660 $this->mLinks
[$ns][$dbk] = $id;
664 * Register a file dependency for this output
665 * @param string $name Title dbKey
666 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
667 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
670 public function addImage( $name, $timestamp = null, $sha1 = null ) {
671 $this->mImages
[$name] = 1;
672 if ( $timestamp !== null && $sha1 !== null ) {
673 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
678 * Register a template dependency for this output
679 * @param Title $title
680 * @param int $page_id
684 public function addTemplate( $title, $page_id, $rev_id ) {
685 $ns = $title->getNamespace();
686 $dbk = $title->getDBkey();
687 if ( !isset( $this->mTemplates
[$ns] ) ) {
688 $this->mTemplates
[$ns] = [];
690 $this->mTemplates
[$ns][$dbk] = $page_id;
691 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
692 $this->mTemplateIds
[$ns] = [];
694 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
698 * @param Title $title Title object, must be an interwiki link
699 * @throws MWException If given invalid input
701 public function addInterwikiLink( $title ) {
702 if ( !$title->isExternal() ) {
703 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
705 $prefix = $title->getInterwiki();
706 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
707 $this->mInterwikiLinks
[$prefix] = [];
709 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
713 * Add some text to the "<head>".
714 * If $tag is set, the section with that tag will only be included once
716 * @param string $section
717 * @param string|bool $tag
719 public function addHeadItem( $section, $tag = false ) {
720 if ( $tag !== false ) {
721 $this->mHeadItems
[$tag] = $section;
723 $this->mHeadItems
[] = $section;
727 public function addModules( $modules ) {
728 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
731 public function addModuleScripts( $modules ) {
732 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
735 public function addModuleStyles( $modules ) {
736 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
740 * Add one or more variables to be set in mw.config in JavaScript.
742 * @param string|array $keys Key or array of key/value pairs.
743 * @param mixed $value [optional] Value of the configuration variable.
746 public function addJsConfigVars( $keys, $value = null ) {
747 if ( is_array( $keys ) ) {
748 foreach ( $keys as $key => $value ) {
749 $this->mJsConfigVars
[$key] = $value;
754 $this->mJsConfigVars
[$keys] = $value;
758 * Copy items from the OutputPage object into this one
760 * @param OutputPage $out
762 public function addOutputPageMetadata( OutputPage
$out ) {
763 $this->addModules( $out->getModules() );
764 $this->addModuleScripts( $out->getModuleScripts() );
765 $this->addModuleStyles( $out->getModuleStyles() );
766 $this->addJsConfigVars( $out->getJsConfigVars() );
768 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
769 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
773 * Add a tracking category, getting the title from a system message,
774 * or print a debug message if the title is invalid.
776 * Any message used with this function should be registered so it will
777 * show up on Special:TrackingCategories. Core messages should be added
778 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
779 * should add to "TrackingCategories" in their extension.json.
781 * @todo Migrate some code to TrackingCategories
783 * @param string $msg Message key
784 * @param Title $title title of the page which is being tracked
785 * @return bool Whether the addition was successful
788 public function addTrackingCategory( $msg, $title ) {
789 if ( $title->isSpecialPage() ) {
790 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
794 // Important to parse with correct title (T33469)
795 $cat = wfMessage( $msg )
797 ->inContentLanguage()
800 # Allow tracking categories to be disabled by setting them to "-"
801 if ( $cat === '-' ) {
805 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
806 if ( $containerCategory ) {
807 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
810 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
816 * Override the title to be used for display
818 * @note this is assumed to have been validated
819 * (check equal normalisation, etc.)
821 * @note this is expected to be safe HTML,
822 * ready to be served to the client.
824 * @param string $text Desired title text
826 public function setDisplayTitle( $text ) {
827 $this->setTitleText( $text );
828 $this->setProperty( 'displaytitle', $text );
832 * Get the title to be used for display.
834 * As per the contract of setDisplayTitle(), this is safe HTML,
835 * ready to be served to the client.
837 * @return string HTML
839 public function getDisplayTitle() {
840 $t = $this->getTitleText();
848 * Fairly generic flag setter thingy.
849 * @param string $flag
851 public function setFlag( $flag ) {
852 $this->mFlags
[$flag] = true;
855 public function getFlag( $flag ) {
856 return isset( $this->mFlags
[$flag] );
860 * Set a property to be stored in the page_props database table.
862 * page_props is a key value store indexed by the page ID. This allows
863 * the parser to set a property on a page which can then be quickly
864 * retrieved given the page ID or via a DB join when given the page
867 * Since 1.23, page_props are also indexed by numeric value, to allow
868 * for efficient "top k" queries of pages wrt a given property.
870 * setProperty() is thus used to propagate properties from the parsed
871 * page to request contexts other than a page view of the currently parsed
874 * Some applications examples:
876 * * To implement hidden categories, hiding pages from category listings
877 * by storing a property.
879 * * Overriding the displayed article title.
880 * @see ParserOutput::setDisplayTitle()
882 * * To implement image tagging, for example displaying an icon on an
883 * image thumbnail to indicate that it is listed for deletion on
885 * This is not actually implemented, yet but would be pretty cool.
887 * @note Do not use setProperty() to set a property which is only used
888 * in a context where the ParserOutput object itself is already available,
889 * for example a normal page view. There is no need to save such a property
890 * in the database since the text is already parsed. You can just hook
891 * OutputPageParserOutput and get your data out of the ParserOutput object.
893 * If you are writing an extension where you want to set a property in the
894 * parser which is used by an OutputPageParserOutput hook, you have to
895 * associate the extension data directly with the ParserOutput object.
896 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
900 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
903 * And then later, in OutputPageParserOutput or similar:
907 * $output->getExtensionData( 'my_ext_foo' );
910 * In MediaWiki 1.20 and older, you have to use a custom member variable
911 * within the ParserOutput object:
915 * $parser->getOutput()->my_ext_foo = '...';
917 * @param string $name
918 * @param mixed $value
920 public function setProperty( $name, $value ) {
921 $this->mProperties
[$name] = $value;
925 * @param string $name The property name to look up.
927 * @return mixed|bool The value previously set using setProperty(). False if null or no value
928 * was set for the given property name.
930 * @note You need to use getProperties() to check for boolean and null properties.
932 public function getProperty( $name ) {
933 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
936 public function unsetProperty( $name ) {
937 unset( $this->mProperties
[$name] );
940 public function getProperties() {
941 if ( !isset( $this->mProperties
) ) {
942 $this->mProperties
= [];
944 return $this->mProperties
;
948 * Returns the options from its ParserOptions which have been taken
949 * into account to produce this output or false if not available.
952 public function getUsedOptions() {
953 if ( !isset( $this->mAccessedOptions
) ) {
956 return array_keys( $this->mAccessedOptions
);
960 * Tags a parser option for use in the cache key for this parser output.
961 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
962 * The information gathered here is available via getUsedOptions(),
963 * and is used by ParserCache::save().
965 * @see ParserCache::getKey
966 * @see ParserCache::save
967 * @see ParserOptions::addExtraKey
968 * @see ParserOptions::optionsHash
969 * @param string $option
971 public function recordOption( $option ) {
972 $this->mAccessedOptions
[$option] = true;
976 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
977 * the ParserOutput object for later use during page output. The data will be cached along with
978 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
981 * This method is provided to overcome the unsafe practice of attaching extra information to a
982 * ParserObject by directly assigning member variables.
984 * To use setExtensionData() to pass extension information from a hook inside the parser to a
985 * hook in the page output, use this in the parser hook:
989 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
992 * And then later, in OutputPageParserOutput or similar:
996 * $output->getExtensionData( 'my_ext_foo' );
999 * In MediaWiki 1.20 and older, you have to use a custom member variable
1000 * within the ParserOutput object:
1004 * $parser->getOutput()->my_ext_foo = '...';
1009 * @param string $key The key for accessing the data. Extensions should take care to avoid
1010 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1012 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1015 public function setExtensionData( $key, $value ) {
1016 if ( $value === null ) {
1017 unset( $this->mExtensionData
[$key] );
1019 $this->mExtensionData
[$key] = $value;
1024 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1025 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1029 * @param string $key The key to look up.
1031 * @return mixed|null The value previously set for the given key using setExtensionData()
1032 * or null if no value was set for this key.
1034 public function getExtensionData( $key ) {
1035 if ( isset( $this->mExtensionData
[$key] ) ) {
1036 return $this->mExtensionData
[$key];
1042 private static function getTimes( $clock = null ) {
1044 if ( !$clock ||
$clock === 'wall' ) {
1045 $ret['wall'] = microtime( true );
1047 if ( !$clock ||
$clock === 'cpu' ) {
1048 $ru = wfGetRusage();
1050 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1051 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1058 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1061 public function resetParseStartTime() {
1062 $this->mParseStartTime
= self
::getTimes();
1066 * Returns the time since resetParseStartTime() was last called
1068 * Clocks available are:
1069 * - wall: Wall clock time
1070 * - cpu: CPU time (requires getrusage)
1073 * @param string $clock
1074 * @return float|null
1076 public function getTimeSinceStart( $clock ) {
1077 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1081 $end = self
::getTimes( $clock );
1082 return $end[$clock] - $this->mParseStartTime
[$clock];
1086 * Sets parser limit report data for a key
1088 * The key is used as the prefix for various messages used for formatting:
1089 * - $key: The label for the field in the limit report
1090 * - $key-value-text: Message used to format the value in the "NewPP limit
1091 * report" HTML comment. If missing, uses $key-format.
1092 * - $key-value-html: Message used to format the value in the preview
1093 * limit report table. If missing, uses $key-format.
1094 * - $key-value: Message used to format the value. If missing, uses "$1".
1096 * Note that all values are interpreted as wikitext, and so should be
1097 * encoded with htmlspecialchars() as necessary, but should avoid complex
1098 * HTML for sanity of display in the "NewPP limit report" comment.
1101 * @param string $key Message key
1102 * @param mixed $value Appropriate for Message::params()
1104 public function setLimitReportData( $key, $value ) {
1105 $this->mLimitReportData
[$key] = $value;
1107 if ( is_array( $value ) ) {
1108 if ( array_keys( $value ) === [ 0, 1 ]
1109 && is_numeric( $value[0] )
1110 && is_numeric( $value[1] )
1112 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1120 if ( strpos( $key, '-' ) ) {
1121 list( $ns, $name ) = explode( '-', $key, 2 );
1122 $this->mLimitReportJSData
[$ns][$name] = $data;
1124 $this->mLimitReportJSData
[$key] = $data;
1129 * Check whether the cache TTL was lowered due to dynamic content
1131 * When content is determined by more than hard state (e.g. page edits),
1132 * such as template/file transclusions based on the current timestamp or
1133 * extension tags that generate lists based on queries, this return true.
1138 public function hasDynamicContent() {
1139 global $wgParserCacheExpireTime;
1141 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1145 * Get or set the prevent-clickjacking flag
1148 * @param bool|null $flag New flag value, or null to leave it unchanged
1149 * @return bool Old flag value
1151 public function preventClickjacking( $flag = null ) {
1152 return wfSetVar( $this->mPreventClickjacking
, $flag );
1156 * Lower the runtime adaptive TTL to at most this value
1161 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1162 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1163 $this->updateCacheExpiry( $ttl );
1167 * Call this when parsing is done to lower the TTL based on low parse times
1171 public function finalizeAdaptiveCacheExpiry() {
1172 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1176 $runtime = $this->getTimeSinceStart( 'wall' );
1177 if ( is_float( $runtime ) ) {
1178 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1179 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1180 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1181 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1184 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1185 $this->mMaxAdaptiveExpiry
1187 $this->updateCacheExpiry( $adaptiveTTL );
1191 public function __sleep() {
1193 array_keys( get_object_vars( $this ) ),
1194 [ 'mParseStartTime' ]