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 call_user_func_array(
315 [ $skin, 'doEditSectionLink' ],
316 [ $editsectionPage, $editsectionSection,
317 $editsectionContent, $wgLang->getCode() ]
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;
747 public function addModules( $modules ) {
748 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
751 public function addModuleScripts( $modules ) {
752 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
755 public function addModuleStyles( $modules ) {
756 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
760 * Add one or more variables to be set in mw.config in JavaScript.
762 * @param string|array $keys Key or array of key/value pairs.
763 * @param mixed $value [optional] Value of the configuration variable.
766 public function addJsConfigVars( $keys, $value = null ) {
767 if ( is_array( $keys ) ) {
768 foreach ( $keys as $key => $value ) {
769 $this->mJsConfigVars
[$key] = $value;
774 $this->mJsConfigVars
[$keys] = $value;
778 * Copy items from the OutputPage object into this one
780 * @param OutputPage $out
782 public function addOutputPageMetadata( OutputPage
$out ) {
783 $this->addModules( $out->getModules() );
784 $this->addModuleScripts( $out->getModuleScripts() );
785 $this->addModuleStyles( $out->getModuleStyles() );
786 $this->addJsConfigVars( $out->getJsConfigVars() );
788 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
789 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
793 * Add a tracking category, getting the title from a system message,
794 * or print a debug message if the title is invalid.
796 * Any message used with this function should be registered so it will
797 * show up on Special:TrackingCategories. Core messages should be added
798 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
799 * should add to "TrackingCategories" in their extension.json.
801 * @todo Migrate some code to TrackingCategories
803 * @param string $msg Message key
804 * @param Title $title title of the page which is being tracked
805 * @return bool Whether the addition was successful
808 public function addTrackingCategory( $msg, $title ) {
809 if ( $title->isSpecialPage() ) {
810 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
814 // Important to parse with correct title (T33469)
815 $cat = wfMessage( $msg )
817 ->inContentLanguage()
820 # Allow tracking categories to be disabled by setting them to "-"
821 if ( $cat === '-' ) {
825 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
826 if ( $containerCategory ) {
827 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
830 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
836 * Override the title to be used for display
838 * @note this is assumed to have been validated
839 * (check equal normalisation, etc.)
841 * @note this is expected to be safe HTML,
842 * ready to be served to the client.
844 * @param string $text Desired title text
846 public function setDisplayTitle( $text ) {
847 $this->setTitleText( $text );
848 $this->setProperty( 'displaytitle', $text );
852 * Get the title to be used for display.
854 * As per the contract of setDisplayTitle(), this is safe HTML,
855 * ready to be served to the client.
857 * @return string HTML
859 public function getDisplayTitle() {
860 $t = $this->getTitleText();
868 * Fairly generic flag setter thingy.
869 * @param string $flag
871 public function setFlag( $flag ) {
872 $this->mFlags
[$flag] = true;
875 public function getFlag( $flag ) {
876 return isset( $this->mFlags
[$flag] );
880 * Set a property to be stored in the page_props database table.
882 * page_props is a key value store indexed by the page ID. This allows
883 * the parser to set a property on a page which can then be quickly
884 * retrieved given the page ID or via a DB join when given the page
887 * Since 1.23, page_props are also indexed by numeric value, to allow
888 * for efficient "top k" queries of pages wrt a given property.
890 * setProperty() is thus used to propagate properties from the parsed
891 * page to request contexts other than a page view of the currently parsed
894 * Some applications examples:
896 * * To implement hidden categories, hiding pages from category listings
897 * by storing a property.
899 * * Overriding the displayed article title.
900 * @see ParserOutput::setDisplayTitle()
902 * * To implement image tagging, for example displaying an icon on an
903 * image thumbnail to indicate that it is listed for deletion on
905 * This is not actually implemented, yet but would be pretty cool.
907 * @note Do not use setProperty() to set a property which is only used
908 * in a context where the ParserOutput object itself is already available,
909 * for example a normal page view. There is no need to save such a property
910 * in the database since the text is already parsed. You can just hook
911 * OutputPageParserOutput and get your data out of the ParserOutput object.
913 * If you are writing an extension where you want to set a property in the
914 * parser which is used by an OutputPageParserOutput hook, you have to
915 * associate the extension data directly with the ParserOutput object.
916 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
920 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
923 * And then later, in OutputPageParserOutput or similar:
927 * $output->getExtensionData( 'my_ext_foo' );
930 * In MediaWiki 1.20 and older, you have to use a custom member variable
931 * within the ParserOutput object:
935 * $parser->getOutput()->my_ext_foo = '...';
937 * @param string $name
938 * @param mixed $value
940 public function setProperty( $name, $value ) {
941 $this->mProperties
[$name] = $value;
945 * @param string $name The property name to look up.
947 * @return mixed|bool The value previously set using setProperty(). False if null or no value
948 * was set for the given property name.
950 * @note You need to use getProperties() to check for boolean and null properties.
952 public function getProperty( $name ) {
953 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
956 public function unsetProperty( $name ) {
957 unset( $this->mProperties
[$name] );
960 public function getProperties() {
961 if ( !isset( $this->mProperties
) ) {
962 $this->mProperties
= [];
964 return $this->mProperties
;
968 * Returns the options from its ParserOptions which have been taken
969 * into account to produce this output.
972 public function getUsedOptions() {
973 if ( !isset( $this->mAccessedOptions
) ) {
976 return array_keys( $this->mAccessedOptions
);
980 * Tags a parser option for use in the cache key for this parser output.
981 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
982 * The information gathered here is available via getUsedOptions(),
983 * and is used by ParserCache::save().
985 * @see ParserCache::getKey
986 * @see ParserCache::save
987 * @see ParserOptions::addExtraKey
988 * @see ParserOptions::optionsHash
989 * @param string $option
991 public function recordOption( $option ) {
992 $this->mAccessedOptions
[$option] = true;
996 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
997 * the ParserOutput object for later use during page output. The data will be cached along with
998 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1001 * This method is provided to overcome the unsafe practice of attaching extra information to a
1002 * ParserObject by directly assigning member variables.
1004 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1005 * hook in the page output, use this in the parser hook:
1009 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1012 * And then later, in OutputPageParserOutput or similar:
1016 * $output->getExtensionData( 'my_ext_foo' );
1019 * In MediaWiki 1.20 and older, you have to use a custom member variable
1020 * within the ParserOutput object:
1024 * $parser->getOutput()->my_ext_foo = '...';
1029 * @param string $key The key for accessing the data. Extensions should take care to avoid
1030 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1032 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1035 public function setExtensionData( $key, $value ) {
1036 if ( $value === null ) {
1037 unset( $this->mExtensionData
[$key] );
1039 $this->mExtensionData
[$key] = $value;
1044 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1045 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1049 * @param string $key The key to look up.
1051 * @return mixed|null The value previously set for the given key using setExtensionData()
1052 * or null if no value was set for this key.
1054 public function getExtensionData( $key ) {
1055 if ( isset( $this->mExtensionData
[$key] ) ) {
1056 return $this->mExtensionData
[$key];
1062 private static function getTimes( $clock = null ) {
1064 if ( !$clock ||
$clock === 'wall' ) {
1065 $ret['wall'] = microtime( true );
1067 if ( !$clock ||
$clock === 'cpu' ) {
1068 $ru = wfGetRusage();
1070 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1071 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1078 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1081 public function resetParseStartTime() {
1082 $this->mParseStartTime
= self
::getTimes();
1086 * Returns the time since resetParseStartTime() was last called
1088 * Clocks available are:
1089 * - wall: Wall clock time
1090 * - cpu: CPU time (requires getrusage)
1093 * @param string $clock
1094 * @return float|null
1096 public function getTimeSinceStart( $clock ) {
1097 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1101 $end = self
::getTimes( $clock );
1102 return $end[$clock] - $this->mParseStartTime
[$clock];
1106 * Sets parser limit report data for a key
1108 * The key is used as the prefix for various messages used for formatting:
1109 * - $key: The label for the field in the limit report
1110 * - $key-value-text: Message used to format the value in the "NewPP limit
1111 * report" HTML comment. If missing, uses $key-format.
1112 * - $key-value-html: Message used to format the value in the preview
1113 * limit report table. If missing, uses $key-format.
1114 * - $key-value: Message used to format the value. If missing, uses "$1".
1116 * Note that all values are interpreted as wikitext, and so should be
1117 * encoded with htmlspecialchars() as necessary, but should avoid complex
1118 * HTML for sanity of display in the "NewPP limit report" comment.
1121 * @param string $key Message key
1122 * @param mixed $value Appropriate for Message::params()
1124 public function setLimitReportData( $key, $value ) {
1125 $this->mLimitReportData
[$key] = $value;
1127 if ( is_array( $value ) ) {
1128 if ( array_keys( $value ) === [ 0, 1 ]
1129 && is_numeric( $value[0] )
1130 && is_numeric( $value[1] )
1132 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1140 if ( strpos( $key, '-' ) ) {
1141 list( $ns, $name ) = explode( '-', $key, 2 );
1142 $this->mLimitReportJSData
[$ns][$name] = $data;
1144 $this->mLimitReportJSData
[$key] = $data;
1149 * Check whether the cache TTL was lowered due to dynamic content
1151 * When content is determined by more than hard state (e.g. page edits),
1152 * such as template/file transclusions based on the current timestamp or
1153 * extension tags that generate lists based on queries, this return true.
1158 public function hasDynamicContent() {
1159 global $wgParserCacheExpireTime;
1161 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1165 * Get or set the prevent-clickjacking flag
1168 * @param bool|null $flag New flag value, or null to leave it unchanged
1169 * @return bool Old flag value
1171 public function preventClickjacking( $flag = null ) {
1172 return wfSetVar( $this->mPreventClickjacking
, $flag );
1176 * Lower the runtime adaptive TTL to at most this value
1181 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1182 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1183 $this->updateCacheExpiry( $ttl );
1187 * Call this when parsing is done to lower the TTL based on low parse times
1191 public function finalizeAdaptiveCacheExpiry() {
1192 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1196 $runtime = $this->getTimeSinceStart( 'wall' );
1197 if ( is_float( $runtime ) ) {
1198 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1199 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1200 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1201 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1204 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1205 $this->mMaxAdaptiveExpiry
1207 $this->updateCacheExpiry( $adaptiveTTL );
1211 public function __sleep() {
1213 array_keys( get_object_vars( $this ) ),
1214 [ 'mParseStartTime' ]