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.
32 const SUPPORTS_STATELESS_TRANSFORMS
= 1;
37 const SUPPORTS_UNWRAP_TRANSFORM
= 1;
40 * @var string|null $mText The output text
45 * @var array $mLanguageLinks List of the full text of language links,
46 * in the order they appear.
48 public $mLanguageLinks;
51 * @var array $mCategories Map of category names to sort keys
56 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
58 public $mIndicators = [];
61 * @var string $mTitleText Title text of the chosen language variant, as HTML.
66 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
72 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
75 public $mTemplates = [];
78 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
81 public $mTemplateIds = [];
84 * @var array $mImages DB keys of the images used, in the array key only
89 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
91 public $mFileSearchOptions = [];
94 * @var array $mExternalLinks External link URLs, in the key only.
96 public $mExternalLinks = [];
99 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
100 * for the inline interwiki links in the document.
102 public $mInterwikiLinks = [];
105 * @var bool $mNewSection Show a new section link?
107 public $mNewSection = false;
110 * @var bool $mHideNewSection Hide the new section link?
112 public $mHideNewSection = false;
115 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
117 public $mNoGallery = false;
120 * @var array $mHeadItems Items to put in the <head> section
122 public $mHeadItems = [];
125 * @var array $mModules Modules to be loaded by ResourceLoader
127 public $mModules = [];
130 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
132 public $mModuleStyles = [];
135 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
137 public $mJsConfigVars = [];
140 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
142 public $mOutputHooks = [];
145 * @var array $mWarnings Warning text to be returned to the user.
146 * Wikitext formatted, in the key only.
148 public $mWarnings = [];
151 * @var array $mSections Table of contents
153 public $mSections = [];
156 * @var array $mProperties Name/value pairs to be cached in the DB.
158 public $mProperties = [];
161 * @var string $mTOCHTML HTML of the TOC.
163 public $mTOCHTML = '';
166 * @var string $mTimestamp Timestamp of the revision.
171 * @var bool $mEnableOOUI Whether OOUI should be enabled.
173 public $mEnableOOUI = false;
176 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
178 private $mIndexPolicy = '';
181 * @var true[] $mAccessedOptions List of ParserOptions (stored in the keys).
183 private $mAccessedOptions = [];
186 * @var array $mExtensionData extra data used by extensions.
188 private $mExtensionData = [];
191 * @var array $mLimitReportData Parser limit report data.
193 private $mLimitReportData = [];
195 /** @var array Parser limit report data for JSON */
196 private $mLimitReportJSData = [];
199 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
201 private $mParseStartTime = [];
204 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
206 private $mPreventClickjacking = false;
209 * @var array $mFlags Generic flags.
211 private $mFlags = [];
213 /** @var int|null Assumed rev ID for {{REVISIONID}} if no revision is set */
214 private $mSpeculativeRevId;
216 /** @var int|null Assumed rev timestamp for {{REVISIONTIMESTAMP}} if no revision is set */
217 private $revisionTimestampUsed;
219 /** string CSS classes to use for the wrapping div, stored in the array keys.
220 * If no class is given, no wrapper is added.
222 private $mWrapperDivClasses = [];
224 /** @var int Upper bound of expiry based on parse duration */
225 private $mMaxAdaptiveExpiry = INF
;
227 const EDITSECTION_REGEX
=
228 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
230 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
231 // Current values imply that m=3933.333333 and b=-333.333333
232 // See https://www.nngroup.com/articles/website-response-times/
233 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
234 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
235 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
236 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
237 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
240 * @param string|null $text HTML. Use null to indicate that this ParserOutput contains only
241 * meta-data, and the HTML output is undetermined, as opposed to empty. Passing null
242 * here causes hasText() to return false.
243 * @param array $languageLinks
244 * @param array $categoryLinks
245 * @param bool $unused
246 * @param string $titletext
248 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
249 $unused = false, $titletext = ''
251 $this->mText
= $text;
252 $this->mLanguageLinks
= $languageLinks;
253 $this->mCategories
= $categoryLinks;
254 $this->mTitleText
= $titletext;
258 * Returns true if text was passed to the constructor, or set using setText(). Returns false
259 * if null was passed to the $text parameter of the constructor to indicate that this
260 * ParserOutput only contains meta-data, and the HTML output is undetermined.
264 * @return bool Whether this ParserOutput contains rendered text. If this returns false, the
265 * ParserOutput contains meta-data only.
267 public function hasText() {
268 return ( $this->mText
!== null );
272 * Get the cacheable text with <mw:editsection> markers still in it. The
273 * return value is suitable for writing back via setText() but is not valid
274 * for display to the user.
279 public function getRawText() {
280 if ( $this->mText
=== null ) {
281 throw new LogicException( 'This ParserOutput contains no text!' );
288 * Get the output HTML
290 * @param array $options (since 1.31) Transformations to apply to the HTML
291 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
292 * to generate one and `__NOTOC__` wasn't used. Default is true,
293 * but might be statefully overridden.
294 * - enableSectionEditLinks: (bool) Include section edit links, assuming
295 * section edit link tokens are present in the HTML. Default is true,
296 * but might be statefully overridden.
297 * - unwrap: (bool) Return text without a wrapper div. Default is false,
298 * meaning a wrapper div will be added if getWrapperDivClass() returns
299 * a non-empty string.
300 * - wrapperDivClass: (string) Wrap the output in a div and apply the given
301 * CSS class to that div. This overrides the output of getWrapperDivClass().
302 * Setting this to an empty string has the same effect as 'unwrap' => true.
303 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
304 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
305 * value of the attribute: all but the first will be replaced by `<link
306 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
307 * the scheme-specific-part of the href is the (percent-encoded) value
308 * of the `data-mw-deduplicate` attribute.
309 * @return string HTML
310 * @return-taint escaped
312 public function getText( $options = [] ) {
315 'enableSectionEditLinks' => true,
317 'deduplicateStyles' => true,
318 'wrapperDivClass' => $this->getWrapperDivClass(),
320 $text = $this->getRawText();
322 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
324 if ( $options['wrapperDivClass'] !== '' && !$options['unwrap'] ) {
325 $text = Html
::rawElement( 'div', [ 'class' => $options['wrapperDivClass'] ], $text );
328 if ( $options['enableSectionEditLinks'] ) {
329 $text = preg_replace_callback(
330 self
::EDITSECTION_REGEX
,
332 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
333 $editsectionSection = htmlspecialchars_decode( $m[2] );
334 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
336 if ( !is_object( $editsectionPage ) ) {
337 throw new MWException( "Bad parser output text." );
340 $context = RequestContext
::getMain();
341 return $context->getSkin()->doEditSectionLink(
345 $context->getLanguage()
351 $text = preg_replace( self
::EDITSECTION_REGEX
, '', $text );
354 if ( $options['allowTOC'] ) {
355 $text = str_replace( [ Parser
::TOC_START
, Parser
::TOC_END
], '', $text );
357 $text = preg_replace(
358 '#' . preg_quote( Parser
::TOC_START
, '#' ) . '.*?' . preg_quote( Parser
::TOC_END
, '#' ) . '#s',
364 if ( $options['deduplicateStyles'] ) {
366 $text = preg_replace_callback(
367 '#<style\s+([^>]*data-mw-deduplicate\s*=[^>]*)>.*?</style>#s',
368 function ( $m ) use ( &$seen ) {
369 $attr = Sanitizer
::decodeTagAttributes( $m[1] );
370 if ( !isset( $attr['data-mw-deduplicate'] ) ) {
374 $key = $attr['data-mw-deduplicate'];
375 if ( !isset( $seen[$key] ) ) {
380 // We were going to use an empty <style> here, but there
381 // was concern that would be too much overhead for browsers.
382 // So let's hope a <link> with a non-standard rel and href isn't
383 // going to be misinterpreted or mangled by any subsequent processing.
384 return Html
::element( 'link', [
385 'rel' => 'mw-deduplicated-inline-style',
386 'href' => "mw-data:" . wfUrlencode( $key ),
393 // Hydrate slot section header placeholders generated by RevisionRenderer.
394 $text = preg_replace_callback(
395 '#<mw:slotheader>(.*?)</mw:slotheader>#',
397 $role = htmlspecialchars_decode( $m[1] );
398 // TODO: map to message, using the interface language. Set lang="xyz" accordingly.
408 * Add a CSS class to use for the wrapping div. If no class is given, no wrapper is added.
410 * @param string $class
412 public function addWrapperDivClass( $class ) {
413 $this->mWrapperDivClasses
[$class] = true;
417 * Clears the CSS class to use for the wrapping div, effectively disabling the wrapper div
418 * until addWrapperDivClass() is called.
420 public function clearWrapperDivClass() {
421 $this->mWrapperDivClasses
= [];
425 * Returns the class (or classes) to be used with the wrapper div for this otuput.
426 * If there is no wrapper class given, no wrapper div should be added.
427 * The wrapper div is added automatically by getText().
431 public function getWrapperDivClass() {
432 return implode( ' ', array_keys( $this->mWrapperDivClasses
) );
439 public function setSpeculativeRevIdUsed( $id ) {
440 $this->mSpeculativeRevId
= $id;
447 public function getSpeculativeRevIdUsed() {
448 return $this->mSpeculativeRevId
;
452 * @param string $timestamp TS_MW timestamp
455 public function setRevisionTimestampUsed( $timestamp ) {
456 $this->revisionTimestampUsed
= $timestamp;
460 * @return string|null TS_MW timestamp or null if not used
463 public function getRevisionTimestampUsed() {
464 return $this->revisionTimestampUsed
;
467 public function &getLanguageLinks() {
468 return $this->mLanguageLinks
;
471 public function getInterwikiLinks() {
472 return $this->mInterwikiLinks
;
475 public function getCategoryLinks() {
476 return array_keys( $this->mCategories
);
479 public function &getCategories() {
480 return $this->mCategories
;
487 public function getIndicators() {
488 return $this->mIndicators
;
491 public function getTitleText() {
492 return $this->mTitleText
;
495 public function getSections() {
496 return $this->mSections
;
499 public function &getLinks() {
500 return $this->mLinks
;
503 public function &getTemplates() {
504 return $this->mTemplates
;
507 public function &getTemplateIds() {
508 return $this->mTemplateIds
;
511 public function &getImages() {
512 return $this->mImages
;
515 public function &getFileSearchOptions() {
516 return $this->mFileSearchOptions
;
519 public function &getExternalLinks() {
520 return $this->mExternalLinks
;
523 public function setNoGallery( $value ) {
524 $this->mNoGallery
= (bool)$value;
527 public function getNoGallery() {
528 return $this->mNoGallery
;
531 public function getHeadItems() {
532 return $this->mHeadItems
;
535 public function getModules() {
536 return $this->mModules
;
539 public function getModuleStyles() {
540 return $this->mModuleStyles
;
547 public function getJsConfigVars() {
548 return $this->mJsConfigVars
;
551 public function getOutputHooks() {
552 return (array)$this->mOutputHooks
;
555 public function getWarnings() {
556 return array_keys( $this->mWarnings
);
559 public function getIndexPolicy() {
560 return $this->mIndexPolicy
;
563 public function getTOCHTML() {
564 return $this->mTOCHTML
;
568 * @return string|null TS_MW timestamp of the revision content
570 public function getTimestamp() {
571 return $this->mTimestamp
;
574 public function getLimitReportData() {
575 return $this->mLimitReportData
;
578 public function getLimitReportJSData() {
579 return $this->mLimitReportJSData
;
582 public function getEnableOOUI() {
583 return $this->mEnableOOUI
;
586 public function setText( $text ) {
587 return wfSetVar( $this->mText
, $text );
590 public function setLanguageLinks( $ll ) {
591 return wfSetVar( $this->mLanguageLinks
, $ll );
594 public function setCategoryLinks( $cl ) {
595 return wfSetVar( $this->mCategories
, $cl );
598 public function setTitleText( $t ) {
599 return wfSetVar( $this->mTitleText
, $t );
602 public function setSections( $toc ) {
603 return wfSetVar( $this->mSections
, $toc );
606 public function setIndexPolicy( $policy ) {
607 return wfSetVar( $this->mIndexPolicy
, $policy );
610 public function setTOCHTML( $tochtml ) {
611 return wfSetVar( $this->mTOCHTML
, $tochtml );
614 public function setTimestamp( $timestamp ) {
615 return wfSetVar( $this->mTimestamp
, $timestamp );
618 public function addCategory( $c, $sort ) {
619 $this->mCategories
[$c] = $sort;
624 * @param string $content
627 public function setIndicator( $id, $content ) {
628 $this->mIndicators
[$id] = $content;
632 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
633 * object is added to.
636 * @param bool $enable If OOUI should be enabled or not
638 public function setEnableOOUI( $enable = false ) {
639 $this->mEnableOOUI
= $enable;
642 public function addLanguageLink( $t ) {
643 $this->mLanguageLinks
[] = $t;
646 public function addWarning( $s ) {
647 $this->mWarnings
[$s] = 1;
650 public function addOutputHook( $hook, $data = false ) {
651 $this->mOutputHooks
[] = [ $hook, $data ];
654 public function setNewSection( $value ) {
655 $this->mNewSection
= (bool)$value;
658 public function hideNewSection( $value ) {
659 $this->mHideNewSection
= (bool)$value;
662 public function getHideNewSection() {
663 return (bool)$this->mHideNewSection
;
666 public function getNewSection() {
667 return (bool)$this->mNewSection
;
671 * Checks, if a url is pointing to the own server
673 * @param string $internal The server to check against
674 * @param string $url The url to check
677 public static function isLinkInternal( $internal, $url ) {
678 return (bool)preg_match( '/^' .
679 # If server is proto relative, check also for http/https links
680 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
681 preg_quote( $internal, '/' ) .
682 # check for query/path/anchor or end of link in each case
688 public function addExternalLink( $url ) {
689 # We don't register links pointing to our own server, unless... :-)
690 global $wgServer, $wgRegisterInternalExternals;
692 # Replace unnecessary URL escape codes with the referenced character
693 # This prevents spammers from hiding links from the filters
694 $url = Parser
::normalizeLinkUrl( $url );
696 $registerExternalLink = true;
697 if ( !$wgRegisterInternalExternals ) {
698 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
700 if ( $registerExternalLink ) {
701 $this->mExternalLinks
[$url] = 1;
706 * Record a local or interwiki inline link for saving in future link tables.
708 * @param Title $title
709 * @param int|null $id Optional known page_id so we can skip the lookup
711 public function addLink( Title
$title, $id = null ) {
712 if ( $title->isExternal() ) {
713 // Don't record interwikis in pagelinks
714 $this->addInterwikiLink( $title );
717 $ns = $title->getNamespace();
718 $dbk = $title->getDBkey();
719 if ( $ns == NS_MEDIA
) {
720 // Normalize this pseudo-alias if it makes it down here...
722 } elseif ( $ns == NS_SPECIAL
) {
723 // We don't record Special: links currently
724 // It might actually be wise to, but we'd need to do some normalization.
726 } elseif ( $dbk === '' ) {
727 // Don't record self links - [[#Foo]]
730 if ( !isset( $this->mLinks
[$ns] ) ) {
731 $this->mLinks
[$ns] = [];
733 if ( is_null( $id ) ) {
734 $id = $title->getArticleID();
736 $this->mLinks
[$ns][$dbk] = $id;
740 * Register a file dependency for this output
741 * @param string $name Title dbKey
742 * @param string|false|null $timestamp MW timestamp of file creation (or false if non-existing)
743 * @param string|false|null $sha1 Base 36 SHA-1 of file (or false if non-existing)
745 public function addImage( $name, $timestamp = null, $sha1 = null ) {
746 $this->mImages
[$name] = 1;
747 if ( $timestamp !== null && $sha1 !== null ) {
748 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
753 * Register a template dependency for this output
754 * @param Title $title
755 * @param int $page_id
758 public function addTemplate( $title, $page_id, $rev_id ) {
759 $ns = $title->getNamespace();
760 $dbk = $title->getDBkey();
761 if ( !isset( $this->mTemplates
[$ns] ) ) {
762 $this->mTemplates
[$ns] = [];
764 $this->mTemplates
[$ns][$dbk] = $page_id;
765 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
766 $this->mTemplateIds
[$ns] = [];
768 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
772 * @param Title $title Title object, must be an interwiki link
773 * @throws MWException If given invalid input
775 public function addInterwikiLink( $title ) {
776 if ( !$title->isExternal() ) {
777 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
779 $prefix = $title->getInterwiki();
780 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
781 $this->mInterwikiLinks
[$prefix] = [];
783 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
787 * Add some text to the "<head>".
788 * If $tag is set, the section with that tag will only be included once
790 * @param string $section
791 * @param string|bool $tag
793 public function addHeadItem( $section, $tag = false ) {
794 if ( $tag !== false ) {
795 $this->mHeadItems
[$tag] = $section;
797 $this->mHeadItems
[] = $section;
802 * @see OutputPage::addModules
804 public function addModules( $modules ) {
805 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
809 * @see OutputPage::addModuleStyles
811 public function addModuleStyles( $modules ) {
812 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
816 * Add one or more variables to be set in mw.config in JavaScript.
818 * @param string|array $keys Key or array of key/value pairs.
819 * @param mixed|null $value [optional] Value of the configuration variable.
822 public function addJsConfigVars( $keys, $value = null ) {
823 if ( is_array( $keys ) ) {
824 foreach ( $keys as $key => $value ) {
825 $this->mJsConfigVars
[$key] = $value;
830 $this->mJsConfigVars
[$keys] = $value;
834 * Copy items from the OutputPage object into this one
836 * @param OutputPage $out
838 public function addOutputPageMetadata( OutputPage
$out ) {
839 $this->addModules( $out->getModules() );
840 $this->addModuleStyles( $out->getModuleStyles() );
841 $this->addJsConfigVars( $out->getJsConfigVars() );
843 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
844 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
848 * Add a tracking category, getting the title from a system message,
849 * or print a debug message if the title is invalid.
851 * Any message used with this function should be registered so it will
852 * show up on Special:TrackingCategories. Core messages should be added
853 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
854 * should add to "TrackingCategories" in their extension.json.
856 * @todo Migrate some code to TrackingCategories
858 * @param string $msg Message key
859 * @param Title $title title of the page which is being tracked
860 * @return bool Whether the addition was successful
863 public function addTrackingCategory( $msg, $title ) {
864 if ( $title->isSpecialPage() ) {
865 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
869 // Important to parse with correct title (T33469)
870 $cat = wfMessage( $msg )
872 ->inContentLanguage()
875 # Allow tracking categories to be disabled by setting them to "-"
876 if ( $cat === '-' ) {
880 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
881 if ( $containerCategory ) {
882 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
885 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
891 * Override the title to be used for display
893 * @note this is assumed to have been validated
894 * (check equal normalisation, etc.)
896 * @note this is expected to be safe HTML,
897 * ready to be served to the client.
899 * @param string $text Desired title text
901 public function setDisplayTitle( $text ) {
902 $this->setTitleText( $text );
903 $this->setProperty( 'displaytitle', $text );
907 * Get the title to be used for display.
909 * As per the contract of setDisplayTitle(), this is safe HTML,
910 * ready to be served to the client.
912 * @return string HTML
914 public function getDisplayTitle() {
915 $t = $this->getTitleText();
923 * Attach a flag to the output so that it can be checked later to handle special cases
925 * @param string $flag
927 public function setFlag( $flag ) {
928 $this->mFlags
[$flag] = true;
932 * @param string $flag
933 * @return bool Whether the given flag was set to signify a special case
935 public function getFlag( $flag ) {
936 return isset( $this->mFlags
[$flag] );
940 * @return string[] List of flags signifying special cases
943 public function getAllFlags() {
944 return array_keys( $this->mFlags
);
948 * Set a property to be stored in the page_props database table.
950 * page_props is a key value store indexed by the page ID. This allows
951 * the parser to set a property on a page which can then be quickly
952 * retrieved given the page ID or via a DB join when given the page
955 * Since 1.23, page_props are also indexed by numeric value, to allow
956 * for efficient "top k" queries of pages wrt a given property.
958 * setProperty() is thus used to propagate properties from the parsed
959 * page to request contexts other than a page view of the currently parsed
962 * Some applications examples:
964 * * To implement hidden categories, hiding pages from category listings
965 * by storing a property.
967 * * Overriding the displayed article title (ParserOutput::setDisplayTitle()).
969 * * To implement image tagging, for example displaying an icon on an
970 * image thumbnail to indicate that it is listed for deletion on
972 * This is not actually implemented, yet but would be pretty cool.
974 * @note Do not use setProperty() to set a property which is only used
975 * in a context where the ParserOutput object itself is already available,
976 * for example a normal page view. There is no need to save such a property
977 * in the database since the text is already parsed. You can just hook
978 * OutputPageParserOutput and get your data out of the ParserOutput object.
980 * If you are writing an extension where you want to set a property in the
981 * parser which is used by an OutputPageParserOutput hook, you have to
982 * associate the extension data directly with the ParserOutput object.
983 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
987 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
990 * And then later, in OutputPageParserOutput or similar:
994 * $output->getExtensionData( 'my_ext_foo' );
997 * In MediaWiki 1.20 and older, you have to use a custom member variable
998 * within the ParserOutput object:
1002 * $parser->getOutput()->my_ext_foo = '...';
1004 * @param string $name
1005 * @param mixed $value
1007 public function setProperty( $name, $value ) {
1008 $this->mProperties
[$name] = $value;
1012 * @param string $name The property name to look up.
1014 * @return mixed|bool The value previously set using setProperty(). False if null or no value
1015 * was set for the given property name.
1017 * @note You need to use getProperties() to check for boolean and null properties.
1019 public function getProperty( $name ) {
1020 return $this->mProperties
[$name] ??
false;
1023 public function unsetProperty( $name ) {
1024 unset( $this->mProperties
[$name] );
1027 public function getProperties() {
1028 if ( !isset( $this->mProperties
) ) {
1029 $this->mProperties
= [];
1031 return $this->mProperties
;
1035 * Returns the options from its ParserOptions which have been taken
1036 * into account to produce this output.
1039 public function getUsedOptions() {
1040 if ( !isset( $this->mAccessedOptions
) ) {
1043 return array_keys( $this->mAccessedOptions
);
1047 * Tags a parser option for use in the cache key for this parser output.
1048 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
1049 * The information gathered here is available via getUsedOptions(),
1050 * and is used by ParserCache::save().
1052 * @see ParserCache::getKey
1053 * @see ParserCache::save
1054 * @see ParserOptions::addExtraKey
1055 * @see ParserOptions::optionsHash
1056 * @param string $option
1058 public function recordOption( $option ) {
1059 $this->mAccessedOptions
[$option] = true;
1063 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
1064 * the ParserOutput object for later use during page output. The data will be cached along with
1065 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1068 * This method is provided to overcome the unsafe practice of attaching extra information to a
1069 * ParserObject by directly assigning member variables.
1071 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1072 * hook in the page output, use this in the parser hook:
1076 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1079 * And then later, in OutputPageParserOutput or similar:
1083 * $output->getExtensionData( 'my_ext_foo' );
1086 * In MediaWiki 1.20 and older, you have to use a custom member variable
1087 * within the ParserOutput object:
1091 * $parser->getOutput()->my_ext_foo = '...';
1096 * @param string $key The key for accessing the data. Extensions should take care to avoid
1097 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1099 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1102 public function setExtensionData( $key, $value ) {
1103 if ( $value === null ) {
1104 unset( $this->mExtensionData
[$key] );
1106 $this->mExtensionData
[$key] = $value;
1111 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1112 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1116 * @param string $key The key to look up.
1118 * @return mixed|null The value previously set for the given key using setExtensionData()
1119 * or null if no value was set for this key.
1121 public function getExtensionData( $key ) {
1122 return $this->mExtensionData
[$key] ??
null;
1125 private static function getTimes( $clock = null ) {
1127 if ( !$clock ||
$clock === 'wall' ) {
1128 $ret['wall'] = microtime( true );
1130 if ( !$clock ||
$clock === 'cpu' ) {
1131 $ru = wfGetRusage();
1133 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1134 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1141 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1144 public function resetParseStartTime() {
1145 $this->mParseStartTime
= self
::getTimes();
1149 * Returns the time since resetParseStartTime() was last called
1151 * Clocks available are:
1152 * - wall: Wall clock time
1153 * - cpu: CPU time (requires getrusage)
1156 * @param string $clock
1157 * @return float|null
1159 public function getTimeSinceStart( $clock ) {
1160 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1164 $end = self
::getTimes( $clock );
1165 return $end[$clock] - $this->mParseStartTime
[$clock];
1169 * Sets parser limit report data for a key
1171 * The key is used as the prefix for various messages used for formatting:
1172 * - $key: The label for the field in the limit report
1173 * - $key-value-text: Message used to format the value in the "NewPP limit
1174 * report" HTML comment. If missing, uses $key-format.
1175 * - $key-value-html: Message used to format the value in the preview
1176 * limit report table. If missing, uses $key-format.
1177 * - $key-value: Message used to format the value. If missing, uses "$1".
1179 * Note that all values are interpreted as wikitext, and so should be
1180 * encoded with htmlspecialchars() as necessary, but should avoid complex
1181 * HTML for sanity of display in the "NewPP limit report" comment.
1184 * @param string $key Message key
1185 * @param mixed $value Appropriate for Message::params()
1187 public function setLimitReportData( $key, $value ) {
1188 $this->mLimitReportData
[$key] = $value;
1190 if ( is_array( $value ) ) {
1191 if ( array_keys( $value ) === [ 0, 1 ]
1192 && is_numeric( $value[0] )
1193 && is_numeric( $value[1] )
1195 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1203 if ( strpos( $key, '-' ) ) {
1204 list( $ns, $name ) = explode( '-', $key, 2 );
1205 $this->mLimitReportJSData
[$ns][$name] = $data;
1207 $this->mLimitReportJSData
[$key] = $data;
1212 * Check whether the cache TTL was lowered due to dynamic content
1214 * When content is determined by more than hard state (e.g. page edits),
1215 * such as template/file transclusions based on the current timestamp or
1216 * extension tags that generate lists based on queries, this return true.
1221 public function hasDynamicContent() {
1222 global $wgParserCacheExpireTime;
1224 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1228 * Get or set the prevent-clickjacking flag
1231 * @param bool|null $flag New flag value, or null to leave it unchanged
1232 * @return bool Old flag value
1234 public function preventClickjacking( $flag = null ) {
1235 return wfSetVar( $this->mPreventClickjacking
, $flag );
1239 * Lower the runtime adaptive TTL to at most this value
1244 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1245 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1246 $this->updateCacheExpiry( $ttl );
1250 * Call this when parsing is done to lower the TTL based on low parse times
1254 public function finalizeAdaptiveCacheExpiry() {
1255 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1259 $runtime = $this->getTimeSinceStart( 'wall' );
1260 if ( is_float( $runtime ) ) {
1261 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1262 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1263 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1264 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1267 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1268 $this->mMaxAdaptiveExpiry
1270 $this->updateCacheExpiry( $adaptiveTTL );
1274 public function __sleep() {
1276 array_keys( get_object_vars( $this ) ),
1277 [ 'mParseStartTime' ]
1282 * Merges internal metadata such as flags, accessed options, and profiling info
1283 * from $source into this ParserOutput. This should be used whenever the state of $source
1284 * has any impact on the state of this ParserOutput.
1286 * @param ParserOutput $source
1288 public function mergeInternalMetaDataFrom( ParserOutput
$source ) {
1289 $this->mOutputHooks
= self
::mergeList( $this->mOutputHooks
, $source->getOutputHooks() );
1290 $this->mWarnings
= self
::mergeMap( $this->mWarnings
, $source->mWarnings
); // don't use getter
1291 $this->mTimestamp
= $this->useMaxValue( $this->mTimestamp
, $source->getTimestamp() );
1293 if ( $this->mSpeculativeRevId
&& $source->mSpeculativeRevId
1294 && $this->mSpeculativeRevId
!== $source->mSpeculativeRevId
1297 'Inconsistent speculative revision ID encountered while merging parser output!'
1301 $this->mSpeculativeRevId
= $this->useMaxValue(
1302 $this->mSpeculativeRevId
,
1303 $source->getSpeculativeRevIdUsed()
1305 $this->mParseStartTime
= $this->useEachMinValue(
1306 $this->mParseStartTime
,
1307 $source->mParseStartTime
1310 $this->mFlags
= self
::mergeMap( $this->mFlags
, $source->mFlags
);
1311 $this->mAccessedOptions
= self
::mergeMap( $this->mAccessedOptions
, $source->mAccessedOptions
);
1313 // TODO: maintain per-slot limit reports!
1314 if ( empty( $this->mLimitReportData
) ) {
1315 $this->mLimitReportData
= $source->mLimitReportData
;
1317 if ( empty( $this->mLimitReportJSData
) ) {
1318 $this->mLimitReportJSData
= $source->mLimitReportJSData
;
1323 * Merges HTML metadata such as head items, JS config vars, and HTTP cache control info
1324 * from $source into this ParserOutput. This should be used whenever the HTML in $source
1325 * has been somehow mered into the HTML of this ParserOutput.
1327 * @param ParserOutput $source
1329 public function mergeHtmlMetaDataFrom( ParserOutput
$source ) {
1331 $this->mHeadItems
= self
::mergeMixedList( $this->mHeadItems
, $source->getHeadItems() );
1332 $this->mModules
= self
::mergeList( $this->mModules
, $source->getModules() );
1333 $this->mModuleStyles
= self
::mergeList( $this->mModuleStyles
, $source->getModuleStyles() );
1334 $this->mJsConfigVars
= self
::mergeMap( $this->mJsConfigVars
, $source->getJsConfigVars() );
1335 $this->mMaxAdaptiveExpiry
= min( $this->mMaxAdaptiveExpiry
, $source->mMaxAdaptiveExpiry
);
1337 // "noindex" always wins!
1338 if ( $this->mIndexPolicy
=== 'noindex' ||
$source->mIndexPolicy
=== 'noindex' ) {
1339 $this->mIndexPolicy
= 'noindex';
1340 } elseif ( $this->mIndexPolicy
!== 'index' ) {
1341 $this->mIndexPolicy
= $source->mIndexPolicy
;
1345 $this->mNewSection
= $this->mNewSection ||
$source->getNewSection();
1346 $this->mHideNewSection
= $this->mHideNewSection ||
$source->getHideNewSection();
1347 $this->mNoGallery
= $this->mNoGallery ||
$source->getNoGallery();
1348 $this->mEnableOOUI
= $this->mEnableOOUI ||
$source->getEnableOOUI();
1349 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$source->preventClickjacking();
1351 // TODO: we'll have to be smarter about this!
1352 $this->mSections
= array_merge( $this->mSections
, $source->getSections() );
1353 $this->mTOCHTML
.= $source->mTOCHTML
;
1355 // XXX: we don't want to concatenate title text, so first write wins.
1356 // We should use the first *modified* title text, but we don't have the original to check.
1357 if ( $this->mTitleText
=== null ||
$this->mTitleText
=== '' ) {
1358 $this->mTitleText
= $source->mTitleText
;
1361 // class names are stored in array keys
1362 $this->mWrapperDivClasses
= self
::mergeMap(
1363 $this->mWrapperDivClasses
,
1364 $source->mWrapperDivClasses
1367 // NOTE: last write wins, same as within one ParserOutput
1368 $this->mIndicators
= self
::mergeMap( $this->mIndicators
, $source->getIndicators() );
1370 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1371 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1372 // kinds of extension data to be merged in different ways.
1373 $this->mExtensionData
= self
::mergeMap(
1374 $this->mExtensionData
,
1375 $source->mExtensionData
1380 * Merges dependency tracking metadata such as backlinks, images used, and extension data
1381 * from $source into this ParserOutput. This allows dependency tracking to be done for the
1382 * combined output of multiple content slots.
1384 * @param ParserOutput $source
1386 public function mergeTrackingMetaDataFrom( ParserOutput
$source ) {
1387 $this->mLanguageLinks
= self
::mergeList( $this->mLanguageLinks
, $source->getLanguageLinks() );
1388 $this->mCategories
= self
::mergeMap( $this->mCategories
, $source->getCategories() );
1389 $this->mLinks
= self
::merge2D( $this->mLinks
, $source->getLinks() );
1390 $this->mTemplates
= self
::merge2D( $this->mTemplates
, $source->getTemplates() );
1391 $this->mTemplateIds
= self
::merge2D( $this->mTemplateIds
, $source->getTemplateIds() );
1392 $this->mImages
= self
::mergeMap( $this->mImages
, $source->getImages() );
1393 $this->mFileSearchOptions
= self
::mergeMap(
1394 $this->mFileSearchOptions
,
1395 $source->getFileSearchOptions()
1397 $this->mExternalLinks
= self
::mergeMap( $this->mExternalLinks
, $source->getExternalLinks() );
1398 $this->mInterwikiLinks
= self
::merge2D(
1399 $this->mInterwikiLinks
,
1400 $source->getInterwikiLinks()
1403 // TODO: add a $mergeStrategy parameter to setProperty to allow different
1404 // kinds of properties to be merged in different ways.
1405 $this->mProperties
= self
::mergeMap( $this->mProperties
, $source->getProperties() );
1407 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1408 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1409 // kinds of extension data to be merged in different ways.
1410 $this->mExtensionData
= self
::mergeMap(
1411 $this->mExtensionData
,
1412 $source->mExtensionData
1416 private static function mergeMixedList( array $a, array $b ) {
1417 return array_unique( array_merge( $a, $b ), SORT_REGULAR
);
1420 private static function mergeList( array $a, array $b ) {
1421 return array_values( array_unique( array_merge( $a, $b ), SORT_REGULAR
) );
1424 private static function mergeMap( array $a, array $b ) {
1425 return array_replace( $a, $b );
1428 private static function merge2D( array $a, array $b ) {
1430 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1432 foreach ( $keys as $k ) {
1433 if ( empty( $a[$k] ) ) {
1434 $values[$k] = $b[$k];
1435 } elseif ( empty( $b[$k] ) ) {
1436 $values[$k] = $a[$k];
1437 } elseif ( is_array( $a[$k] ) && is_array( $b[$k] ) ) {
1438 $values[$k] = array_replace( $a[$k], $b[$k] );
1440 $values[$k] = $b[$k];
1447 private static function useEachMinValue( array $a, array $b ) {
1449 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1451 foreach ( $keys as $k ) {
1452 if ( is_array( $a[$k] ??
null ) && is_array( $b[$k] ??
null ) ) {
1453 $values[$k] = self
::useEachMinValue( $a[$k], $b[$k] );
1455 $values[$k] = self
::useMinValue( $a[$k] ??
null, $b[$k] ??
null );
1462 private static function useMinValue( $a, $b ) {
1463 if ( $a === null ) {
1467 if ( $b === null ) {
1471 return min( $a, $b );
1474 private static function useMaxValue( $a, $b ) {
1475 if ( $a === null ) {
1479 if ( $b === null ) {
1483 return max( $a, $b );