4 * Output of the PHP parser.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 class ParserOutput
extends CacheTime
{
27 * Feature flags to indicate to extensions that MediaWiki core supports and
28 * uses getText() stateless transforms.
30 const SUPPORTS_STATELESS_TRANSFORMS
= 1;
31 const SUPPORTS_UNWRAP_TRANSFORM
= 1;
34 * @var string $mText The output text
39 * @var array $mLanguageLinks List of the full text of language links,
40 * in the order they appear.
42 public $mLanguageLinks;
45 * @var array $mCategoriesMap of category names to sort keys
50 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
52 public $mIndicators = [];
55 * @var string $mTitleText Title text of the chosen language variant, as HTML.
60 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
66 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
69 public $mTemplates = [];
72 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
75 public $mTemplateIds = [];
78 * @var array $mImages DB keys of the images used, in the array key only
83 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
85 public $mFileSearchOptions = [];
88 * @var array $mExternalLinks External link URLs, in the key only.
90 public $mExternalLinks = [];
93 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
94 * for the inline interwiki links in the document.
96 public $mInterwikiLinks = [];
99 * @var bool $mNewSection Show a new section link?
101 public $mNewSection = false;
104 * @var bool $mHideNewSection Hide the new section link?
106 public $mHideNewSection = false;
109 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
111 public $mNoGallery = false;
114 * @var array $mHeadItems Items to put in the <head> section
116 public $mHeadItems = [];
119 * @var array $mModules Modules to be loaded by ResourceLoader
121 public $mModules = [];
124 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
126 public $mModuleScripts = [];
129 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
131 public $mModuleStyles = [];
134 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
136 public $mJsConfigVars = [];
139 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
141 public $mOutputHooks = [];
144 * @var array $mWarnings Warning text to be returned to the user.
145 * Wikitext formatted, in the key only.
147 public $mWarnings = [];
150 * @var array $mSections Table of contents
152 public $mSections = [];
155 * @var array $mProperties Name/value pairs to be cached in the DB.
157 public $mProperties = [];
160 * @var string $mTOCHTML HTML of the TOC.
162 public $mTOCHTML = '';
165 * @var string $mTimestamp Timestamp of the revision.
170 * @var bool $mEnableOOUI Whether OOUI should be enabled.
172 public $mEnableOOUI = false;
175 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
177 private $mIndexPolicy = '';
180 * @var true[] $mAccessedOptions List of ParserOptions (stored in the keys).
182 private $mAccessedOptions = [];
185 * @var array $mExtensionData extra data used by extensions.
187 private $mExtensionData = [];
190 * @var array $mLimitReportData Parser limit report data.
192 private $mLimitReportData = [];
194 /** @var array Parser limit report data for JSON */
195 private $mLimitReportJSData = [];
198 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
200 private $mParseStartTime = [];
203 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
205 private $mPreventClickjacking = false;
208 * @var array $mFlags Generic flags.
210 private $mFlags = [];
212 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
213 private $mSpeculativeRevId;
215 /** string CSS classes to use for the wrapping div, stored in the array keys.
216 * If no class is given, no wrapper is added.
218 private $mWrapperDivClasses = [];
220 /** @var int Upper bound of expiry based on parse duration */
221 private $mMaxAdaptiveExpiry = INF
;
223 const EDITSECTION_REGEX
=
224 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
226 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
227 // Current values imply that m=3933.333333 and b=-333.333333
228 // See https://www.nngroup.com/articles/website-response-times/
229 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
230 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
231 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
232 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
233 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
235 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
236 $unused = false, $titletext = ''
238 $this->mText
= $text;
239 $this->mLanguageLinks
= $languageLinks;
240 $this->mCategories
= $categoryLinks;
241 $this->mTitleText
= $titletext;
245 * Get the cacheable text with <mw:editsection> markers still in it. The
246 * return value is suitable for writing back via setText() but is not valid
247 * for display to the user.
252 public function getRawText() {
257 * Get the output HTML
259 * @param array $options (since 1.31) Transformations to apply to the HTML
260 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
261 * to generate one and `__NOTOC__` wasn't used. Default is true,
262 * but might be statefully overridden.
263 * - enableSectionEditLinks: (bool) Include section edit links, assuming
264 * section edit link tokens are present in the HTML. Default is true,
265 * but might be statefully overridden.
266 * - unwrap: (bool) Return text without a wrapper div. Default is false,
267 * meaning a wrapper div will be added if getWrapperDivClass() returns
268 * a non-empty string.
269 * - wrapperDivClass: (string) Wrap the output in a div and apply the given
270 * CSS class to that div. This overrides the output of getWrapperDivClass().
271 * Setting this to an empty string has the same effect as 'unwrap' => true.
272 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
273 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
274 * value of the attribute: all but the first will be replaced by `<link
275 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
276 * the scheme-specific-part of the href is the (percent-encoded) value
277 * of the `data-mw-deduplicate` attribute.
278 * @return string HTML
280 public function getText( $options = [] ) {
283 'enableSectionEditLinks' => true,
285 'deduplicateStyles' => true,
286 'wrapperDivClass' => $this->getWrapperDivClass(),
288 $text = $this->mText
;
290 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
292 if ( $options['wrapperDivClass'] !== '' && !$options['unwrap'] ) {
293 $text = Html
::rawElement( 'div', [ 'class' => $options['wrapperDivClass'] ], $text );
296 if ( $options['enableSectionEditLinks'] ) {
297 $text = preg_replace_callback(
298 self
::EDITSECTION_REGEX
,
300 global $wgOut, $wgLang;
301 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
302 $editsectionSection = htmlspecialchars_decode( $m[2] );
303 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
305 if ( !is_object( $editsectionPage ) ) {
306 throw new MWException( "Bad parser output text." );
309 $skin = $wgOut->getSkin();
310 return $skin->doEditSectionLink( $editsectionPage,
319 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
322 if ( $options['allowTOC'] ) {
323 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
325 $text = preg_replace(
326 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
332 if ( $options['deduplicateStyles'] ) {
334 $text = preg_replace_callback(
335 '#<style\s+([^>]*data-mw-deduplicate\s*=[^>]*)>.*?</style>#s',
336 function ( $m ) use ( &$seen ) {
337 $attr = Sanitizer
::decodeTagAttributes( $m[1] );
338 if ( !isset( $attr['data-mw-deduplicate'] ) ) {
342 $key = $attr['data-mw-deduplicate'];
343 if ( !isset( $seen[$key] ) ) {
348 // We were going to use an empty <style> here, but there
349 // was concern that would be too much overhead for browsers.
350 // So let's hope a <link> with a non-standard rel and href isn't
351 // going to be misinterpreted or mangled by any subsequent processing.
352 return Html
::element( 'link', [
353 'rel' => 'mw-deduplicated-inline-style',
354 'href' => "mw-data:" . wfUrlencode( $key ),
361 // Hydrate slot section header placeholders generated by RevisionRenderer.
362 $text = preg_replace_callback(
363 '#<mw:slotheader>(.*?)</mw:slotheader>#',
365 $role = htmlspecialchars_decode( $m[1] );
366 // TODO: map to message, using the interface language. Set lang="xyz" accordingly.
376 * Add a CSS class to use for the wrapping div. If no class is given, no wrapper is added.
378 * @param string $class
380 public function addWrapperDivClass( $class ) {
381 $this->mWrapperDivClasses
[$class] = true;
385 * Clears the CSS class to use for the wrapping div, effectively disabling the wrapper div
386 * until addWrapperDivClass() is called.
388 public function clearWrapperDivClass() {
389 $this->mWrapperDivClasses
= [];
393 * Returns the class (or classes) to be used with the wrapper div for this otuput.
394 * If there is no wrapper class given, no wrapper div should be added.
395 * The wrapper div is added automatically by getText().
399 public function getWrapperDivClass() {
400 return implode( ' ', array_keys( $this->mWrapperDivClasses
) );
407 public function setSpeculativeRevIdUsed( $id ) {
408 $this->mSpeculativeRevId
= $id;
415 public function getSpeculativeRevIdUsed() {
416 return $this->mSpeculativeRevId
;
419 public function &getLanguageLinks() {
420 return $this->mLanguageLinks
;
423 public function getInterwikiLinks() {
424 return $this->mInterwikiLinks
;
427 public function getCategoryLinks() {
428 return array_keys( $this->mCategories
);
431 public function &getCategories() {
432 return $this->mCategories
;
439 public function getIndicators() {
440 return $this->mIndicators
;
443 public function getTitleText() {
444 return $this->mTitleText
;
447 public function getSections() {
448 return $this->mSections
;
452 * @deprecated since 1.31 Use getText() options.
454 public function getEditSectionTokens() {
455 wfDeprecated( __METHOD__
, '1.31' );
459 public function &getLinks() {
460 return $this->mLinks
;
463 public function &getTemplates() {
464 return $this->mTemplates
;
467 public function &getTemplateIds() {
468 return $this->mTemplateIds
;
471 public function &getImages() {
472 return $this->mImages
;
475 public function &getFileSearchOptions() {
476 return $this->mFileSearchOptions
;
479 public function &getExternalLinks() {
480 return $this->mExternalLinks
;
483 public function setNoGallery( $value ) {
484 $this->mNoGallery
= (bool)$value;
486 public function getNoGallery() {
487 return $this->mNoGallery
;
490 public function getHeadItems() {
491 return $this->mHeadItems
;
494 public function getModules() {
495 return $this->mModules
;
498 public function getModuleScripts() {
499 return $this->mModuleScripts
;
502 public function getModuleStyles() {
503 return $this->mModuleStyles
;
510 public function getJsConfigVars() {
511 return $this->mJsConfigVars
;
514 public function getOutputHooks() {
515 return (array)$this->mOutputHooks
;
518 public function getWarnings() {
519 return array_keys( $this->mWarnings
);
522 public function getIndexPolicy() {
523 return $this->mIndexPolicy
;
526 public function getTOCHTML() {
527 return $this->mTOCHTML
;
531 * @return string|null TS_MW timestamp of the revision content
533 public function getTimestamp() {
534 return $this->mTimestamp
;
537 public function getLimitReportData() {
538 return $this->mLimitReportData
;
541 public function getLimitReportJSData() {
542 return $this->mLimitReportJSData
;
546 * @deprecated since 1.31 Use getText() options.
548 public function getTOCEnabled() {
549 wfDeprecated( __METHOD__
, '1.31' );
553 public function getEnableOOUI() {
554 return $this->mEnableOOUI
;
557 public function setText( $text ) {
558 return wfSetVar( $this->mText
, $text );
561 public function setLanguageLinks( $ll ) {
562 return wfSetVar( $this->mLanguageLinks
, $ll );
565 public function setCategoryLinks( $cl ) {
566 return wfSetVar( $this->mCategories
, $cl );
569 public function setTitleText( $t ) {
570 return wfSetVar( $this->mTitleText
, $t );
573 public function setSections( $toc ) {
574 return wfSetVar( $this->mSections
, $toc );
578 * @deprecated since 1.31 Use getText() options.
580 public function setEditSectionTokens( $t ) {
581 wfDeprecated( __METHOD__
, '1.31' );
585 public function setIndexPolicy( $policy ) {
586 return wfSetVar( $this->mIndexPolicy
, $policy );
589 public function setTOCHTML( $tochtml ) {
590 return wfSetVar( $this->mTOCHTML
, $tochtml );
593 public function setTimestamp( $timestamp ) {
594 return wfSetVar( $this->mTimestamp
, $timestamp );
598 * @deprecated since 1.31 Use getText() options.
600 public function setTOCEnabled( $flag ) {
601 wfDeprecated( __METHOD__
, '1.31' );
605 public function addCategory( $c, $sort ) {
606 $this->mCategories
[$c] = $sort;
611 * @param string $content
614 public function setIndicator( $id, $content ) {
615 $this->mIndicators
[$id] = $content;
619 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
620 * object is added to.
623 * @param bool $enable If OOUI should be enabled or not
625 public function setEnableOOUI( $enable = false ) {
626 $this->mEnableOOUI
= $enable;
629 public function addLanguageLink( $t ) {
630 $this->mLanguageLinks
[] = $t;
633 public function addWarning( $s ) {
634 $this->mWarnings
[$s] = 1;
637 public function addOutputHook( $hook, $data = false ) {
638 $this->mOutputHooks
[] = [ $hook, $data ];
641 public function setNewSection( $value ) {
642 $this->mNewSection
= (bool)$value;
644 public function hideNewSection( $value ) {
645 $this->mHideNewSection
= (bool)$value;
647 public function getHideNewSection() {
648 return (bool)$this->mHideNewSection
;
650 public function getNewSection() {
651 return (bool)$this->mNewSection
;
655 * Checks, if a url is pointing to the own server
657 * @param string $internal The server to check against
658 * @param string $url The url to check
661 public static function isLinkInternal( $internal, $url ) {
662 return (bool)preg_match( '/^' .
663 # If server is proto relative, check also for http/https links
664 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
665 preg_quote( $internal, '/' ) .
666 # check for query/path/anchor or end of link in each case
672 public function addExternalLink( $url ) {
673 # We don't register links pointing to our own server, unless... :-)
674 global $wgServer, $wgRegisterInternalExternals;
676 # Replace unnecessary URL escape codes with the referenced character
677 # This prevents spammers from hiding links from the filters
678 $url = Parser
::normalizeLinkUrl( $url );
680 $registerExternalLink = true;
681 if ( !$wgRegisterInternalExternals ) {
682 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
684 if ( $registerExternalLink ) {
685 $this->mExternalLinks
[$url] = 1;
690 * Record a local or interwiki inline link for saving in future link tables.
692 * @param Title $title
693 * @param int|null $id Optional known page_id so we can skip the lookup
695 public function addLink( Title
$title, $id = null ) {
696 if ( $title->isExternal() ) {
697 // Don't record interwikis in pagelinks
698 $this->addInterwikiLink( $title );
701 $ns = $title->getNamespace();
702 $dbk = $title->getDBkey();
703 if ( $ns == NS_MEDIA
) {
704 // Normalize this pseudo-alias if it makes it down here...
706 } elseif ( $ns == NS_SPECIAL
) {
707 // We don't record Special: links currently
708 // It might actually be wise to, but we'd need to do some normalization.
710 } elseif ( $dbk === '' ) {
711 // Don't record self links - [[#Foo]]
714 if ( !isset( $this->mLinks
[$ns] ) ) {
715 $this->mLinks
[$ns] = [];
717 if ( is_null( $id ) ) {
718 $id = $title->getArticleID();
720 $this->mLinks
[$ns][$dbk] = $id;
724 * Register a file dependency for this output
725 * @param string $name Title dbKey
726 * @param string|false|null $timestamp MW timestamp of file creation (or false if non-existing)
727 * @param string|false|null $sha1 Base 36 SHA-1 of file (or false if non-existing)
729 public function addImage( $name, $timestamp = null, $sha1 = null ) {
730 $this->mImages
[$name] = 1;
731 if ( $timestamp !== null && $sha1 !== null ) {
732 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
737 * Register a template dependency for this output
738 * @param Title $title
739 * @param int $page_id
742 public function addTemplate( $title, $page_id, $rev_id ) {
743 $ns = $title->getNamespace();
744 $dbk = $title->getDBkey();
745 if ( !isset( $this->mTemplates
[$ns] ) ) {
746 $this->mTemplates
[$ns] = [];
748 $this->mTemplates
[$ns][$dbk] = $page_id;
749 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
750 $this->mTemplateIds
[$ns] = [];
752 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
756 * @param Title $title Title object, must be an interwiki link
757 * @throws MWException If given invalid input
759 public function addInterwikiLink( $title ) {
760 if ( !$title->isExternal() ) {
761 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
763 $prefix = $title->getInterwiki();
764 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
765 $this->mInterwikiLinks
[$prefix] = [];
767 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
771 * Add some text to the "<head>".
772 * If $tag is set, the section with that tag will only be included once
774 * @param string $section
775 * @param string|bool $tag
777 public function addHeadItem( $section, $tag = false ) {
778 if ( $tag !== false ) {
779 $this->mHeadItems
[$tag] = $section;
781 $this->mHeadItems
[] = $section;
786 * @see OutputPage::addModules
788 public function addModules( $modules ) {
789 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
793 * @deprecated since 1.31 Use addModules() instead.
794 * @see OutputPage::addModuleScripts
796 public function addModuleScripts( $modules ) {
797 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
801 * @see OutputPage::addModuleStyles
803 public function addModuleStyles( $modules ) {
804 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
808 * Add one or more variables to be set in mw.config in JavaScript.
810 * @param string|array $keys Key or array of key/value pairs.
811 * @param mixed|null $value [optional] Value of the configuration variable.
814 public function addJsConfigVars( $keys, $value = null ) {
815 if ( is_array( $keys ) ) {
816 foreach ( $keys as $key => $value ) {
817 $this->mJsConfigVars
[$key] = $value;
822 $this->mJsConfigVars
[$keys] = $value;
826 * Copy items from the OutputPage object into this one
828 * @param OutputPage $out
830 public function addOutputPageMetadata( OutputPage
$out ) {
831 $this->addModules( $out->getModules() );
832 $this->addModuleScripts( $out->getModuleScripts() );
833 $this->addModuleStyles( $out->getModuleStyles() );
834 $this->addJsConfigVars( $out->getJsConfigVars() );
836 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
837 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
841 * Add a tracking category, getting the title from a system message,
842 * or print a debug message if the title is invalid.
844 * Any message used with this function should be registered so it will
845 * show up on Special:TrackingCategories. Core messages should be added
846 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
847 * should add to "TrackingCategories" in their extension.json.
849 * @todo Migrate some code to TrackingCategories
851 * @param string $msg Message key
852 * @param Title $title title of the page which is being tracked
853 * @return bool Whether the addition was successful
856 public function addTrackingCategory( $msg, $title ) {
857 if ( $title->isSpecialPage() ) {
858 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
862 // Important to parse with correct title (T33469)
863 $cat = wfMessage( $msg )
865 ->inContentLanguage()
868 # Allow tracking categories to be disabled by setting them to "-"
869 if ( $cat === '-' ) {
873 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
874 if ( $containerCategory ) {
875 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
878 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
884 * Override the title to be used for display
886 * @note this is assumed to have been validated
887 * (check equal normalisation, etc.)
889 * @note this is expected to be safe HTML,
890 * ready to be served to the client.
892 * @param string $text Desired title text
894 public function setDisplayTitle( $text ) {
895 $this->setTitleText( $text );
896 $this->setProperty( 'displaytitle', $text );
900 * Get the title to be used for display.
902 * As per the contract of setDisplayTitle(), this is safe HTML,
903 * ready to be served to the client.
905 * @return string HTML
907 public function getDisplayTitle() {
908 $t = $this->getTitleText();
916 * Fairly generic flag setter thingy.
917 * @param string $flag
919 public function setFlag( $flag ) {
920 $this->mFlags
[$flag] = true;
923 public function getFlag( $flag ) {
924 return isset( $this->mFlags
[$flag] );
928 * Set a property to be stored in the page_props database table.
930 * page_props is a key value store indexed by the page ID. This allows
931 * the parser to set a property on a page which can then be quickly
932 * retrieved given the page ID or via a DB join when given the page
935 * Since 1.23, page_props are also indexed by numeric value, to allow
936 * for efficient "top k" queries of pages wrt a given property.
938 * setProperty() is thus used to propagate properties from the parsed
939 * page to request contexts other than a page view of the currently parsed
942 * Some applications examples:
944 * * To implement hidden categories, hiding pages from category listings
945 * by storing a property.
947 * * Overriding the displayed article title (ParserOutput::setDisplayTitle()).
949 * * To implement image tagging, for example displaying an icon on an
950 * image thumbnail to indicate that it is listed for deletion on
952 * This is not actually implemented, yet but would be pretty cool.
954 * @note Do not use setProperty() to set a property which is only used
955 * in a context where the ParserOutput object itself is already available,
956 * for example a normal page view. There is no need to save such a property
957 * in the database since the text is already parsed. You can just hook
958 * OutputPageParserOutput and get your data out of the ParserOutput object.
960 * If you are writing an extension where you want to set a property in the
961 * parser which is used by an OutputPageParserOutput hook, you have to
962 * associate the extension data directly with the ParserOutput object.
963 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
967 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
970 * And then later, in OutputPageParserOutput or similar:
974 * $output->getExtensionData( 'my_ext_foo' );
977 * In MediaWiki 1.20 and older, you have to use a custom member variable
978 * within the ParserOutput object:
982 * $parser->getOutput()->my_ext_foo = '...';
984 * @param string $name
985 * @param mixed $value
987 public function setProperty( $name, $value ) {
988 $this->mProperties
[$name] = $value;
992 * @param string $name The property name to look up.
994 * @return mixed|bool The value previously set using setProperty(). False if null or no value
995 * was set for the given property name.
997 * @note You need to use getProperties() to check for boolean and null properties.
999 public function getProperty( $name ) {
1000 return $this->mProperties
[$name] ??
false;
1003 public function unsetProperty( $name ) {
1004 unset( $this->mProperties
[$name] );
1007 public function getProperties() {
1008 if ( !isset( $this->mProperties
) ) {
1009 $this->mProperties
= [];
1011 return $this->mProperties
;
1015 * Returns the options from its ParserOptions which have been taken
1016 * into account to produce this output.
1019 public function getUsedOptions() {
1020 if ( !isset( $this->mAccessedOptions
) ) {
1023 return array_keys( $this->mAccessedOptions
);
1027 * Tags a parser option for use in the cache key for this parser output.
1028 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
1029 * The information gathered here is available via getUsedOptions(),
1030 * and is used by ParserCache::save().
1032 * @see ParserCache::getKey
1033 * @see ParserCache::save
1034 * @see ParserOptions::addExtraKey
1035 * @see ParserOptions::optionsHash
1036 * @param string $option
1038 public function recordOption( $option ) {
1039 $this->mAccessedOptions
[$option] = true;
1043 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
1044 * the ParserOutput object for later use during page output. The data will be cached along with
1045 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1048 * This method is provided to overcome the unsafe practice of attaching extra information to a
1049 * ParserObject by directly assigning member variables.
1051 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1052 * hook in the page output, use this in the parser hook:
1056 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1059 * And then later, in OutputPageParserOutput or similar:
1063 * $output->getExtensionData( 'my_ext_foo' );
1066 * In MediaWiki 1.20 and older, you have to use a custom member variable
1067 * within the ParserOutput object:
1071 * $parser->getOutput()->my_ext_foo = '...';
1076 * @param string $key The key for accessing the data. Extensions should take care to avoid
1077 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1079 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1082 public function setExtensionData( $key, $value ) {
1083 if ( $value === null ) {
1084 unset( $this->mExtensionData
[$key] );
1086 $this->mExtensionData
[$key] = $value;
1091 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1092 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1096 * @param string $key The key to look up.
1098 * @return mixed|null The value previously set for the given key using setExtensionData()
1099 * or null if no value was set for this key.
1101 public function getExtensionData( $key ) {
1102 if ( isset( $this->mExtensionData
[$key] ) ) {
1103 return $this->mExtensionData
[$key];
1109 private static function getTimes( $clock = null ) {
1111 if ( !$clock ||
$clock === 'wall' ) {
1112 $ret['wall'] = microtime( true );
1114 if ( !$clock ||
$clock === 'cpu' ) {
1115 $ru = wfGetRusage();
1117 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1118 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1125 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1128 public function resetParseStartTime() {
1129 $this->mParseStartTime
= self
::getTimes();
1133 * Returns the time since resetParseStartTime() was last called
1135 * Clocks available are:
1136 * - wall: Wall clock time
1137 * - cpu: CPU time (requires getrusage)
1140 * @param string $clock
1141 * @return float|null
1143 public function getTimeSinceStart( $clock ) {
1144 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1148 $end = self
::getTimes( $clock );
1149 return $end[$clock] - $this->mParseStartTime
[$clock];
1153 * Sets parser limit report data for a key
1155 * The key is used as the prefix for various messages used for formatting:
1156 * - $key: The label for the field in the limit report
1157 * - $key-value-text: Message used to format the value in the "NewPP limit
1158 * report" HTML comment. If missing, uses $key-format.
1159 * - $key-value-html: Message used to format the value in the preview
1160 * limit report table. If missing, uses $key-format.
1161 * - $key-value: Message used to format the value. If missing, uses "$1".
1163 * Note that all values are interpreted as wikitext, and so should be
1164 * encoded with htmlspecialchars() as necessary, but should avoid complex
1165 * HTML for sanity of display in the "NewPP limit report" comment.
1168 * @param string $key Message key
1169 * @param mixed $value Appropriate for Message::params()
1171 public function setLimitReportData( $key, $value ) {
1172 $this->mLimitReportData
[$key] = $value;
1174 if ( is_array( $value ) ) {
1175 if ( array_keys( $value ) === [ 0, 1 ]
1176 && is_numeric( $value[0] )
1177 && is_numeric( $value[1] )
1179 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1187 if ( strpos( $key, '-' ) ) {
1188 list( $ns, $name ) = explode( '-', $key, 2 );
1189 $this->mLimitReportJSData
[$ns][$name] = $data;
1191 $this->mLimitReportJSData
[$key] = $data;
1196 * Check whether the cache TTL was lowered due to dynamic content
1198 * When content is determined by more than hard state (e.g. page edits),
1199 * such as template/file transclusions based on the current timestamp or
1200 * extension tags that generate lists based on queries, this return true.
1205 public function hasDynamicContent() {
1206 global $wgParserCacheExpireTime;
1208 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1212 * Get or set the prevent-clickjacking flag
1215 * @param bool|null $flag New flag value, or null to leave it unchanged
1216 * @return bool Old flag value
1218 public function preventClickjacking( $flag = null ) {
1219 return wfSetVar( $this->mPreventClickjacking
, $flag );
1223 * Lower the runtime adaptive TTL to at most this value
1228 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1229 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1230 $this->updateCacheExpiry( $ttl );
1234 * Call this when parsing is done to lower the TTL based on low parse times
1238 public function finalizeAdaptiveCacheExpiry() {
1239 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1243 $runtime = $this->getTimeSinceStart( 'wall' );
1244 if ( is_float( $runtime ) ) {
1245 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1246 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1247 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1248 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1251 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1252 $this->mMaxAdaptiveExpiry
1254 $this->updateCacheExpiry( $adaptiveTTL );
1258 public function __sleep() {
1260 array_keys( get_object_vars( $this ) ),
1261 [ 'mParseStartTime' ]
1266 * Merges internal metadata such as flags, accessed options, and profiling info
1267 * from $source into this ParserOutput. This should be used whenever the state of $source
1268 * has any impact on the state of this ParserOutput.
1270 * @param ParserOutput $source
1272 public function mergeInternalMetaDataFrom( ParserOutput
$source ) {
1273 $this->mOutputHooks
= self
::mergeList( $this->mOutputHooks
, $source->getOutputHooks() );
1274 $this->mWarnings
= self
::mergeMap( $this->mWarnings
, $source->mWarnings
); // don't use getter
1275 $this->mTimestamp
= $this->useMaxValue( $this->mTimestamp
, $source->getTimestamp() );
1277 if ( $this->mSpeculativeRevId
&& $source->mSpeculativeRevId
1278 && $this->mSpeculativeRevId
!== $source->mSpeculativeRevId
1281 'Inconsistent speculative revision ID encountered while merging parser output!'
1285 $this->mSpeculativeRevId
= $this->useMaxValue(
1286 $this->mSpeculativeRevId
,
1287 $source->getSpeculativeRevIdUsed()
1289 $this->mParseStartTime
= $this->useEachMinValue(
1290 $this->mParseStartTime
,
1291 $source->mParseStartTime
1294 $this->mFlags
= self
::mergeMap( $this->mFlags
, $source->mFlags
);
1295 $this->mAccessedOptions
= self
::mergeMap( $this->mAccessedOptions
, $source->mAccessedOptions
);
1297 // TODO: maintain per-slot limit reports!
1298 if ( empty( $this->mLimitReportData
) ) {
1299 $this->mLimitReportData
= $source->mLimitReportData
;
1301 if ( empty( $this->mLimitReportJSData
) ) {
1302 $this->mLimitReportJSData
= $source->mLimitReportJSData
;
1307 * Merges HTML metadata such as head items, JS config vars, and HTTP cache control info
1308 * from $source into this ParserOutput. This should be used whenever the HTML in $source
1309 * has been somehow mered into the HTML of this ParserOutput.
1311 * @param ParserOutput $source
1313 public function mergeHtmlMetaDataFrom( ParserOutput
$source ) {
1315 $this->mHeadItems
= self
::mergeMixedList( $this->mHeadItems
, $source->getHeadItems() );
1316 $this->mModules
= self
::mergeList( $this->mModules
, $source->getModules() );
1317 $this->mModuleScripts
= self
::mergeList( $this->mModuleScripts
, $source->getModuleScripts() );
1318 $this->mModuleStyles
= self
::mergeList( $this->mModuleStyles
, $source->getModuleStyles() );
1319 $this->mJsConfigVars
= self
::mergeMap( $this->mJsConfigVars
, $source->getJsConfigVars() );
1320 $this->mMaxAdaptiveExpiry
= min( $this->mMaxAdaptiveExpiry
, $source->mMaxAdaptiveExpiry
);
1322 // "noindex" always wins!
1323 if ( $this->mIndexPolicy
=== 'noindex' ||
$source->mIndexPolicy
=== 'noindex' ) {
1324 $this->mIndexPolicy
= 'noindex';
1325 } elseif ( $this->mIndexPolicy
!== 'index' ) {
1326 $this->mIndexPolicy
= $source->mIndexPolicy
;
1330 $this->mNewSection
= $this->mNewSection ||
$source->getNewSection();
1331 $this->mHideNewSection
= $this->mHideNewSection ||
$source->getHideNewSection();
1332 $this->mNoGallery
= $this->mNoGallery ||
$source->getNoGallery();
1333 $this->mEnableOOUI
= $this->mEnableOOUI ||
$source->getEnableOOUI();
1334 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$source->preventClickjacking();
1336 // TODO: we'll have to be smarter about this!
1337 $this->mSections
= array_merge( $this->mSections
, $source->getSections() );
1338 $this->mTOCHTML
= $this->mTOCHTML
. $source->mTOCHTML
;
1340 // XXX: we don't want to concatenate title text, so first write wins.
1341 // We should use the first *modified* title text, but we don't have the original to check.
1342 if ( $this->mTitleText
=== null ||
$this->mTitleText
=== '' ) {
1343 $this->mTitleText
= $source->mTitleText
;
1346 // class names are stored in array keys
1347 $this->mWrapperDivClasses
= self
::mergeMap(
1348 $this->mWrapperDivClasses
,
1349 $source->mWrapperDivClasses
1352 // NOTE: last write wins, same as within one ParserOutput
1353 $this->mIndicators
= self
::mergeMap( $this->mIndicators
, $source->getIndicators() );
1355 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1356 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1357 // kinds of extension data to be merged in different ways.
1358 $this->mExtensionData
= self
::mergeMap(
1359 $this->mExtensionData
,
1360 $source->mExtensionData
1365 * Merges dependency tracking metadata such as backlinks, images used, and extension data
1366 * from $source into this ParserOutput. This allows dependency tracking to be done for the
1367 * combined output of multiple content slots.
1369 * @param ParserOutput $source
1371 public function mergeTrackingMetaDataFrom( ParserOutput
$source ) {
1372 $this->mLanguageLinks
= self
::mergeList( $this->mLanguageLinks
, $source->getLanguageLinks() );
1373 $this->mCategories
= self
::mergeMap( $this->mCategories
, $source->getCategories() );
1374 $this->mLinks
= self
::merge2D( $this->mLinks
, $source->getLinks() );
1375 $this->mTemplates
= self
::merge2D( $this->mTemplates
, $source->getTemplates() );
1376 $this->mTemplateIds
= self
::merge2D( $this->mTemplateIds
, $source->getTemplateIds() );
1377 $this->mImages
= self
::mergeMap( $this->mImages
, $source->getImages() );
1378 $this->mFileSearchOptions
= self
::mergeMap(
1379 $this->mFileSearchOptions
,
1380 $source->getFileSearchOptions()
1382 $this->mExternalLinks
= self
::mergeMap( $this->mExternalLinks
, $source->getExternalLinks() );
1383 $this->mInterwikiLinks
= self
::merge2D(
1384 $this->mInterwikiLinks
,
1385 $source->getInterwikiLinks()
1388 // TODO: add a $mergeStrategy parameter to setProperty to allow different
1389 // kinds of properties to be merged in different ways.
1390 $this->mProperties
= self
::mergeMap( $this->mProperties
, $source->getProperties() );
1392 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1393 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1394 // kinds of extension data to be merged in different ways.
1395 $this->mExtensionData
= self
::mergeMap(
1396 $this->mExtensionData
,
1397 $source->mExtensionData
1401 private static function mergeMixedList( array $a, array $b ) {
1402 return array_unique( array_merge( $a, $b ), SORT_REGULAR
);
1405 private static function mergeList( array $a, array $b ) {
1406 return array_values( array_unique( array_merge( $a, $b ), SORT_REGULAR
) );
1409 private static function mergeMap( array $a, array $b ) {
1410 return array_replace( $a, $b );
1413 private static function merge2D( array $a, array $b ) {
1415 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1417 foreach ( $keys as $k ) {
1418 if ( empty( $a[$k] ) ) {
1419 $values[$k] = $b[$k];
1420 } elseif ( empty( $b[$k] ) ) {
1421 $values[$k] = $a[$k];
1422 } elseif ( is_array( $a[$k] ) && is_array( $b[$k] ) ) {
1423 $values[$k] = array_replace( $a[$k], $b[$k] );
1425 $values[$k] = $b[$k];
1432 private static function useEachMinValue( array $a, array $b ) {
1434 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1436 foreach ( $keys as $k ) {
1437 if ( is_array( $a[$k] ??
null ) && is_array( $b[$k] ??
null ) ) {
1438 $values[$k] = self
::useEachMinValue( $a[$k], $b[$k] );
1440 $values[$k] = self
::useMinValue( $a[$k] ??
null, $b[$k] ??
null );
1447 private static function useMinValue( $a, $b ) {
1448 if ( $a === null ) {
1452 if ( $b === null ) {
1456 return min( $a, $b );
1459 private static function useMaxValue( $a, $b ) {
1460 if ( $a === null ) {
1464 if ( $b === null ) {
1468 return max( $a, $b );