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 /** @var int Upper bound of expiry based on parse duration */
216 private $mMaxAdaptiveExpiry = INF
;
218 const EDITSECTION_REGEX
=
219 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
221 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
222 // Current values imply that m=3933.333333 and b=-333.333333
223 // See https://www.nngroup.com/articles/website-response-times/
224 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
225 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
226 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
227 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
228 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
230 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
231 $unused = false, $titletext = ''
233 $this->mText
= $text;
234 $this->mLanguageLinks
= $languageLinks;
235 $this->mCategories
= $categoryLinks;
236 $this->mTitleText
= $titletext;
240 * Get the cacheable text with <mw:editsection> markers still in it. The
241 * return value is suitable for writing back via setText() but is not valid
242 * for display to the user.
247 public function getRawText() {
252 * Get the output HTML
254 * @param array $options (since 1.31) Transformations to apply to the HTML
255 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
256 * to generate one and `__NOTOC__` wasn't used. Default is true,
257 * but might be statefully overridden.
258 * - enableSectionEditLinks: (bool) Include section edit links, assuming
259 * section edit link tokens are present in the HTML. Default is true,
260 * but might be statefully overridden.
261 * - unwrap: (bool) Remove a wrapping mw-parser-output div. Default is false.
262 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
263 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
264 * value of the attribute: all but the first will be replaced by `<link
265 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
266 * the scheme-specific-part of the href is the (percent-encoded) value
267 * of the `data-mw-deduplicate` attribute.
268 * @return string HTML
270 public function getText( $options = [] ) {
273 'enableSectionEditLinks' => true,
275 'deduplicateStyles' => true,
277 $text = $this->mText
;
279 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
281 if ( $options['unwrap'] !== false ) {
282 $start = Html
::openElement( 'div', [
283 'class' => 'mw-parser-output'
285 $startLen = strlen( $start );
286 $end = Html
::closeElement( 'div' );
287 $endPos = strrpos( $text, $end );
288 $endLen = strlen( $end );
290 if ( substr( $text, 0, $startLen ) === $start && $endPos !== false
291 // if the closing div is followed by real content, bail out of unwrapping
292 && preg_match( '/^(?>\s*<!--.*?-->)*\s*$/s', substr( $text, $endPos +
$endLen ) )
294 $text = substr( $text, $startLen );
295 $text = substr( $text, 0, $endPos - $startLen )
296 . substr( $text, $endPos - $startLen +
$endLen );
300 if ( $options['enableSectionEditLinks'] ) {
301 $text = preg_replace_callback(
302 self
::EDITSECTION_REGEX
,
304 global $wgOut, $wgLang;
305 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
306 $editsectionSection = htmlspecialchars_decode( $m[2] );
307 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
309 if ( !is_object( $editsectionPage ) ) {
310 throw new MWException( "Bad parser output text." );
313 $skin = $wgOut->getSkin();
314 return $skin->doEditSectionLink( $editsectionPage,
323 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
326 if ( $options['allowTOC'] ) {
327 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
329 $text = preg_replace(
330 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
336 if ( $options['deduplicateStyles'] ) {
338 $text = preg_replace_callback(
339 '#<style\s+([^>]*data-mw-deduplicate\s*=[^>]*)>.*?</style>#s',
340 function ( $m ) use ( &$seen ) {
341 $attr = Sanitizer
::decodeTagAttributes( $m[1] );
342 if ( !isset( $attr['data-mw-deduplicate'] ) ) {
346 $key = $attr['data-mw-deduplicate'];
347 if ( !isset( $seen[$key] ) ) {
352 // We were going to use an empty <style> here, but there
353 // was concern that would be too much overhead for browsers.
354 // So let's hope a <link> with a non-standard rel and href isn't
355 // going to be misinterpreted or mangled by any subsequent processing.
356 return Html
::element( 'link', [
357 'rel' => 'mw-deduplicated-inline-style',
358 'href' => "mw-data:" . wfUrlencode( $key ),
372 public function setSpeculativeRevIdUsed( $id ) {
373 $this->mSpeculativeRevId
= $id;
380 public function getSpeculativeRevIdUsed() {
381 return $this->mSpeculativeRevId
;
384 public function &getLanguageLinks() {
385 return $this->mLanguageLinks
;
388 public function getInterwikiLinks() {
389 return $this->mInterwikiLinks
;
392 public function getCategoryLinks() {
393 return array_keys( $this->mCategories
);
396 public function &getCategories() {
397 return $this->mCategories
;
404 public function getIndicators() {
405 return $this->mIndicators
;
408 public function getTitleText() {
409 return $this->mTitleText
;
412 public function getSections() {
413 return $this->mSections
;
417 * @deprecated since 1.31 Use getText() options.
419 public function getEditSectionTokens() {
420 wfDeprecated( __METHOD__
, '1.31' );
424 public function &getLinks() {
425 return $this->mLinks
;
428 public function &getTemplates() {
429 return $this->mTemplates
;
432 public function &getTemplateIds() {
433 return $this->mTemplateIds
;
436 public function &getImages() {
437 return $this->mImages
;
440 public function &getFileSearchOptions() {
441 return $this->mFileSearchOptions
;
444 public function &getExternalLinks() {
445 return $this->mExternalLinks
;
448 public function getNoGallery() {
449 return $this->mNoGallery
;
452 public function getHeadItems() {
453 return $this->mHeadItems
;
456 public function getModules() {
457 return $this->mModules
;
460 public function getModuleScripts() {
461 return $this->mModuleScripts
;
464 public function getModuleStyles() {
465 return $this->mModuleStyles
;
472 public function getJsConfigVars() {
473 return $this->mJsConfigVars
;
476 public function getOutputHooks() {
477 return (array)$this->mOutputHooks
;
480 public function getWarnings() {
481 return array_keys( $this->mWarnings
);
484 public function getIndexPolicy() {
485 return $this->mIndexPolicy
;
488 public function getTOCHTML() {
489 return $this->mTOCHTML
;
493 * @return string|null TS_MW timestamp of the revision content
495 public function getTimestamp() {
496 return $this->mTimestamp
;
499 public function getLimitReportData() {
500 return $this->mLimitReportData
;
503 public function getLimitReportJSData() {
504 return $this->mLimitReportJSData
;
508 * @deprecated since 1.31 Use getText() options.
510 public function getTOCEnabled() {
511 wfDeprecated( __METHOD__
, '1.31' );
515 public function getEnableOOUI() {
516 return $this->mEnableOOUI
;
519 public function setText( $text ) {
520 return wfSetVar( $this->mText
, $text );
523 public function setLanguageLinks( $ll ) {
524 return wfSetVar( $this->mLanguageLinks
, $ll );
527 public function setCategoryLinks( $cl ) {
528 return wfSetVar( $this->mCategories
, $cl );
531 public function setTitleText( $t ) {
532 return wfSetVar( $this->mTitleText
, $t );
535 public function setSections( $toc ) {
536 return wfSetVar( $this->mSections
, $toc );
540 * @deprecated since 1.31 Use getText() options.
542 public function setEditSectionTokens( $t ) {
543 wfDeprecated( __METHOD__
, '1.31' );
547 public function setIndexPolicy( $policy ) {
548 return wfSetVar( $this->mIndexPolicy
, $policy );
551 public function setTOCHTML( $tochtml ) {
552 return wfSetVar( $this->mTOCHTML
, $tochtml );
555 public function setTimestamp( $timestamp ) {
556 return wfSetVar( $this->mTimestamp
, $timestamp );
560 * @deprecated since 1.31 Use getText() options.
562 public function setTOCEnabled( $flag ) {
563 wfDeprecated( __METHOD__
, '1.31' );
567 public function addCategory( $c, $sort ) {
568 $this->mCategories
[$c] = $sort;
573 * @param string $content
576 public function setIndicator( $id, $content ) {
577 $this->mIndicators
[$id] = $content;
581 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
582 * object is added to.
585 * @param bool $enable If OOUI should be enabled or not
587 public function setEnableOOUI( $enable = false ) {
588 $this->mEnableOOUI
= $enable;
591 public function addLanguageLink( $t ) {
592 $this->mLanguageLinks
[] = $t;
595 public function addWarning( $s ) {
596 $this->mWarnings
[$s] = 1;
599 public function addOutputHook( $hook, $data = false ) {
600 $this->mOutputHooks
[] = [ $hook, $data ];
603 public function setNewSection( $value ) {
604 $this->mNewSection
= (bool)$value;
606 public function hideNewSection( $value ) {
607 $this->mHideNewSection
= (bool)$value;
609 public function getHideNewSection() {
610 return (bool)$this->mHideNewSection
;
612 public function getNewSection() {
613 return (bool)$this->mNewSection
;
617 * Checks, if a url is pointing to the own server
619 * @param string $internal The server to check against
620 * @param string $url The url to check
623 public static function isLinkInternal( $internal, $url ) {
624 return (bool)preg_match( '/^' .
625 # If server is proto relative, check also for http/https links
626 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
627 preg_quote( $internal, '/' ) .
628 # check for query/path/anchor or end of link in each case
634 public function addExternalLink( $url ) {
635 # We don't register links pointing to our own server, unless... :-)
636 global $wgServer, $wgRegisterInternalExternals;
638 # Replace unnecessary URL escape codes with the referenced character
639 # This prevents spammers from hiding links from the filters
640 $url = Parser
::normalizeLinkUrl( $url );
642 $registerExternalLink = true;
643 if ( !$wgRegisterInternalExternals ) {
644 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
646 if ( $registerExternalLink ) {
647 $this->mExternalLinks
[$url] = 1;
652 * Record a local or interwiki inline link for saving in future link tables.
654 * @param Title $title
655 * @param int|null $id Optional known page_id so we can skip the lookup
657 public function addLink( Title
$title, $id = null ) {
658 if ( $title->isExternal() ) {
659 // Don't record interwikis in pagelinks
660 $this->addInterwikiLink( $title );
663 $ns = $title->getNamespace();
664 $dbk = $title->getDBkey();
665 if ( $ns == NS_MEDIA
) {
666 // Normalize this pseudo-alias if it makes it down here...
668 } elseif ( $ns == NS_SPECIAL
) {
669 // We don't record Special: links currently
670 // It might actually be wise to, but we'd need to do some normalization.
672 } elseif ( $dbk === '' ) {
673 // Don't record self links - [[#Foo]]
676 if ( !isset( $this->mLinks
[$ns] ) ) {
677 $this->mLinks
[$ns] = [];
679 if ( is_null( $id ) ) {
680 $id = $title->getArticleID();
682 $this->mLinks
[$ns][$dbk] = $id;
686 * Register a file dependency for this output
687 * @param string $name Title dbKey
688 * @param string|false|null $timestamp MW timestamp of file creation (or false if non-existing)
689 * @param string|false|null $sha1 Base 36 SHA-1 of file (or false if non-existing)
691 public function addImage( $name, $timestamp = null, $sha1 = null ) {
692 $this->mImages
[$name] = 1;
693 if ( $timestamp !== null && $sha1 !== null ) {
694 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
699 * Register a template dependency for this output
700 * @param Title $title
701 * @param int $page_id
704 public function addTemplate( $title, $page_id, $rev_id ) {
705 $ns = $title->getNamespace();
706 $dbk = $title->getDBkey();
707 if ( !isset( $this->mTemplates
[$ns] ) ) {
708 $this->mTemplates
[$ns] = [];
710 $this->mTemplates
[$ns][$dbk] = $page_id;
711 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
712 $this->mTemplateIds
[$ns] = [];
714 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
718 * @param Title $title Title object, must be an interwiki link
719 * @throws MWException If given invalid input
721 public function addInterwikiLink( $title ) {
722 if ( !$title->isExternal() ) {
723 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
725 $prefix = $title->getInterwiki();
726 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
727 $this->mInterwikiLinks
[$prefix] = [];
729 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
733 * Add some text to the "<head>".
734 * If $tag is set, the section with that tag will only be included once
736 * @param string $section
737 * @param string|bool $tag
739 public function addHeadItem( $section, $tag = false ) {
740 if ( $tag !== false ) {
741 $this->mHeadItems
[$tag] = $section;
743 $this->mHeadItems
[] = $section;
748 * @see OutputPage::addModules
750 public function addModules( $modules ) {
751 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
755 * @deprecated since 1.31 Use addModules() instead.
756 * @see OutputPage::addModuleScripts
758 public function addModuleScripts( $modules ) {
759 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
763 * @see OutputPage::addModuleStyles
765 public function addModuleStyles( $modules ) {
766 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
770 * Add one or more variables to be set in mw.config in JavaScript.
772 * @param string|array $keys Key or array of key/value pairs.
773 * @param mixed $value [optional] Value of the configuration variable.
776 public function addJsConfigVars( $keys, $value = null ) {
777 if ( is_array( $keys ) ) {
778 foreach ( $keys as $key => $value ) {
779 $this->mJsConfigVars
[$key] = $value;
784 $this->mJsConfigVars
[$keys] = $value;
788 * Copy items from the OutputPage object into this one
790 * @param OutputPage $out
792 public function addOutputPageMetadata( OutputPage
$out ) {
793 $this->addModules( $out->getModules() );
794 $this->addModuleScripts( $out->getModuleScripts() );
795 $this->addModuleStyles( $out->getModuleStyles() );
796 $this->addJsConfigVars( $out->getJsConfigVars() );
798 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
799 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
803 * Add a tracking category, getting the title from a system message,
804 * or print a debug message if the title is invalid.
806 * Any message used with this function should be registered so it will
807 * show up on Special:TrackingCategories. Core messages should be added
808 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
809 * should add to "TrackingCategories" in their extension.json.
811 * @todo Migrate some code to TrackingCategories
813 * @param string $msg Message key
814 * @param Title $title title of the page which is being tracked
815 * @return bool Whether the addition was successful
818 public function addTrackingCategory( $msg, $title ) {
819 if ( $title->isSpecialPage() ) {
820 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
824 // Important to parse with correct title (T33469)
825 $cat = wfMessage( $msg )
827 ->inContentLanguage()
830 # Allow tracking categories to be disabled by setting them to "-"
831 if ( $cat === '-' ) {
835 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
836 if ( $containerCategory ) {
837 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
840 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
846 * Override the title to be used for display
848 * @note this is assumed to have been validated
849 * (check equal normalisation, etc.)
851 * @note this is expected to be safe HTML,
852 * ready to be served to the client.
854 * @param string $text Desired title text
856 public function setDisplayTitle( $text ) {
857 $this->setTitleText( $text );
858 $this->setProperty( 'displaytitle', $text );
862 * Get the title to be used for display.
864 * As per the contract of setDisplayTitle(), this is safe HTML,
865 * ready to be served to the client.
867 * @return string HTML
869 public function getDisplayTitle() {
870 $t = $this->getTitleText();
878 * Fairly generic flag setter thingy.
879 * @param string $flag
881 public function setFlag( $flag ) {
882 $this->mFlags
[$flag] = true;
885 public function getFlag( $flag ) {
886 return isset( $this->mFlags
[$flag] );
890 * Set a property to be stored in the page_props database table.
892 * page_props is a key value store indexed by the page ID. This allows
893 * the parser to set a property on a page which can then be quickly
894 * retrieved given the page ID or via a DB join when given the page
897 * Since 1.23, page_props are also indexed by numeric value, to allow
898 * for efficient "top k" queries of pages wrt a given property.
900 * setProperty() is thus used to propagate properties from the parsed
901 * page to request contexts other than a page view of the currently parsed
904 * Some applications examples:
906 * * To implement hidden categories, hiding pages from category listings
907 * by storing a property.
909 * * Overriding the displayed article title (ParserOutput::setDisplayTitle()).
911 * * To implement image tagging, for example displaying an icon on an
912 * image thumbnail to indicate that it is listed for deletion on
914 * This is not actually implemented, yet but would be pretty cool.
916 * @note Do not use setProperty() to set a property which is only used
917 * in a context where the ParserOutput object itself is already available,
918 * for example a normal page view. There is no need to save such a property
919 * in the database since the text is already parsed. You can just hook
920 * OutputPageParserOutput and get your data out of the ParserOutput object.
922 * If you are writing an extension where you want to set a property in the
923 * parser which is used by an OutputPageParserOutput hook, you have to
924 * associate the extension data directly with the ParserOutput object.
925 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
929 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
932 * And then later, in OutputPageParserOutput or similar:
936 * $output->getExtensionData( 'my_ext_foo' );
939 * In MediaWiki 1.20 and older, you have to use a custom member variable
940 * within the ParserOutput object:
944 * $parser->getOutput()->my_ext_foo = '...';
946 * @param string $name
947 * @param mixed $value
949 public function setProperty( $name, $value ) {
950 $this->mProperties
[$name] = $value;
954 * @param string $name The property name to look up.
956 * @return mixed|bool The value previously set using setProperty(). False if null or no value
957 * was set for the given property name.
959 * @note You need to use getProperties() to check for boolean and null properties.
961 public function getProperty( $name ) {
962 return $this->mProperties
[$name] ??
false;
965 public function unsetProperty( $name ) {
966 unset( $this->mProperties
[$name] );
969 public function getProperties() {
970 if ( !isset( $this->mProperties
) ) {
971 $this->mProperties
= [];
973 return $this->mProperties
;
977 * Returns the options from its ParserOptions which have been taken
978 * into account to produce this output.
981 public function getUsedOptions() {
982 if ( !isset( $this->mAccessedOptions
) ) {
985 return array_keys( $this->mAccessedOptions
);
989 * Tags a parser option for use in the cache key for this parser output.
990 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
991 * The information gathered here is available via getUsedOptions(),
992 * and is used by ParserCache::save().
994 * @see ParserCache::getKey
995 * @see ParserCache::save
996 * @see ParserOptions::addExtraKey
997 * @see ParserOptions::optionsHash
998 * @param string $option
1000 public function recordOption( $option ) {
1001 $this->mAccessedOptions
[$option] = true;
1005 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
1006 * the ParserOutput object for later use during page output. The data will be cached along with
1007 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1010 * This method is provided to overcome the unsafe practice of attaching extra information to a
1011 * ParserObject by directly assigning member variables.
1013 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1014 * hook in the page output, use this in the parser hook:
1018 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1021 * And then later, in OutputPageParserOutput or similar:
1025 * $output->getExtensionData( 'my_ext_foo' );
1028 * In MediaWiki 1.20 and older, you have to use a custom member variable
1029 * within the ParserOutput object:
1033 * $parser->getOutput()->my_ext_foo = '...';
1038 * @param string $key The key for accessing the data. Extensions should take care to avoid
1039 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1041 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1044 public function setExtensionData( $key, $value ) {
1045 if ( $value === null ) {
1046 unset( $this->mExtensionData
[$key] );
1048 $this->mExtensionData
[$key] = $value;
1053 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1054 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1058 * @param string $key The key to look up.
1060 * @return mixed|null The value previously set for the given key using setExtensionData()
1061 * or null if no value was set for this key.
1063 public function getExtensionData( $key ) {
1064 if ( isset( $this->mExtensionData
[$key] ) ) {
1065 return $this->mExtensionData
[$key];
1071 private static function getTimes( $clock = null ) {
1073 if ( !$clock ||
$clock === 'wall' ) {
1074 $ret['wall'] = microtime( true );
1076 if ( !$clock ||
$clock === 'cpu' ) {
1077 $ru = wfGetRusage();
1079 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1080 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1087 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1090 public function resetParseStartTime() {
1091 $this->mParseStartTime
= self
::getTimes();
1095 * Returns the time since resetParseStartTime() was last called
1097 * Clocks available are:
1098 * - wall: Wall clock time
1099 * - cpu: CPU time (requires getrusage)
1102 * @param string $clock
1103 * @return float|null
1105 public function getTimeSinceStart( $clock ) {
1106 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1110 $end = self
::getTimes( $clock );
1111 return $end[$clock] - $this->mParseStartTime
[$clock];
1115 * Sets parser limit report data for a key
1117 * The key is used as the prefix for various messages used for formatting:
1118 * - $key: The label for the field in the limit report
1119 * - $key-value-text: Message used to format the value in the "NewPP limit
1120 * report" HTML comment. If missing, uses $key-format.
1121 * - $key-value-html: Message used to format the value in the preview
1122 * limit report table. If missing, uses $key-format.
1123 * - $key-value: Message used to format the value. If missing, uses "$1".
1125 * Note that all values are interpreted as wikitext, and so should be
1126 * encoded with htmlspecialchars() as necessary, but should avoid complex
1127 * HTML for sanity of display in the "NewPP limit report" comment.
1130 * @param string $key Message key
1131 * @param mixed $value Appropriate for Message::params()
1133 public function setLimitReportData( $key, $value ) {
1134 $this->mLimitReportData
[$key] = $value;
1136 if ( is_array( $value ) ) {
1137 if ( array_keys( $value ) === [ 0, 1 ]
1138 && is_numeric( $value[0] )
1139 && is_numeric( $value[1] )
1141 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1149 if ( strpos( $key, '-' ) ) {
1150 list( $ns, $name ) = explode( '-', $key, 2 );
1151 $this->mLimitReportJSData
[$ns][$name] = $data;
1153 $this->mLimitReportJSData
[$key] = $data;
1158 * Check whether the cache TTL was lowered due to dynamic content
1160 * When content is determined by more than hard state (e.g. page edits),
1161 * such as template/file transclusions based on the current timestamp or
1162 * extension tags that generate lists based on queries, this return true.
1167 public function hasDynamicContent() {
1168 global $wgParserCacheExpireTime;
1170 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1174 * Get or set the prevent-clickjacking flag
1177 * @param bool|null $flag New flag value, or null to leave it unchanged
1178 * @return bool Old flag value
1180 public function preventClickjacking( $flag = null ) {
1181 return wfSetVar( $this->mPreventClickjacking
, $flag );
1185 * Lower the runtime adaptive TTL to at most this value
1190 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1191 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1192 $this->updateCacheExpiry( $ttl );
1196 * Call this when parsing is done to lower the TTL based on low parse times
1200 public function finalizeAdaptiveCacheExpiry() {
1201 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1205 $runtime = $this->getTimeSinceStart( 'wall' );
1206 if ( is_float( $runtime ) ) {
1207 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1208 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1209 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1210 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1213 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1214 $this->mMaxAdaptiveExpiry
1216 $this->updateCacheExpiry( $adaptiveTTL );
1220 public function __sleep() {
1222 array_keys( get_object_vars( $this ) ),
1223 [ 'mParseStartTime' ]