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 * @deprecated since 1.31 Use getText() options.
156 * @var bool $mEditSectionTokens prefix/suffix markers if edit sections were output as tokens.
158 public $mEditSectionTokens = true;
161 * @var array $mProperties Name/value pairs to be cached in the DB.
163 public $mProperties = [];
166 * @var string $mTOCHTML HTML of the TOC.
168 public $mTOCHTML = '';
171 * @var string $mTimestamp Timestamp of the revision.
176 * @deprecated since 1.31 Use getText() options.
177 * @var bool $mTOCEnabled Whether TOC should be shown, can't override __NOTOC__.
179 public $mTOCEnabled = true;
182 * @var bool $mEnableOOUI Whether OOUI should be enabled.
184 public $mEnableOOUI = false;
187 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
189 private $mIndexPolicy = '';
192 * @var array $mAccessedOptions List of ParserOptions (stored in the keys).
194 private $mAccessedOptions = [];
197 * @var array $mExtensionData extra data used by extensions.
199 private $mExtensionData = [];
202 * @var array $mLimitReportData Parser limit report data.
204 private $mLimitReportData = [];
206 /** @var array Parser limit report data for JSON */
207 private $mLimitReportJSData = [];
210 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
212 private $mParseStartTime = [];
215 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
217 private $mPreventClickjacking = false;
220 * @var array $mFlags Generic flags.
222 private $mFlags = [];
224 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
225 private $mSpeculativeRevId;
227 /** @var int Upper bound of expiry based on parse duration */
228 private $mMaxAdaptiveExpiry = INF
;
230 const EDITSECTION_REGEX
=
231 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
233 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
234 // Current values imply that m=3933.333333 and b=-333.333333
235 // See https://www.nngroup.com/articles/website-response-times/
236 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
237 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
238 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
239 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
240 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
242 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
243 $unused = false, $titletext = ''
245 $this->mText
= $text;
246 $this->mLanguageLinks
= $languageLinks;
247 $this->mCategories
= $categoryLinks;
248 $this->mTitleText
= $titletext;
252 * Get the cacheable text with <mw:editsection> markers still in it. The
253 * return value is suitable for writing back via setText() but is not valid
254 * for display to the user.
259 public function getRawText() {
264 * Get the output HTML
266 * @param array $options (since 1.31) Transformations to apply to the HTML
267 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
268 * to generate one and `__NOTOC__` wasn't used. Default is true,
269 * but might be statefully overridden.
270 * - enableSectionEditLinks: (bool) Include section edit links, assuming
271 * section edit link tokens are present in the HTML. Default is true,
272 * but might be statefully overridden.
273 * - unwrap: (bool) Remove a wrapping mw-parser-output div. Default is false.
274 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
275 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
276 * value of the attribute: all but the first will be replaced by `<link
277 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
278 * the scheme-specific-part of the href is the (percent-encoded) value
279 * of the `data-mw-deduplicate` attribute.
280 * @return string HTML
282 public function getText( $options = [] ) {
283 if ( !array_key_exists( 'allowTOC', $options ) && empty( $this->mTOCEnabled
) ) {
284 wfDeprecated( 'ParserOutput stateful allowTOC', '1.31' );
287 // Note that while $this->mEditSectionTokens formerly defaulted to false,
288 // ParserOptions->getEditSection() defaults to true and Parser copies
289 // that to us so true makes more sense as the stateless default.
290 if ( !array_key_exists( 'enableSectionEditLinks', $options ) && !$this->mEditSectionTokens
) {
291 wfDeprecated( 'ParserOutput stateful enableSectionEditLinks', '1.31' );
295 // empty() here because old cached versions might lack the field somehow.
296 // In that situation, the historical behavior (possibly buggy) is to remove the TOC.
297 'allowTOC' => !empty( $this->mTOCEnabled
),
298 'enableSectionEditLinks' => $this->mEditSectionTokens
,
300 'deduplicateStyles' => true,
302 $text = $this->mText
;
304 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
306 if ( $options['unwrap'] !== false ) {
307 $start = Html
::openElement( 'div', [
308 'class' => 'mw-parser-output'
310 $startLen = strlen( $start );
311 $end = Html
::closeElement( 'div' );
312 $endPos = strrpos( $text, $end );
313 $endLen = strlen( $end );
315 if ( substr( $text, 0, $startLen ) === $start && $endPos !== false
316 // if the closing div is followed by real content, bail out of unwrapping
317 && preg_match( '/^(?>\s*<!--.*?-->)*\s*$/s', substr( $text, $endPos +
$endLen ) )
319 $text = substr( $text, $startLen );
320 $text = substr( $text, 0, $endPos - $startLen )
321 . substr( $text, $endPos - $startLen +
$endLen );
325 if ( $options['enableSectionEditLinks'] ) {
326 $text = preg_replace_callback(
327 self
::EDITSECTION_REGEX
,
329 global $wgOut, $wgLang;
330 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
331 $editsectionSection = htmlspecialchars_decode( $m[2] );
332 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
334 if ( !is_object( $editsectionPage ) ) {
335 throw new MWException( "Bad parser output text." );
338 $skin = $wgOut->getSkin();
339 return call_user_func_array(
340 [ $skin, 'doEditSectionLink' ],
341 [ $editsectionPage, $editsectionSection,
342 $editsectionContent, $wgLang->getCode() ]
348 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
351 if ( $options['allowTOC'] ) {
352 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
354 $text = preg_replace(
355 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
361 if ( $options['deduplicateStyles'] ) {
363 $text = preg_replace_callback(
364 '#<style\s+([^>]*data-mw-deduplicate\s*=[^>]*)>.*?</style>#s',
365 function ( $m ) use ( &$seen ) {
366 $attr = Sanitizer
::decodeTagAttributes( $m[1] );
367 if ( !isset( $attr['data-mw-deduplicate'] ) ) {
371 $key = $attr['data-mw-deduplicate'];
372 if ( !isset( $seen[$key] ) ) {
377 // We were going to use an empty <style> here, but there
378 // was concern that would be too much overhead for browsers.
379 // So let's hope a <link> with a non-standard rel and href isn't
380 // going to be misinterpreted or mangled by any subsequent processing.
381 return Html
::element( 'link', [
382 'rel' => 'mw-deduplicated-inline-style',
383 'href' => "mw-data:" . wfUrlencode( $key ),
397 public function setSpeculativeRevIdUsed( $id ) {
398 $this->mSpeculativeRevId
= $id;
405 public function getSpeculativeRevIdUsed() {
406 return $this->mSpeculativeRevId
;
409 public function &getLanguageLinks() {
410 return $this->mLanguageLinks
;
413 public function getInterwikiLinks() {
414 return $this->mInterwikiLinks
;
417 public function getCategoryLinks() {
418 return array_keys( $this->mCategories
);
421 public function &getCategories() {
422 return $this->mCategories
;
429 public function getIndicators() {
430 return $this->mIndicators
;
433 public function getTitleText() {
434 return $this->mTitleText
;
437 public function getSections() {
438 return $this->mSections
;
442 * @deprecated since 1.31 Use getText() options.
444 public function getEditSectionTokens() {
445 return $this->mEditSectionTokens
;
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 return $this->mTOCEnabled
;
538 public function getEnableOOUI() {
539 return $this->mEnableOOUI
;
542 public function setText( $text ) {
543 return wfSetVar( $this->mText
, $text );
546 public function setLanguageLinks( $ll ) {
547 return wfSetVar( $this->mLanguageLinks
, $ll );
550 public function setCategoryLinks( $cl ) {
551 return wfSetVar( $this->mCategories
, $cl );
554 public function setTitleText( $t ) {
555 return wfSetVar( $this->mTitleText
, $t );
558 public function setSections( $toc ) {
559 return wfSetVar( $this->mSections
, $toc );
563 * @deprecated since 1.31 Use getText() options.
565 public function setEditSectionTokens( $t ) {
566 return wfSetVar( $this->mEditSectionTokens
, $t );
569 public function setIndexPolicy( $policy ) {
570 return wfSetVar( $this->mIndexPolicy
, $policy );
573 public function setTOCHTML( $tochtml ) {
574 return wfSetVar( $this->mTOCHTML
, $tochtml );
577 public function setTimestamp( $timestamp ) {
578 return wfSetVar( $this->mTimestamp
, $timestamp );
582 * @deprecated since 1.31 Use getText() options.
584 public function setTOCEnabled( $flag ) {
585 return wfSetVar( $this->mTOCEnabled
, $flag );
588 public function addCategory( $c, $sort ) {
589 $this->mCategories
[$c] = $sort;
594 * @param string $content
597 public function setIndicator( $id, $content ) {
598 $this->mIndicators
[$id] = $content;
602 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
603 * object is added to.
606 * @param bool $enable If OOUI should be enabled or not
608 public function setEnableOOUI( $enable = false ) {
609 $this->mEnableOOUI
= $enable;
612 public function addLanguageLink( $t ) {
613 $this->mLanguageLinks
[] = $t;
616 public function addWarning( $s ) {
617 $this->mWarnings
[$s] = 1;
620 public function addOutputHook( $hook, $data = false ) {
621 $this->mOutputHooks
[] = [ $hook, $data ];
624 public function setNewSection( $value ) {
625 $this->mNewSection
= (bool)$value;
627 public function hideNewSection( $value ) {
628 $this->mHideNewSection
= (bool)$value;
630 public function getHideNewSection() {
631 return (bool)$this->mHideNewSection
;
633 public function getNewSection() {
634 return (bool)$this->mNewSection
;
638 * Checks, if a url is pointing to the own server
640 * @param string $internal The server to check against
641 * @param string $url The url to check
644 public static function isLinkInternal( $internal, $url ) {
645 return (bool)preg_match( '/^' .
646 # If server is proto relative, check also for http/https links
647 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
648 preg_quote( $internal, '/' ) .
649 # check for query/path/anchor or end of link in each case
655 public function addExternalLink( $url ) {
656 # We don't register links pointing to our own server, unless... :-)
657 global $wgServer, $wgRegisterInternalExternals;
659 # Replace unnecessary URL escape codes with the referenced character
660 # This prevents spammers from hiding links from the filters
661 $url = Parser
::normalizeLinkUrl( $url );
663 $registerExternalLink = true;
664 if ( !$wgRegisterInternalExternals ) {
665 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
667 if ( $registerExternalLink ) {
668 $this->mExternalLinks
[$url] = 1;
673 * Record a local or interwiki inline link for saving in future link tables.
675 * @param Title $title
676 * @param int|null $id Optional known page_id so we can skip the lookup
678 public function addLink( Title
$title, $id = null ) {
679 if ( $title->isExternal() ) {
680 // Don't record interwikis in pagelinks
681 $this->addInterwikiLink( $title );
684 $ns = $title->getNamespace();
685 $dbk = $title->getDBkey();
686 if ( $ns == NS_MEDIA
) {
687 // Normalize this pseudo-alias if it makes it down here...
689 } elseif ( $ns == NS_SPECIAL
) {
690 // We don't record Special: links currently
691 // It might actually be wise to, but we'd need to do some normalization.
693 } elseif ( $dbk === '' ) {
694 // Don't record self links - [[#Foo]]
697 if ( !isset( $this->mLinks
[$ns] ) ) {
698 $this->mLinks
[$ns] = [];
700 if ( is_null( $id ) ) {
701 $id = $title->getArticleID();
703 $this->mLinks
[$ns][$dbk] = $id;
707 * Register a file dependency for this output
708 * @param string $name Title dbKey
709 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
710 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
713 public function addImage( $name, $timestamp = null, $sha1 = null ) {
714 $this->mImages
[$name] = 1;
715 if ( $timestamp !== null && $sha1 !== null ) {
716 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
721 * Register a template dependency for this output
722 * @param Title $title
723 * @param int $page_id
727 public function addTemplate( $title, $page_id, $rev_id ) {
728 $ns = $title->getNamespace();
729 $dbk = $title->getDBkey();
730 if ( !isset( $this->mTemplates
[$ns] ) ) {
731 $this->mTemplates
[$ns] = [];
733 $this->mTemplates
[$ns][$dbk] = $page_id;
734 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
735 $this->mTemplateIds
[$ns] = [];
737 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
741 * @param Title $title Title object, must be an interwiki link
742 * @throws MWException If given invalid input
744 public function addInterwikiLink( $title ) {
745 if ( !$title->isExternal() ) {
746 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
748 $prefix = $title->getInterwiki();
749 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
750 $this->mInterwikiLinks
[$prefix] = [];
752 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
756 * Add some text to the "<head>".
757 * If $tag is set, the section with that tag will only be included once
759 * @param string $section
760 * @param string|bool $tag
762 public function addHeadItem( $section, $tag = false ) {
763 if ( $tag !== false ) {
764 $this->mHeadItems
[$tag] = $section;
766 $this->mHeadItems
[] = $section;
770 public function addModules( $modules ) {
771 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
774 public function addModuleScripts( $modules ) {
775 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
778 public function addModuleStyles( $modules ) {
779 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
783 * Add one or more variables to be set in mw.config in JavaScript.
785 * @param string|array $keys Key or array of key/value pairs.
786 * @param mixed $value [optional] Value of the configuration variable.
789 public function addJsConfigVars( $keys, $value = null ) {
790 if ( is_array( $keys ) ) {
791 foreach ( $keys as $key => $value ) {
792 $this->mJsConfigVars
[$key] = $value;
797 $this->mJsConfigVars
[$keys] = $value;
801 * Copy items from the OutputPage object into this one
803 * @param OutputPage $out
805 public function addOutputPageMetadata( OutputPage
$out ) {
806 $this->addModules( $out->getModules() );
807 $this->addModuleScripts( $out->getModuleScripts() );
808 $this->addModuleStyles( $out->getModuleStyles() );
809 $this->addJsConfigVars( $out->getJsConfigVars() );
811 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
812 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
816 * Add a tracking category, getting the title from a system message,
817 * or print a debug message if the title is invalid.
819 * Any message used with this function should be registered so it will
820 * show up on Special:TrackingCategories. Core messages should be added
821 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
822 * should add to "TrackingCategories" in their extension.json.
824 * @todo Migrate some code to TrackingCategories
826 * @param string $msg Message key
827 * @param Title $title title of the page which is being tracked
828 * @return bool Whether the addition was successful
831 public function addTrackingCategory( $msg, $title ) {
832 if ( $title->isSpecialPage() ) {
833 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
837 // Important to parse with correct title (T33469)
838 $cat = wfMessage( $msg )
840 ->inContentLanguage()
843 # Allow tracking categories to be disabled by setting them to "-"
844 if ( $cat === '-' ) {
848 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
849 if ( $containerCategory ) {
850 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
853 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
859 * Override the title to be used for display
861 * @note this is assumed to have been validated
862 * (check equal normalisation, etc.)
864 * @note this is expected to be safe HTML,
865 * ready to be served to the client.
867 * @param string $text Desired title text
869 public function setDisplayTitle( $text ) {
870 $this->setTitleText( $text );
871 $this->setProperty( 'displaytitle', $text );
875 * Get the title to be used for display.
877 * As per the contract of setDisplayTitle(), this is safe HTML,
878 * ready to be served to the client.
880 * @return string HTML
882 public function getDisplayTitle() {
883 $t = $this->getTitleText();
891 * Fairly generic flag setter thingy.
892 * @param string $flag
894 public function setFlag( $flag ) {
895 $this->mFlags
[$flag] = true;
898 public function getFlag( $flag ) {
899 return isset( $this->mFlags
[$flag] );
903 * Set a property to be stored in the page_props database table.
905 * page_props is a key value store indexed by the page ID. This allows
906 * the parser to set a property on a page which can then be quickly
907 * retrieved given the page ID or via a DB join when given the page
910 * Since 1.23, page_props are also indexed by numeric value, to allow
911 * for efficient "top k" queries of pages wrt a given property.
913 * setProperty() is thus used to propagate properties from the parsed
914 * page to request contexts other than a page view of the currently parsed
917 * Some applications examples:
919 * * To implement hidden categories, hiding pages from category listings
920 * by storing a property.
922 * * Overriding the displayed article title.
923 * @see ParserOutput::setDisplayTitle()
925 * * To implement image tagging, for example displaying an icon on an
926 * image thumbnail to indicate that it is listed for deletion on
928 * This is not actually implemented, yet but would be pretty cool.
930 * @note Do not use setProperty() to set a property which is only used
931 * in a context where the ParserOutput object itself is already available,
932 * for example a normal page view. There is no need to save such a property
933 * in the database since the text is already parsed. You can just hook
934 * OutputPageParserOutput and get your data out of the ParserOutput object.
936 * If you are writing an extension where you want to set a property in the
937 * parser which is used by an OutputPageParserOutput hook, you have to
938 * associate the extension data directly with the ParserOutput object.
939 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
943 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
946 * And then later, in OutputPageParserOutput or similar:
950 * $output->getExtensionData( 'my_ext_foo' );
953 * In MediaWiki 1.20 and older, you have to use a custom member variable
954 * within the ParserOutput object:
958 * $parser->getOutput()->my_ext_foo = '...';
960 * @param string $name
961 * @param mixed $value
963 public function setProperty( $name, $value ) {
964 $this->mProperties
[$name] = $value;
968 * @param string $name The property name to look up.
970 * @return mixed|bool The value previously set using setProperty(). False if null or no value
971 * was set for the given property name.
973 * @note You need to use getProperties() to check for boolean and null properties.
975 public function getProperty( $name ) {
976 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
979 public function unsetProperty( $name ) {
980 unset( $this->mProperties
[$name] );
983 public function getProperties() {
984 if ( !isset( $this->mProperties
) ) {
985 $this->mProperties
= [];
987 return $this->mProperties
;
991 * Returns the options from its ParserOptions which have been taken
992 * into account to produce this output or false if not available.
995 public function getUsedOptions() {
996 if ( !isset( $this->mAccessedOptions
) ) {
999 return array_keys( $this->mAccessedOptions
);
1003 * Tags a parser option for use in the cache key for this parser output.
1004 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
1005 * The information gathered here is available via getUsedOptions(),
1006 * and is used by ParserCache::save().
1008 * @see ParserCache::getKey
1009 * @see ParserCache::save
1010 * @see ParserOptions::addExtraKey
1011 * @see ParserOptions::optionsHash
1012 * @param string $option
1014 public function recordOption( $option ) {
1015 $this->mAccessedOptions
[$option] = true;
1019 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
1020 * the ParserOutput object for later use during page output. The data will be cached along with
1021 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1024 * This method is provided to overcome the unsafe practice of attaching extra information to a
1025 * ParserObject by directly assigning member variables.
1027 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1028 * hook in the page output, use this in the parser hook:
1032 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1035 * And then later, in OutputPageParserOutput or similar:
1039 * $output->getExtensionData( 'my_ext_foo' );
1042 * In MediaWiki 1.20 and older, you have to use a custom member variable
1043 * within the ParserOutput object:
1047 * $parser->getOutput()->my_ext_foo = '...';
1052 * @param string $key The key for accessing the data. Extensions should take care to avoid
1053 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1055 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1058 public function setExtensionData( $key, $value ) {
1059 if ( $value === null ) {
1060 unset( $this->mExtensionData
[$key] );
1062 $this->mExtensionData
[$key] = $value;
1067 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1068 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1072 * @param string $key The key to look up.
1074 * @return mixed|null The value previously set for the given key using setExtensionData()
1075 * or null if no value was set for this key.
1077 public function getExtensionData( $key ) {
1078 if ( isset( $this->mExtensionData
[$key] ) ) {
1079 return $this->mExtensionData
[$key];
1085 private static function getTimes( $clock = null ) {
1087 if ( !$clock ||
$clock === 'wall' ) {
1088 $ret['wall'] = microtime( true );
1090 if ( !$clock ||
$clock === 'cpu' ) {
1091 $ru = wfGetRusage();
1093 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1094 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1101 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1104 public function resetParseStartTime() {
1105 $this->mParseStartTime
= self
::getTimes();
1109 * Returns the time since resetParseStartTime() was last called
1111 * Clocks available are:
1112 * - wall: Wall clock time
1113 * - cpu: CPU time (requires getrusage)
1116 * @param string $clock
1117 * @return float|null
1119 public function getTimeSinceStart( $clock ) {
1120 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1124 $end = self
::getTimes( $clock );
1125 return $end[$clock] - $this->mParseStartTime
[$clock];
1129 * Sets parser limit report data for a key
1131 * The key is used as the prefix for various messages used for formatting:
1132 * - $key: The label for the field in the limit report
1133 * - $key-value-text: Message used to format the value in the "NewPP limit
1134 * report" HTML comment. If missing, uses $key-format.
1135 * - $key-value-html: Message used to format the value in the preview
1136 * limit report table. If missing, uses $key-format.
1137 * - $key-value: Message used to format the value. If missing, uses "$1".
1139 * Note that all values are interpreted as wikitext, and so should be
1140 * encoded with htmlspecialchars() as necessary, but should avoid complex
1141 * HTML for sanity of display in the "NewPP limit report" comment.
1144 * @param string $key Message key
1145 * @param mixed $value Appropriate for Message::params()
1147 public function setLimitReportData( $key, $value ) {
1148 $this->mLimitReportData
[$key] = $value;
1150 if ( is_array( $value ) ) {
1151 if ( array_keys( $value ) === [ 0, 1 ]
1152 && is_numeric( $value[0] )
1153 && is_numeric( $value[1] )
1155 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1163 if ( strpos( $key, '-' ) ) {
1164 list( $ns, $name ) = explode( '-', $key, 2 );
1165 $this->mLimitReportJSData
[$ns][$name] = $data;
1167 $this->mLimitReportJSData
[$key] = $data;
1172 * Check whether the cache TTL was lowered due to dynamic content
1174 * When content is determined by more than hard state (e.g. page edits),
1175 * such as template/file transclusions based on the current timestamp or
1176 * extension tags that generate lists based on queries, this return true.
1181 public function hasDynamicContent() {
1182 global $wgParserCacheExpireTime;
1184 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1188 * Get or set the prevent-clickjacking flag
1191 * @param bool|null $flag New flag value, or null to leave it unchanged
1192 * @return bool Old flag value
1194 public function preventClickjacking( $flag = null ) {
1195 return wfSetVar( $this->mPreventClickjacking
, $flag );
1199 * Lower the runtime adaptive TTL to at most this value
1204 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1205 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1206 $this->updateCacheExpiry( $ttl );
1210 * Call this when parsing is done to lower the TTL based on low parse times
1214 public function finalizeAdaptiveCacheExpiry() {
1215 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1219 $runtime = $this->getTimeSinceStart( 'wall' );
1220 if ( is_float( $runtime ) ) {
1221 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1222 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1223 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1224 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1227 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1228 $this->mMaxAdaptiveExpiry
1230 $this->updateCacheExpiry( $adaptiveTTL );
1234 public function __sleep() {
1236 array_keys( get_object_vars( $this ) ),
1237 [ 'mParseStartTime' ]