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
25 class ParserOutput
extends CacheTime
{
27 * Feature flags to indicate to extensions that MediaWiki core supports and
28 * uses getText() stateless transforms.
30 const SUPPORTS_STATELESS_TRANSFORMS
= 1;
31 const SUPPORTS_UNWRAP_TRANSFORM
= 1;
34 * @var string $mText The output text
39 * @var array $mLanguageLinks List of the full text of language links,
40 * in the order they appear.
42 public $mLanguageLinks;
45 * @var array $mCategoriesMap of category names to sort keys
50 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
52 public $mIndicators = [];
55 * @var string $mTitleText Title text of the chosen language variant, as HTML.
60 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
66 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
69 public $mTemplates = [];
72 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
75 public $mTemplateIds = [];
78 * @var array $mImages DB keys of the images used, in the array key only
83 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
85 public $mFileSearchOptions = [];
88 * @var array $mExternalLinks External link URLs, in the key only.
90 public $mExternalLinks = [];
93 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
94 * for the inline interwiki links in the document.
96 public $mInterwikiLinks = [];
99 * @var bool $mNewSection Show a new section link?
101 public $mNewSection = false;
104 * @var bool $mHideNewSection Hide the new section link?
106 public $mHideNewSection = false;
109 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
111 public $mNoGallery = false;
114 * @var array $mHeadItems Items to put in the <head> section
116 public $mHeadItems = [];
119 * @var array $mModules Modules to be loaded by ResourceLoader
121 public $mModules = [];
124 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
126 public $mModuleScripts = [];
129 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
131 public $mModuleStyles = [];
134 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
136 public $mJsConfigVars = [];
139 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
141 public $mOutputHooks = [];
144 * @var array $mWarnings Warning text to be returned to the user.
145 * Wikitext formatted, in the key only.
147 public $mWarnings = [];
150 * @var array $mSections Table of contents
152 public $mSections = [];
155 * @var array $mProperties Name/value pairs to be cached in the DB.
157 public $mProperties = [];
160 * @var string $mTOCHTML HTML of the TOC.
162 public $mTOCHTML = '';
165 * @var string $mTimestamp Timestamp of the revision.
170 * @var bool $mEnableOOUI Whether OOUI should be enabled.
172 public $mEnableOOUI = false;
175 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
177 private $mIndexPolicy = '';
180 * @var true[] $mAccessedOptions List of ParserOptions (stored in the keys).
182 private $mAccessedOptions = [];
185 * @var array $mExtensionData extra data used by extensions.
187 private $mExtensionData = [];
190 * @var array $mLimitReportData Parser limit report data.
192 private $mLimitReportData = [];
194 /** @var array Parser limit report data for JSON */
195 private $mLimitReportJSData = [];
198 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
200 private $mParseStartTime = [];
203 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
205 private $mPreventClickjacking = false;
208 * @var array $mFlags Generic flags.
210 private $mFlags = [];
212 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
213 private $mSpeculativeRevId;
215 /** string CSS classes to use for the wrapping div, stored in the array keys.
216 * If no class is given, no wrapper is added.
218 private $mWrapperDivClasses = [];
220 /** @var int Upper bound of expiry based on parse duration */
221 private $mMaxAdaptiveExpiry = INF
;
223 const EDITSECTION_REGEX
=
224 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
226 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
227 // Current values imply that m=3933.333333 and b=-333.333333
228 // See https://www.nngroup.com/articles/website-response-times/
229 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
230 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
231 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
232 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
233 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
235 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
236 $unused = false, $titletext = ''
238 $this->mText
= $text;
239 $this->mLanguageLinks
= $languageLinks;
240 $this->mCategories
= $categoryLinks;
241 $this->mTitleText
= $titletext;
245 * Get the cacheable text with <mw:editsection> markers still in it. The
246 * return value is suitable for writing back via setText() but is not valid
247 * for display to the user.
252 public function getRawText() {
257 * Get the output HTML
259 * @param array $options (since 1.31) Transformations to apply to the HTML
260 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
261 * to generate one and `__NOTOC__` wasn't used. Default is true,
262 * but might be statefully overridden.
263 * - enableSectionEditLinks: (bool) Include section edit links, assuming
264 * section edit link tokens are present in the HTML. Default is true,
265 * but might be statefully overridden.
266 * - unwrap: (bool) Return text without a wrapper div. Default is false,
267 * meaning a wrapper div will be added if getWrapperDivClass() returns
268 * a non-empty string.
269 * - wrapperDivClass: (string) Wrap the output in a div and apply the given
270 * CSS class to that div. This overrides the output of getWrapperDivClass().
271 * Setting this to an empty string has the same effect as 'unwrap' => true.
272 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
273 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
274 * value of the attribute: all but the first will be replaced by `<link
275 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
276 * the scheme-specific-part of the href is the (percent-encoded) value
277 * of the `data-mw-deduplicate` attribute.
278 * @return string HTML
280 public function getText( $options = [] ) {
283 'enableSectionEditLinks' => true,
285 'deduplicateStyles' => true,
286 'wrapperDivClass' => $this->getWrapperDivClass(),
288 $text = $this->mText
;
290 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
292 if ( $options['wrapperDivClass'] !== '' && !$options['unwrap'] ) {
293 $text = Html
::rawElement( 'div', [ 'class' => $options['wrapperDivClass'] ], $text );
296 if ( $options['enableSectionEditLinks'] ) {
297 $text = preg_replace_callback(
298 self
::EDITSECTION_REGEX
,
300 global $wgOut, $wgLang;
301 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
302 $editsectionSection = htmlspecialchars_decode( $m[2] );
303 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
305 if ( !is_object( $editsectionPage ) ) {
306 throw new MWException( "Bad parser output text." );
309 $skin = $wgOut->getSkin();
310 return $skin->doEditSectionLink( $editsectionPage,
319 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
322 if ( $options['allowTOC'] ) {
323 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
325 $text = preg_replace(
326 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
332 if ( $options['deduplicateStyles'] ) {
334 $text = preg_replace_callback(
335 '#<style\s+([^>]*data-mw-deduplicate\s*=[^>]*)>.*?</style>#s',
336 function ( $m ) use ( &$seen ) {
337 $attr = Sanitizer
::decodeTagAttributes( $m[1] );
338 if ( !isset( $attr['data-mw-deduplicate'] ) ) {
342 $key = $attr['data-mw-deduplicate'];
343 if ( !isset( $seen[$key] ) ) {
348 // We were going to use an empty <style> here, but there
349 // was concern that would be too much overhead for browsers.
350 // So let's hope a <link> with a non-standard rel and href isn't
351 // going to be misinterpreted or mangled by any subsequent processing.
352 return Html
::element( 'link', [
353 'rel' => 'mw-deduplicated-inline-style',
354 'href' => "mw-data:" . wfUrlencode( $key ),
365 * Add a CSS class to use for the wrapping div. If no class is given, no wrapper is added.
367 * @param string $class
369 public function addWrapperDivClass( $class ) {
370 $this->mWrapperDivClasses
[$class] = true;
374 * Clears the CSS class to use for the wrapping div, effectively disabling the wrapper div
375 * until addWrapperDivClass() is called.
377 public function clearWrapperDivClass() {
378 $this->mWrapperDivClasses
= [];
382 * Returns the class (or classes) to be used with the wrapper div for this otuput.
383 * If there is no wrapper class given, no wrapper div should be added.
384 * The wrapper div is added automatically by getText().
388 public function getWrapperDivClass() {
389 return implode( ' ', array_keys( $this->mWrapperDivClasses
) );
396 public function setSpeculativeRevIdUsed( $id ) {
397 $this->mSpeculativeRevId
= $id;
404 public function getSpeculativeRevIdUsed() {
405 return $this->mSpeculativeRevId
;
408 public function &getLanguageLinks() {
409 return $this->mLanguageLinks
;
412 public function getInterwikiLinks() {
413 return $this->mInterwikiLinks
;
416 public function getCategoryLinks() {
417 return array_keys( $this->mCategories
);
420 public function &getCategories() {
421 return $this->mCategories
;
428 public function getIndicators() {
429 return $this->mIndicators
;
432 public function getTitleText() {
433 return $this->mTitleText
;
436 public function getSections() {
437 return $this->mSections
;
441 * @deprecated since 1.31 Use getText() options.
443 public function getEditSectionTokens() {
444 wfDeprecated( __METHOD__
, '1.31' );
448 public function &getLinks() {
449 return $this->mLinks
;
452 public function &getTemplates() {
453 return $this->mTemplates
;
456 public function &getTemplateIds() {
457 return $this->mTemplateIds
;
460 public function &getImages() {
461 return $this->mImages
;
464 public function &getFileSearchOptions() {
465 return $this->mFileSearchOptions
;
468 public function &getExternalLinks() {
469 return $this->mExternalLinks
;
472 public function getNoGallery() {
473 return $this->mNoGallery
;
476 public function getHeadItems() {
477 return $this->mHeadItems
;
480 public function getModules() {
481 return $this->mModules
;
484 public function getModuleScripts() {
485 return $this->mModuleScripts
;
488 public function getModuleStyles() {
489 return $this->mModuleStyles
;
496 public function getJsConfigVars() {
497 return $this->mJsConfigVars
;
500 public function getOutputHooks() {
501 return (array)$this->mOutputHooks
;
504 public function getWarnings() {
505 return array_keys( $this->mWarnings
);
508 public function getIndexPolicy() {
509 return $this->mIndexPolicy
;
512 public function getTOCHTML() {
513 return $this->mTOCHTML
;
517 * @return string|null TS_MW timestamp of the revision content
519 public function getTimestamp() {
520 return $this->mTimestamp
;
523 public function getLimitReportData() {
524 return $this->mLimitReportData
;
527 public function getLimitReportJSData() {
528 return $this->mLimitReportJSData
;
532 * @deprecated since 1.31 Use getText() options.
534 public function getTOCEnabled() {
535 wfDeprecated( __METHOD__
, '1.31' );
539 public function getEnableOOUI() {
540 return $this->mEnableOOUI
;
543 public function setText( $text ) {
544 return wfSetVar( $this->mText
, $text );
547 public function setLanguageLinks( $ll ) {
548 return wfSetVar( $this->mLanguageLinks
, $ll );
551 public function setCategoryLinks( $cl ) {
552 return wfSetVar( $this->mCategories
, $cl );
555 public function setTitleText( $t ) {
556 return wfSetVar( $this->mTitleText
, $t );
559 public function setSections( $toc ) {
560 return wfSetVar( $this->mSections
, $toc );
564 * @deprecated since 1.31 Use getText() options.
566 public function setEditSectionTokens( $t ) {
567 wfDeprecated( __METHOD__
, '1.31' );
571 public function setIndexPolicy( $policy ) {
572 return wfSetVar( $this->mIndexPolicy
, $policy );
575 public function setTOCHTML( $tochtml ) {
576 return wfSetVar( $this->mTOCHTML
, $tochtml );
579 public function setTimestamp( $timestamp ) {
580 return wfSetVar( $this->mTimestamp
, $timestamp );
584 * @deprecated since 1.31 Use getText() options.
586 public function setTOCEnabled( $flag ) {
587 wfDeprecated( __METHOD__
, '1.31' );
591 public function addCategory( $c, $sort ) {
592 $this->mCategories
[$c] = $sort;
597 * @param string $content
600 public function setIndicator( $id, $content ) {
601 $this->mIndicators
[$id] = $content;
605 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
606 * object is added to.
609 * @param bool $enable If OOUI should be enabled or not
611 public function setEnableOOUI( $enable = false ) {
612 $this->mEnableOOUI
= $enable;
615 public function addLanguageLink( $t ) {
616 $this->mLanguageLinks
[] = $t;
619 public function addWarning( $s ) {
620 $this->mWarnings
[$s] = 1;
623 public function addOutputHook( $hook, $data = false ) {
624 $this->mOutputHooks
[] = [ $hook, $data ];
627 public function setNewSection( $value ) {
628 $this->mNewSection
= (bool)$value;
630 public function hideNewSection( $value ) {
631 $this->mHideNewSection
= (bool)$value;
633 public function getHideNewSection() {
634 return (bool)$this->mHideNewSection
;
636 public function getNewSection() {
637 return (bool)$this->mNewSection
;
641 * Checks, if a url is pointing to the own server
643 * @param string $internal The server to check against
644 * @param string $url The url to check
647 public static function isLinkInternal( $internal, $url ) {
648 return (bool)preg_match( '/^' .
649 # If server is proto relative, check also for http/https links
650 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
651 preg_quote( $internal, '/' ) .
652 # check for query/path/anchor or end of link in each case
658 public function addExternalLink( $url ) {
659 # We don't register links pointing to our own server, unless... :-)
660 global $wgServer, $wgRegisterInternalExternals;
662 # Replace unnecessary URL escape codes with the referenced character
663 # This prevents spammers from hiding links from the filters
664 $url = Parser
::normalizeLinkUrl( $url );
666 $registerExternalLink = true;
667 if ( !$wgRegisterInternalExternals ) {
668 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
670 if ( $registerExternalLink ) {
671 $this->mExternalLinks
[$url] = 1;
676 * Record a local or interwiki inline link for saving in future link tables.
678 * @param Title $title
679 * @param int|null $id Optional known page_id so we can skip the lookup
681 public function addLink( Title
$title, $id = null ) {
682 if ( $title->isExternal() ) {
683 // Don't record interwikis in pagelinks
684 $this->addInterwikiLink( $title );
687 $ns = $title->getNamespace();
688 $dbk = $title->getDBkey();
689 if ( $ns == NS_MEDIA
) {
690 // Normalize this pseudo-alias if it makes it down here...
692 } elseif ( $ns == NS_SPECIAL
) {
693 // We don't record Special: links currently
694 // It might actually be wise to, but we'd need to do some normalization.
696 } elseif ( $dbk === '' ) {
697 // Don't record self links - [[#Foo]]
700 if ( !isset( $this->mLinks
[$ns] ) ) {
701 $this->mLinks
[$ns] = [];
703 if ( is_null( $id ) ) {
704 $id = $title->getArticleID();
706 $this->mLinks
[$ns][$dbk] = $id;
710 * Register a file dependency for this output
711 * @param string $name Title dbKey
712 * @param string|false|null $timestamp MW timestamp of file creation (or false if non-existing)
713 * @param string|false|null $sha1 Base 36 SHA-1 of file (or false if non-existing)
715 public function addImage( $name, $timestamp = null, $sha1 = null ) {
716 $this->mImages
[$name] = 1;
717 if ( $timestamp !== null && $sha1 !== null ) {
718 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
723 * Register a template dependency for this output
724 * @param Title $title
725 * @param int $page_id
728 public function addTemplate( $title, $page_id, $rev_id ) {
729 $ns = $title->getNamespace();
730 $dbk = $title->getDBkey();
731 if ( !isset( $this->mTemplates
[$ns] ) ) {
732 $this->mTemplates
[$ns] = [];
734 $this->mTemplates
[$ns][$dbk] = $page_id;
735 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
736 $this->mTemplateIds
[$ns] = [];
738 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
742 * @param Title $title Title object, must be an interwiki link
743 * @throws MWException If given invalid input
745 public function addInterwikiLink( $title ) {
746 if ( !$title->isExternal() ) {
747 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
749 $prefix = $title->getInterwiki();
750 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
751 $this->mInterwikiLinks
[$prefix] = [];
753 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
757 * Add some text to the "<head>".
758 * If $tag is set, the section with that tag will only be included once
760 * @param string $section
761 * @param string|bool $tag
763 public function addHeadItem( $section, $tag = false ) {
764 if ( $tag !== false ) {
765 $this->mHeadItems
[$tag] = $section;
767 $this->mHeadItems
[] = $section;
772 * @see OutputPage::addModules
774 public function addModules( $modules ) {
775 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
779 * @deprecated since 1.31 Use addModules() instead.
780 * @see OutputPage::addModuleScripts
782 public function addModuleScripts( $modules ) {
783 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
787 * @see OutputPage::addModuleStyles
789 public function addModuleStyles( $modules ) {
790 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
794 * Add one or more variables to be set in mw.config in JavaScript.
796 * @param string|array $keys Key or array of key/value pairs.
797 * @param mixed|null $value [optional] Value of the configuration variable.
800 public function addJsConfigVars( $keys, $value = null ) {
801 if ( is_array( $keys ) ) {
802 foreach ( $keys as $key => $value ) {
803 $this->mJsConfigVars
[$key] = $value;
808 $this->mJsConfigVars
[$keys] = $value;
812 * Copy items from the OutputPage object into this one
814 * @param OutputPage $out
816 public function addOutputPageMetadata( OutputPage
$out ) {
817 $this->addModules( $out->getModules() );
818 $this->addModuleScripts( $out->getModuleScripts() );
819 $this->addModuleStyles( $out->getModuleStyles() );
820 $this->addJsConfigVars( $out->getJsConfigVars() );
822 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
823 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
827 * Add a tracking category, getting the title from a system message,
828 * or print a debug message if the title is invalid.
830 * Any message used with this function should be registered so it will
831 * show up on Special:TrackingCategories. Core messages should be added
832 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
833 * should add to "TrackingCategories" in their extension.json.
835 * @todo Migrate some code to TrackingCategories
837 * @param string $msg Message key
838 * @param Title $title title of the page which is being tracked
839 * @return bool Whether the addition was successful
842 public function addTrackingCategory( $msg, $title ) {
843 if ( $title->isSpecialPage() ) {
844 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
848 // Important to parse with correct title (T33469)
849 $cat = wfMessage( $msg )
851 ->inContentLanguage()
854 # Allow tracking categories to be disabled by setting them to "-"
855 if ( $cat === '-' ) {
859 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
860 if ( $containerCategory ) {
861 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
864 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
870 * Override the title to be used for display
872 * @note this is assumed to have been validated
873 * (check equal normalisation, etc.)
875 * @note this is expected to be safe HTML,
876 * ready to be served to the client.
878 * @param string $text Desired title text
880 public function setDisplayTitle( $text ) {
881 $this->setTitleText( $text );
882 $this->setProperty( 'displaytitle', $text );
886 * Get the title to be used for display.
888 * As per the contract of setDisplayTitle(), this is safe HTML,
889 * ready to be served to the client.
891 * @return string HTML
893 public function getDisplayTitle() {
894 $t = $this->getTitleText();
902 * Fairly generic flag setter thingy.
903 * @param string $flag
905 public function setFlag( $flag ) {
906 $this->mFlags
[$flag] = true;
909 public function getFlag( $flag ) {
910 return isset( $this->mFlags
[$flag] );
914 * Set a property to be stored in the page_props database table.
916 * page_props is a key value store indexed by the page ID. This allows
917 * the parser to set a property on a page which can then be quickly
918 * retrieved given the page ID or via a DB join when given the page
921 * Since 1.23, page_props are also indexed by numeric value, to allow
922 * for efficient "top k" queries of pages wrt a given property.
924 * setProperty() is thus used to propagate properties from the parsed
925 * page to request contexts other than a page view of the currently parsed
928 * Some applications examples:
930 * * To implement hidden categories, hiding pages from category listings
931 * by storing a property.
933 * * Overriding the displayed article title (ParserOutput::setDisplayTitle()).
935 * * To implement image tagging, for example displaying an icon on an
936 * image thumbnail to indicate that it is listed for deletion on
938 * This is not actually implemented, yet but would be pretty cool.
940 * @note Do not use setProperty() to set a property which is only used
941 * in a context where the ParserOutput object itself is already available,
942 * for example a normal page view. There is no need to save such a property
943 * in the database since the text is already parsed. You can just hook
944 * OutputPageParserOutput and get your data out of the ParserOutput object.
946 * If you are writing an extension where you want to set a property in the
947 * parser which is used by an OutputPageParserOutput hook, you have to
948 * associate the extension data directly with the ParserOutput object.
949 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
953 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
956 * And then later, in OutputPageParserOutput or similar:
960 * $output->getExtensionData( 'my_ext_foo' );
963 * In MediaWiki 1.20 and older, you have to use a custom member variable
964 * within the ParserOutput object:
968 * $parser->getOutput()->my_ext_foo = '...';
970 * @param string $name
971 * @param mixed $value
973 public function setProperty( $name, $value ) {
974 $this->mProperties
[$name] = $value;
978 * @param string $name The property name to look up.
980 * @return mixed|bool The value previously set using setProperty(). False if null or no value
981 * was set for the given property name.
983 * @note You need to use getProperties() to check for boolean and null properties.
985 public function getProperty( $name ) {
986 return $this->mProperties
[$name] ??
false;
989 public function unsetProperty( $name ) {
990 unset( $this->mProperties
[$name] );
993 public function getProperties() {
994 if ( !isset( $this->mProperties
) ) {
995 $this->mProperties
= [];
997 return $this->mProperties
;
1001 * Returns the options from its ParserOptions which have been taken
1002 * into account to produce this output.
1005 public function getUsedOptions() {
1006 if ( !isset( $this->mAccessedOptions
) ) {
1009 return array_keys( $this->mAccessedOptions
);
1013 * Tags a parser option for use in the cache key for this parser output.
1014 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
1015 * The information gathered here is available via getUsedOptions(),
1016 * and is used by ParserCache::save().
1018 * @see ParserCache::getKey
1019 * @see ParserCache::save
1020 * @see ParserOptions::addExtraKey
1021 * @see ParserOptions::optionsHash
1022 * @param string $option
1024 public function recordOption( $option ) {
1025 $this->mAccessedOptions
[$option] = true;
1029 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
1030 * the ParserOutput object for later use during page output. The data will be cached along with
1031 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1034 * This method is provided to overcome the unsafe practice of attaching extra information to a
1035 * ParserObject by directly assigning member variables.
1037 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1038 * hook in the page output, use this in the parser hook:
1042 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1045 * And then later, in OutputPageParserOutput or similar:
1049 * $output->getExtensionData( 'my_ext_foo' );
1052 * In MediaWiki 1.20 and older, you have to use a custom member variable
1053 * within the ParserOutput object:
1057 * $parser->getOutput()->my_ext_foo = '...';
1062 * @param string $key The key for accessing the data. Extensions should take care to avoid
1063 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1065 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1068 public function setExtensionData( $key, $value ) {
1069 if ( $value === null ) {
1070 unset( $this->mExtensionData
[$key] );
1072 $this->mExtensionData
[$key] = $value;
1077 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1078 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1082 * @param string $key The key to look up.
1084 * @return mixed|null The value previously set for the given key using setExtensionData()
1085 * or null if no value was set for this key.
1087 public function getExtensionData( $key ) {
1088 if ( isset( $this->mExtensionData
[$key] ) ) {
1089 return $this->mExtensionData
[$key];
1095 private static function getTimes( $clock = null ) {
1097 if ( !$clock ||
$clock === 'wall' ) {
1098 $ret['wall'] = microtime( true );
1100 if ( !$clock ||
$clock === 'cpu' ) {
1101 $ru = wfGetRusage();
1103 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1104 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1111 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1114 public function resetParseStartTime() {
1115 $this->mParseStartTime
= self
::getTimes();
1119 * Returns the time since resetParseStartTime() was last called
1121 * Clocks available are:
1122 * - wall: Wall clock time
1123 * - cpu: CPU time (requires getrusage)
1126 * @param string $clock
1127 * @return float|null
1129 public function getTimeSinceStart( $clock ) {
1130 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1134 $end = self
::getTimes( $clock );
1135 return $end[$clock] - $this->mParseStartTime
[$clock];
1139 * Sets parser limit report data for a key
1141 * The key is used as the prefix for various messages used for formatting:
1142 * - $key: The label for the field in the limit report
1143 * - $key-value-text: Message used to format the value in the "NewPP limit
1144 * report" HTML comment. If missing, uses $key-format.
1145 * - $key-value-html: Message used to format the value in the preview
1146 * limit report table. If missing, uses $key-format.
1147 * - $key-value: Message used to format the value. If missing, uses "$1".
1149 * Note that all values are interpreted as wikitext, and so should be
1150 * encoded with htmlspecialchars() as necessary, but should avoid complex
1151 * HTML for sanity of display in the "NewPP limit report" comment.
1154 * @param string $key Message key
1155 * @param mixed $value Appropriate for Message::params()
1157 public function setLimitReportData( $key, $value ) {
1158 $this->mLimitReportData
[$key] = $value;
1160 if ( is_array( $value ) ) {
1161 if ( array_keys( $value ) === [ 0, 1 ]
1162 && is_numeric( $value[0] )
1163 && is_numeric( $value[1] )
1165 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1173 if ( strpos( $key, '-' ) ) {
1174 list( $ns, $name ) = explode( '-', $key, 2 );
1175 $this->mLimitReportJSData
[$ns][$name] = $data;
1177 $this->mLimitReportJSData
[$key] = $data;
1182 * Check whether the cache TTL was lowered due to dynamic content
1184 * When content is determined by more than hard state (e.g. page edits),
1185 * such as template/file transclusions based on the current timestamp or
1186 * extension tags that generate lists based on queries, this return true.
1191 public function hasDynamicContent() {
1192 global $wgParserCacheExpireTime;
1194 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1198 * Get or set the prevent-clickjacking flag
1201 * @param bool|null $flag New flag value, or null to leave it unchanged
1202 * @return bool Old flag value
1204 public function preventClickjacking( $flag = null ) {
1205 return wfSetVar( $this->mPreventClickjacking
, $flag );
1209 * Lower the runtime adaptive TTL to at most this value
1214 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1215 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1216 $this->updateCacheExpiry( $ttl );
1220 * Call this when parsing is done to lower the TTL based on low parse times
1224 public function finalizeAdaptiveCacheExpiry() {
1225 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1229 $runtime = $this->getTimeSinceStart( 'wall' );
1230 if ( is_float( $runtime ) ) {
1231 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1232 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1233 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1234 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1237 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1238 $this->mMaxAdaptiveExpiry
1240 $this->updateCacheExpiry( $adaptiveTTL );
1244 public function __sleep() {
1246 array_keys( get_object_vars( $this ) ),
1247 [ 'mParseStartTime' ]