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 /** string CSS classes to use for the wrapping div, stored in the array keys.
217 * If no class is given, no wrapper is added.
219 private $mWrapperDivClasses = [];
221 /** @var int Upper bound of expiry based on parse duration */
222 private $mMaxAdaptiveExpiry = INF
;
224 const EDITSECTION_REGEX
=
225 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
227 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
228 // Current values imply that m=3933.333333 and b=-333.333333
229 // See https://www.nngroup.com/articles/website-response-times/
230 const PARSE_FAST_SEC
= 0.100; // perceived "fast" page parse
231 const PARSE_SLOW_SEC
= 1.0; // perceived "slow" page parse
232 const FAST_AR_TTL
= 60; // adaptive TTL for "fast" pages
233 const SLOW_AR_TTL
= 3600; // adaptive TTL for "slow" pages
234 const MIN_AR_TTL
= 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
237 * @param string|null $text HTML. Use null to indicate that this ParserOutput contains only
238 * meta-data, and the HTML output is undetermined, as opposed to empty. Passing null
239 * here causes hasText() to return false.
240 * @param array $languageLinks
241 * @param array $categoryLinks
242 * @param bool $unused
243 * @param string $titletext
245 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
246 $unused = false, $titletext = ''
248 $this->mText
= $text;
249 $this->mLanguageLinks
= $languageLinks;
250 $this->mCategories
= $categoryLinks;
251 $this->mTitleText
= $titletext;
255 * Returns true if text was passed to the constructor, or set using setText(). Returns false
256 * if null was passed to the $text parameter of the constructor to indicate that this
257 * ParserOutput only contains meta-data, and the HTML output is undetermined.
261 * @return bool Whether this ParserOutput contains rendered text. If this returns false, the
262 * ParserOutput contains meta-data only.
264 public function hasText() {
265 return ( $this->mText
!== null );
269 * Get the cacheable text with <mw:editsection> markers still in it. The
270 * return value is suitable for writing back via setText() but is not valid
271 * for display to the user.
276 public function getRawText() {
277 if ( $this->mText
=== null ) {
278 throw new LogicException( 'This ParserOutput contains no text!' );
285 * Get the output HTML
287 * @param array $options (since 1.31) Transformations to apply to the HTML
288 * - allowTOC: (bool) Show the TOC, assuming there were enough headings
289 * to generate one and `__NOTOC__` wasn't used. Default is true,
290 * but might be statefully overridden.
291 * - enableSectionEditLinks: (bool) Include section edit links, assuming
292 * section edit link tokens are present in the HTML. Default is true,
293 * but might be statefully overridden.
294 * - unwrap: (bool) Return text without a wrapper div. Default is false,
295 * meaning a wrapper div will be added if getWrapperDivClass() returns
296 * a non-empty string.
297 * - wrapperDivClass: (string) Wrap the output in a div and apply the given
298 * CSS class to that div. This overrides the output of getWrapperDivClass().
299 * Setting this to an empty string has the same effect as 'unwrap' => true.
300 * - deduplicateStyles: (bool) When true, which is the default, `<style>`
301 * tags with the `data-mw-deduplicate` attribute set are deduplicated by
302 * value of the attribute: all but the first will be replaced by `<link
303 * rel="mw-deduplicated-inline-style" href="mw-data:..."/>` tags, where
304 * the scheme-specific-part of the href is the (percent-encoded) value
305 * of the `data-mw-deduplicate` attribute.
306 * @return string HTML
307 * @return-taint escaped
309 public function getText( $options = [] ) {
312 'enableSectionEditLinks' => true,
314 'deduplicateStyles' => true,
315 'wrapperDivClass' => $this->getWrapperDivClass(),
317 $text = $this->getRawText();
319 Hooks
::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
321 if ( $options['wrapperDivClass'] !== '' && !$options['unwrap'] ) {
322 $text = Html
::rawElement( 'div', [ 'class' => $options['wrapperDivClass'] ], $text );
325 if ( $options['enableSectionEditLinks'] ) {
326 $text = preg_replace_callback(
327 self
::EDITSECTION_REGEX
,
329 $editsectionPage = Title
::newFromText( htmlspecialchars_decode( $m[1] ) );
330 $editsectionSection = htmlspecialchars_decode( $m[2] );
331 $editsectionContent = isset( $m[4] ) ? Sanitizer
::decodeCharReferences( $m[3] ) : null;
333 if ( !is_object( $editsectionPage ) ) {
334 throw new MWException( "Bad parser output text." );
337 $context = RequestContext
::getMain();
338 return $context->getSkin()->doEditSectionLink(
342 $context->getLanguage()
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 ),
390 // Hydrate slot section header placeholders generated by RevisionRenderer.
391 $text = preg_replace_callback(
392 '#<mw:slotheader>(.*?)</mw:slotheader>#',
394 $role = htmlspecialchars_decode( $m[1] );
395 // TODO: map to message, using the interface language. Set lang="xyz" accordingly.
405 * Add a CSS class to use for the wrapping div. If no class is given, no wrapper is added.
407 * @param string $class
409 public function addWrapperDivClass( $class ) {
410 $this->mWrapperDivClasses
[$class] = true;
414 * Clears the CSS class to use for the wrapping div, effectively disabling the wrapper div
415 * until addWrapperDivClass() is called.
417 public function clearWrapperDivClass() {
418 $this->mWrapperDivClasses
= [];
422 * Returns the class (or classes) to be used with the wrapper div for this otuput.
423 * If there is no wrapper class given, no wrapper div should be added.
424 * The wrapper div is added automatically by getText().
428 public function getWrapperDivClass() {
429 return implode( ' ', array_keys( $this->mWrapperDivClasses
) );
436 public function setSpeculativeRevIdUsed( $id ) {
437 $this->mSpeculativeRevId
= $id;
444 public function getSpeculativeRevIdUsed() {
445 return $this->mSpeculativeRevId
;
448 public function &getLanguageLinks() {
449 return $this->mLanguageLinks
;
452 public function getInterwikiLinks() {
453 return $this->mInterwikiLinks
;
456 public function getCategoryLinks() {
457 return array_keys( $this->mCategories
);
460 public function &getCategories() {
461 return $this->mCategories
;
468 public function getIndicators() {
469 return $this->mIndicators
;
472 public function getTitleText() {
473 return $this->mTitleText
;
476 public function getSections() {
477 return $this->mSections
;
480 public function &getLinks() {
481 return $this->mLinks
;
484 public function &getTemplates() {
485 return $this->mTemplates
;
488 public function &getTemplateIds() {
489 return $this->mTemplateIds
;
492 public function &getImages() {
493 return $this->mImages
;
496 public function &getFileSearchOptions() {
497 return $this->mFileSearchOptions
;
500 public function &getExternalLinks() {
501 return $this->mExternalLinks
;
504 public function setNoGallery( $value ) {
505 $this->mNoGallery
= (bool)$value;
508 public function getNoGallery() {
509 return $this->mNoGallery
;
512 public function getHeadItems() {
513 return $this->mHeadItems
;
516 public function getModules() {
517 return $this->mModules
;
520 public function getModuleStyles() {
521 return $this->mModuleStyles
;
528 public function getJsConfigVars() {
529 return $this->mJsConfigVars
;
532 public function getOutputHooks() {
533 return (array)$this->mOutputHooks
;
536 public function getWarnings() {
537 return array_keys( $this->mWarnings
);
540 public function getIndexPolicy() {
541 return $this->mIndexPolicy
;
544 public function getTOCHTML() {
545 return $this->mTOCHTML
;
549 * @return string|null TS_MW timestamp of the revision content
551 public function getTimestamp() {
552 return $this->mTimestamp
;
555 public function getLimitReportData() {
556 return $this->mLimitReportData
;
559 public function getLimitReportJSData() {
560 return $this->mLimitReportJSData
;
563 public function getEnableOOUI() {
564 return $this->mEnableOOUI
;
567 public function setText( $text ) {
568 return wfSetVar( $this->mText
, $text );
571 public function setLanguageLinks( $ll ) {
572 return wfSetVar( $this->mLanguageLinks
, $ll );
575 public function setCategoryLinks( $cl ) {
576 return wfSetVar( $this->mCategories
, $cl );
579 public function setTitleText( $t ) {
580 return wfSetVar( $this->mTitleText
, $t );
583 public function setSections( $toc ) {
584 return wfSetVar( $this->mSections
, $toc );
587 public function setIndexPolicy( $policy ) {
588 return wfSetVar( $this->mIndexPolicy
, $policy );
591 public function setTOCHTML( $tochtml ) {
592 return wfSetVar( $this->mTOCHTML
, $tochtml );
595 public function setTimestamp( $timestamp ) {
596 return wfSetVar( $this->mTimestamp
, $timestamp );
599 public function addCategory( $c, $sort ) {
600 $this->mCategories
[$c] = $sort;
605 * @param string $content
608 public function setIndicator( $id, $content ) {
609 $this->mIndicators
[$id] = $content;
613 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
614 * object is added to.
617 * @param bool $enable If OOUI should be enabled or not
619 public function setEnableOOUI( $enable = false ) {
620 $this->mEnableOOUI
= $enable;
623 public function addLanguageLink( $t ) {
624 $this->mLanguageLinks
[] = $t;
627 public function addWarning( $s ) {
628 $this->mWarnings
[$s] = 1;
631 public function addOutputHook( $hook, $data = false ) {
632 $this->mOutputHooks
[] = [ $hook, $data ];
635 public function setNewSection( $value ) {
636 $this->mNewSection
= (bool)$value;
639 public function hideNewSection( $value ) {
640 $this->mHideNewSection
= (bool)$value;
643 public function getHideNewSection() {
644 return (bool)$this->mHideNewSection
;
647 public function getNewSection() {
648 return (bool)$this->mNewSection
;
652 * Checks, if a url is pointing to the own server
654 * @param string $internal The server to check against
655 * @param string $url The url to check
658 public static function isLinkInternal( $internal, $url ) {
659 return (bool)preg_match( '/^' .
660 # If server is proto relative, check also for http/https links
661 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
662 preg_quote( $internal, '/' ) .
663 # check for query/path/anchor or end of link in each case
669 public function addExternalLink( $url ) {
670 # We don't register links pointing to our own server, unless... :-)
671 global $wgServer, $wgRegisterInternalExternals;
673 # Replace unnecessary URL escape codes with the referenced character
674 # This prevents spammers from hiding links from the filters
675 $url = Parser
::normalizeLinkUrl( $url );
677 $registerExternalLink = true;
678 if ( !$wgRegisterInternalExternals ) {
679 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
681 if ( $registerExternalLink ) {
682 $this->mExternalLinks
[$url] = 1;
687 * Record a local or interwiki inline link for saving in future link tables.
689 * @param Title $title
690 * @param int|null $id Optional known page_id so we can skip the lookup
692 public function addLink( Title
$title, $id = null ) {
693 if ( $title->isExternal() ) {
694 // Don't record interwikis in pagelinks
695 $this->addInterwikiLink( $title );
698 $ns = $title->getNamespace();
699 $dbk = $title->getDBkey();
700 if ( $ns == NS_MEDIA
) {
701 // Normalize this pseudo-alias if it makes it down here...
703 } elseif ( $ns == NS_SPECIAL
) {
704 // We don't record Special: links currently
705 // It might actually be wise to, but we'd need to do some normalization.
707 } elseif ( $dbk === '' ) {
708 // Don't record self links - [[#Foo]]
711 if ( !isset( $this->mLinks
[$ns] ) ) {
712 $this->mLinks
[$ns] = [];
714 if ( is_null( $id ) ) {
715 $id = $title->getArticleID();
717 $this->mLinks
[$ns][$dbk] = $id;
721 * Register a file dependency for this output
722 * @param string $name Title dbKey
723 * @param string|false|null $timestamp MW timestamp of file creation (or false if non-existing)
724 * @param string|false|null $sha1 Base 36 SHA-1 of file (or false if non-existing)
726 public function addImage( $name, $timestamp = null, $sha1 = null ) {
727 $this->mImages
[$name] = 1;
728 if ( $timestamp !== null && $sha1 !== null ) {
729 $this->mFileSearchOptions
[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
734 * Register a template dependency for this output
735 * @param Title $title
736 * @param int $page_id
739 public function addTemplate( $title, $page_id, $rev_id ) {
740 $ns = $title->getNamespace();
741 $dbk = $title->getDBkey();
742 if ( !isset( $this->mTemplates
[$ns] ) ) {
743 $this->mTemplates
[$ns] = [];
745 $this->mTemplates
[$ns][$dbk] = $page_id;
746 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
747 $this->mTemplateIds
[$ns] = [];
749 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
753 * @param Title $title Title object, must be an interwiki link
754 * @throws MWException If given invalid input
756 public function addInterwikiLink( $title ) {
757 if ( !$title->isExternal() ) {
758 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
760 $prefix = $title->getInterwiki();
761 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
762 $this->mInterwikiLinks
[$prefix] = [];
764 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
768 * Add some text to the "<head>".
769 * If $tag is set, the section with that tag will only be included once
771 * @param string $section
772 * @param string|bool $tag
774 public function addHeadItem( $section, $tag = false ) {
775 if ( $tag !== false ) {
776 $this->mHeadItems
[$tag] = $section;
778 $this->mHeadItems
[] = $section;
783 * @see OutputPage::addModules
785 public function addModules( $modules ) {
786 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
790 * @see OutputPage::addModuleStyles
792 public function addModuleStyles( $modules ) {
793 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
797 * Add one or more variables to be set in mw.config in JavaScript.
799 * @param string|array $keys Key or array of key/value pairs.
800 * @param mixed|null $value [optional] Value of the configuration variable.
803 public function addJsConfigVars( $keys, $value = null ) {
804 if ( is_array( $keys ) ) {
805 foreach ( $keys as $key => $value ) {
806 $this->mJsConfigVars
[$key] = $value;
811 $this->mJsConfigVars
[$keys] = $value;
815 * Copy items from the OutputPage object into this one
817 * @param OutputPage $out
819 public function addOutputPageMetadata( OutputPage
$out ) {
820 $this->addModules( $out->getModules() );
821 $this->addModuleStyles( $out->getModuleStyles() );
822 $this->addJsConfigVars( $out->getJsConfigVars() );
824 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
825 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$out->getPreventClickjacking();
829 * Add a tracking category, getting the title from a system message,
830 * or print a debug message if the title is invalid.
832 * Any message used with this function should be registered so it will
833 * show up on Special:TrackingCategories. Core messages should be added
834 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
835 * should add to "TrackingCategories" in their extension.json.
837 * @todo Migrate some code to TrackingCategories
839 * @param string $msg Message key
840 * @param Title $title title of the page which is being tracked
841 * @return bool Whether the addition was successful
844 public function addTrackingCategory( $msg, $title ) {
845 if ( $title->isSpecialPage() ) {
846 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
850 // Important to parse with correct title (T33469)
851 $cat = wfMessage( $msg )
853 ->inContentLanguage()
856 # Allow tracking categories to be disabled by setting them to "-"
857 if ( $cat === '-' ) {
861 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
862 if ( $containerCategory ) {
863 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?
: '' );
866 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
872 * Override the title to be used for display
874 * @note this is assumed to have been validated
875 * (check equal normalisation, etc.)
877 * @note this is expected to be safe HTML,
878 * ready to be served to the client.
880 * @param string $text Desired title text
882 public function setDisplayTitle( $text ) {
883 $this->setTitleText( $text );
884 $this->setProperty( 'displaytitle', $text );
888 * Get the title to be used for display.
890 * As per the contract of setDisplayTitle(), this is safe HTML,
891 * ready to be served to the client.
893 * @return string HTML
895 public function getDisplayTitle() {
896 $t = $this->getTitleText();
904 * Attach a flag to the output so that it can be checked later to handle special cases
906 * @param string $flag
908 public function setFlag( $flag ) {
909 $this->mFlags
[$flag] = true;
913 * @param string $flag
914 * @return bool Whether the given flag was set to signify a special case
916 public function getFlag( $flag ) {
917 return isset( $this->mFlags
[$flag] );
921 * @return string[] List of flags signifying special cases
924 public function getAllFlags() {
925 return array_keys( $this->mFlags
);
929 * Set a property to be stored in the page_props database table.
931 * page_props is a key value store indexed by the page ID. This allows
932 * the parser to set a property on a page which can then be quickly
933 * retrieved given the page ID or via a DB join when given the page
936 * Since 1.23, page_props are also indexed by numeric value, to allow
937 * for efficient "top k" queries of pages wrt a given property.
939 * setProperty() is thus used to propagate properties from the parsed
940 * page to request contexts other than a page view of the currently parsed
943 * Some applications examples:
945 * * To implement hidden categories, hiding pages from category listings
946 * by storing a property.
948 * * Overriding the displayed article title (ParserOutput::setDisplayTitle()).
950 * * To implement image tagging, for example displaying an icon on an
951 * image thumbnail to indicate that it is listed for deletion on
953 * This is not actually implemented, yet but would be pretty cool.
955 * @note Do not use setProperty() to set a property which is only used
956 * in a context where the ParserOutput object itself is already available,
957 * for example a normal page view. There is no need to save such a property
958 * in the database since the text is already parsed. You can just hook
959 * OutputPageParserOutput and get your data out of the ParserOutput object.
961 * If you are writing an extension where you want to set a property in the
962 * parser which is used by an OutputPageParserOutput hook, you have to
963 * associate the extension data directly with the ParserOutput object.
964 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
968 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
971 * And then later, in OutputPageParserOutput or similar:
975 * $output->getExtensionData( 'my_ext_foo' );
978 * In MediaWiki 1.20 and older, you have to use a custom member variable
979 * within the ParserOutput object:
983 * $parser->getOutput()->my_ext_foo = '...';
985 * @param string $name
986 * @param mixed $value
988 public function setProperty( $name, $value ) {
989 $this->mProperties
[$name] = $value;
993 * @param string $name The property name to look up.
995 * @return mixed|bool The value previously set using setProperty(). False if null or no value
996 * was set for the given property name.
998 * @note You need to use getProperties() to check for boolean and null properties.
1000 public function getProperty( $name ) {
1001 return $this->mProperties
[$name] ??
false;
1004 public function unsetProperty( $name ) {
1005 unset( $this->mProperties
[$name] );
1008 public function getProperties() {
1009 if ( !isset( $this->mProperties
) ) {
1010 $this->mProperties
= [];
1012 return $this->mProperties
;
1016 * Returns the options from its ParserOptions which have been taken
1017 * into account to produce this output.
1020 public function getUsedOptions() {
1021 if ( !isset( $this->mAccessedOptions
) ) {
1024 return array_keys( $this->mAccessedOptions
);
1028 * Tags a parser option for use in the cache key for this parser output.
1029 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
1030 * The information gathered here is available via getUsedOptions(),
1031 * and is used by ParserCache::save().
1033 * @see ParserCache::getKey
1034 * @see ParserCache::save
1035 * @see ParserOptions::addExtraKey
1036 * @see ParserOptions::optionsHash
1037 * @param string $option
1039 public function recordOption( $option ) {
1040 $this->mAccessedOptions
[$option] = true;
1044 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
1045 * the ParserOutput object for later use during page output. The data will be cached along with
1046 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
1049 * This method is provided to overcome the unsafe practice of attaching extra information to a
1050 * ParserObject by directly assigning member variables.
1052 * To use setExtensionData() to pass extension information from a hook inside the parser to a
1053 * hook in the page output, use this in the parser hook:
1057 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
1060 * And then later, in OutputPageParserOutput or similar:
1064 * $output->getExtensionData( 'my_ext_foo' );
1067 * In MediaWiki 1.20 and older, you have to use a custom member variable
1068 * within the ParserOutput object:
1072 * $parser->getOutput()->my_ext_foo = '...';
1077 * @param string $key The key for accessing the data. Extensions should take care to avoid
1078 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
1080 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
1083 public function setExtensionData( $key, $value ) {
1084 if ( $value === null ) {
1085 unset( $this->mExtensionData
[$key] );
1087 $this->mExtensionData
[$key] = $value;
1092 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
1093 * Typically, such data would be set while parsing the page, e.g. by a parser function.
1097 * @param string $key The key to look up.
1099 * @return mixed|null The value previously set for the given key using setExtensionData()
1100 * or null if no value was set for this key.
1102 public function getExtensionData( $key ) {
1103 return $this->mExtensionData
[$key] ??
null;
1106 private static function getTimes( $clock = null ) {
1108 if ( !$clock ||
$clock === 'wall' ) {
1109 $ret['wall'] = microtime( true );
1111 if ( !$clock ||
$clock === 'cpu' ) {
1112 $ru = wfGetRusage();
1114 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
1115 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
1122 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1125 public function resetParseStartTime() {
1126 $this->mParseStartTime
= self
::getTimes();
1130 * Returns the time since resetParseStartTime() was last called
1132 * Clocks available are:
1133 * - wall: Wall clock time
1134 * - cpu: CPU time (requires getrusage)
1137 * @param string $clock
1138 * @return float|null
1140 public function getTimeSinceStart( $clock ) {
1141 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
1145 $end = self
::getTimes( $clock );
1146 return $end[$clock] - $this->mParseStartTime
[$clock];
1150 * Sets parser limit report data for a key
1152 * The key is used as the prefix for various messages used for formatting:
1153 * - $key: The label for the field in the limit report
1154 * - $key-value-text: Message used to format the value in the "NewPP limit
1155 * report" HTML comment. If missing, uses $key-format.
1156 * - $key-value-html: Message used to format the value in the preview
1157 * limit report table. If missing, uses $key-format.
1158 * - $key-value: Message used to format the value. If missing, uses "$1".
1160 * Note that all values are interpreted as wikitext, and so should be
1161 * encoded with htmlspecialchars() as necessary, but should avoid complex
1162 * HTML for sanity of display in the "NewPP limit report" comment.
1165 * @param string $key Message key
1166 * @param mixed $value Appropriate for Message::params()
1168 public function setLimitReportData( $key, $value ) {
1169 $this->mLimitReportData
[$key] = $value;
1171 if ( is_array( $value ) ) {
1172 if ( array_keys( $value ) === [ 0, 1 ]
1173 && is_numeric( $value[0] )
1174 && is_numeric( $value[1] )
1176 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1184 if ( strpos( $key, '-' ) ) {
1185 list( $ns, $name ) = explode( '-', $key, 2 );
1186 $this->mLimitReportJSData
[$ns][$name] = $data;
1188 $this->mLimitReportJSData
[$key] = $data;
1193 * Check whether the cache TTL was lowered due to dynamic content
1195 * When content is determined by more than hard state (e.g. page edits),
1196 * such as template/file transclusions based on the current timestamp or
1197 * extension tags that generate lists based on queries, this return true.
1202 public function hasDynamicContent() {
1203 global $wgParserCacheExpireTime;
1205 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1209 * Get or set the prevent-clickjacking flag
1212 * @param bool|null $flag New flag value, or null to leave it unchanged
1213 * @return bool Old flag value
1215 public function preventClickjacking( $flag = null ) {
1216 return wfSetVar( $this->mPreventClickjacking
, $flag );
1220 * Lower the runtime adaptive TTL to at most this value
1225 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1226 $this->mMaxAdaptiveExpiry
= min( $ttl, $this->mMaxAdaptiveExpiry
);
1227 $this->updateCacheExpiry( $ttl );
1231 * Call this when parsing is done to lower the TTL based on low parse times
1235 public function finalizeAdaptiveCacheExpiry() {
1236 if ( is_infinite( $this->mMaxAdaptiveExpiry
) ) {
1240 $runtime = $this->getTimeSinceStart( 'wall' );
1241 if ( is_float( $runtime ) ) {
1242 $slope = ( self
::SLOW_AR_TTL
- self
::FAST_AR_TTL
)
1243 / ( self
::PARSE_SLOW_SEC
- self
::PARSE_FAST_SEC
);
1244 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1245 $point = self
::SLOW_AR_TTL
- self
::PARSE_SLOW_SEC
* $slope;
1248 max( $slope * $runtime +
$point, self
::MIN_AR_TTL
),
1249 $this->mMaxAdaptiveExpiry
1251 $this->updateCacheExpiry( $adaptiveTTL );
1255 public function __sleep() {
1257 array_keys( get_object_vars( $this ) ),
1258 [ 'mParseStartTime' ]
1263 * Merges internal metadata such as flags, accessed options, and profiling info
1264 * from $source into this ParserOutput. This should be used whenever the state of $source
1265 * has any impact on the state of this ParserOutput.
1267 * @param ParserOutput $source
1269 public function mergeInternalMetaDataFrom( ParserOutput
$source ) {
1270 $this->mOutputHooks
= self
::mergeList( $this->mOutputHooks
, $source->getOutputHooks() );
1271 $this->mWarnings
= self
::mergeMap( $this->mWarnings
, $source->mWarnings
); // don't use getter
1272 $this->mTimestamp
= $this->useMaxValue( $this->mTimestamp
, $source->getTimestamp() );
1274 if ( $this->mSpeculativeRevId
&& $source->mSpeculativeRevId
1275 && $this->mSpeculativeRevId
!== $source->mSpeculativeRevId
1278 'Inconsistent speculative revision ID encountered while merging parser output!'
1282 $this->mSpeculativeRevId
= $this->useMaxValue(
1283 $this->mSpeculativeRevId
,
1284 $source->getSpeculativeRevIdUsed()
1286 $this->mParseStartTime
= $this->useEachMinValue(
1287 $this->mParseStartTime
,
1288 $source->mParseStartTime
1291 $this->mFlags
= self
::mergeMap( $this->mFlags
, $source->mFlags
);
1292 $this->mAccessedOptions
= self
::mergeMap( $this->mAccessedOptions
, $source->mAccessedOptions
);
1294 // TODO: maintain per-slot limit reports!
1295 if ( empty( $this->mLimitReportData
) ) {
1296 $this->mLimitReportData
= $source->mLimitReportData
;
1298 if ( empty( $this->mLimitReportJSData
) ) {
1299 $this->mLimitReportJSData
= $source->mLimitReportJSData
;
1304 * Merges HTML metadata such as head items, JS config vars, and HTTP cache control info
1305 * from $source into this ParserOutput. This should be used whenever the HTML in $source
1306 * has been somehow mered into the HTML of this ParserOutput.
1308 * @param ParserOutput $source
1310 public function mergeHtmlMetaDataFrom( ParserOutput
$source ) {
1312 $this->mHeadItems
= self
::mergeMixedList( $this->mHeadItems
, $source->getHeadItems() );
1313 $this->mModules
= self
::mergeList( $this->mModules
, $source->getModules() );
1314 $this->mModuleStyles
= self
::mergeList( $this->mModuleStyles
, $source->getModuleStyles() );
1315 $this->mJsConfigVars
= self
::mergeMap( $this->mJsConfigVars
, $source->getJsConfigVars() );
1316 $this->mMaxAdaptiveExpiry
= min( $this->mMaxAdaptiveExpiry
, $source->mMaxAdaptiveExpiry
);
1318 // "noindex" always wins!
1319 if ( $this->mIndexPolicy
=== 'noindex' ||
$source->mIndexPolicy
=== 'noindex' ) {
1320 $this->mIndexPolicy
= 'noindex';
1321 } elseif ( $this->mIndexPolicy
!== 'index' ) {
1322 $this->mIndexPolicy
= $source->mIndexPolicy
;
1326 $this->mNewSection
= $this->mNewSection ||
$source->getNewSection();
1327 $this->mHideNewSection
= $this->mHideNewSection ||
$source->getHideNewSection();
1328 $this->mNoGallery
= $this->mNoGallery ||
$source->getNoGallery();
1329 $this->mEnableOOUI
= $this->mEnableOOUI ||
$source->getEnableOOUI();
1330 $this->mPreventClickjacking
= $this->mPreventClickjacking ||
$source->preventClickjacking();
1332 // TODO: we'll have to be smarter about this!
1333 $this->mSections
= array_merge( $this->mSections
, $source->getSections() );
1334 $this->mTOCHTML
.= $source->mTOCHTML
;
1336 // XXX: we don't want to concatenate title text, so first write wins.
1337 // We should use the first *modified* title text, but we don't have the original to check.
1338 if ( $this->mTitleText
=== null ||
$this->mTitleText
=== '' ) {
1339 $this->mTitleText
= $source->mTitleText
;
1342 // class names are stored in array keys
1343 $this->mWrapperDivClasses
= self
::mergeMap(
1344 $this->mWrapperDivClasses
,
1345 $source->mWrapperDivClasses
1348 // NOTE: last write wins, same as within one ParserOutput
1349 $this->mIndicators
= self
::mergeMap( $this->mIndicators
, $source->getIndicators() );
1351 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1352 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1353 // kinds of extension data to be merged in different ways.
1354 $this->mExtensionData
= self
::mergeMap(
1355 $this->mExtensionData
,
1356 $source->mExtensionData
1361 * Merges dependency tracking metadata such as backlinks, images used, and extension data
1362 * from $source into this ParserOutput. This allows dependency tracking to be done for the
1363 * combined output of multiple content slots.
1365 * @param ParserOutput $source
1367 public function mergeTrackingMetaDataFrom( ParserOutput
$source ) {
1368 $this->mLanguageLinks
= self
::mergeList( $this->mLanguageLinks
, $source->getLanguageLinks() );
1369 $this->mCategories
= self
::mergeMap( $this->mCategories
, $source->getCategories() );
1370 $this->mLinks
= self
::merge2D( $this->mLinks
, $source->getLinks() );
1371 $this->mTemplates
= self
::merge2D( $this->mTemplates
, $source->getTemplates() );
1372 $this->mTemplateIds
= self
::merge2D( $this->mTemplateIds
, $source->getTemplateIds() );
1373 $this->mImages
= self
::mergeMap( $this->mImages
, $source->getImages() );
1374 $this->mFileSearchOptions
= self
::mergeMap(
1375 $this->mFileSearchOptions
,
1376 $source->getFileSearchOptions()
1378 $this->mExternalLinks
= self
::mergeMap( $this->mExternalLinks
, $source->getExternalLinks() );
1379 $this->mInterwikiLinks
= self
::merge2D(
1380 $this->mInterwikiLinks
,
1381 $source->getInterwikiLinks()
1384 // TODO: add a $mergeStrategy parameter to setProperty to allow different
1385 // kinds of properties to be merged in different ways.
1386 $this->mProperties
= self
::mergeMap( $this->mProperties
, $source->getProperties() );
1388 // NOTE: include extension data in "tracking meta data" as well as "html meta data"!
1389 // TODO: add a $mergeStrategy parameter to setExtensionData to allow different
1390 // kinds of extension data to be merged in different ways.
1391 $this->mExtensionData
= self
::mergeMap(
1392 $this->mExtensionData
,
1393 $source->mExtensionData
1397 private static function mergeMixedList( array $a, array $b ) {
1398 return array_unique( array_merge( $a, $b ), SORT_REGULAR
);
1401 private static function mergeList( array $a, array $b ) {
1402 return array_values( array_unique( array_merge( $a, $b ), SORT_REGULAR
) );
1405 private static function mergeMap( array $a, array $b ) {
1406 return array_replace( $a, $b );
1409 private static function merge2D( array $a, array $b ) {
1411 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1413 foreach ( $keys as $k ) {
1414 if ( empty( $a[$k] ) ) {
1415 $values[$k] = $b[$k];
1416 } elseif ( empty( $b[$k] ) ) {
1417 $values[$k] = $a[$k];
1418 } elseif ( is_array( $a[$k] ) && is_array( $b[$k] ) ) {
1419 $values[$k] = array_replace( $a[$k], $b[$k] );
1421 $values[$k] = $b[$k];
1428 private static function useEachMinValue( array $a, array $b ) {
1430 $keys = array_merge( array_keys( $a ), array_keys( $b ) );
1432 foreach ( $keys as $k ) {
1433 if ( is_array( $a[$k] ??
null ) && is_array( $b[$k] ??
null ) ) {
1434 $values[$k] = self
::useEachMinValue( $a[$k], $b[$k] );
1436 $values[$k] = self
::useMinValue( $a[$k] ??
null, $b[$k] ??
null );
1443 private static function useMinValue( $a, $b ) {
1444 if ( $a === null ) {
1448 if ( $b === null ) {
1452 return min( $a, $b );
1455 private static function useMaxValue( $a, $b ) {
1456 if ( $a === null ) {
1460 if ( $b === null ) {
1464 return max( $a, $b );