wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / parser / ParserOutput.php
blobe4c287a3894ee6e20f83d84dc74316c8a1c1b9a4
1 <?php
3 /**
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
21 * @file
22 * @ingroup Parser
24 class ParserOutput extends CacheTime {
25 /**
26 * @var string $mText The output text
28 public $mText;
30 /**
31 * @var array $mLanguageLinks List of the full text of language links,
32 * in the order they appear.
34 public $mLanguageLinks;
36 /**
37 * @var array $mCategoriesMap of category names to sort keys
39 public $mCategories;
41 /**
42 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
44 public $mIndicators = array();
46 /**
47 * @var string $mTitleText Title text of the chosen language variant, as HTML.
49 public $mTitleText;
51 /**
52 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
53 * ID=zero for broken.
55 public $mLinks = array();
57 /**
58 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
59 * ID=zero for broken.
61 public $mTemplates = array();
63 /**
64 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
65 * ID=zero for broken.
67 public $mTemplateIds = array();
69 /**
70 * @var array $mImages DB keys of the images used, in the array key only
72 public $mImages = array();
74 /**
75 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
77 public $mFileSearchOptions = array();
79 /**
80 * @var array $mExternalLinks External link URLs, in the key only.
82 public $mExternalLinks = array();
84 /**
85 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
86 * for the inline interwiki links in the document.
88 public $mInterwikiLinks = array();
90 /**
91 * @var bool $mNewSection Show a new section link?
93 public $mNewSection = false;
95 /**
96 * @var bool $mHideNewSection Hide the new section link?
98 public $mHideNewSection = false;
101 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
103 public $mNoGallery = false;
106 * @var array $mHeadItems Items to put in the <head> section
108 public $mHeadItems = array();
111 * @var array $mModules Modules to be loaded by ResourceLoader
113 public $mModules = array();
116 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
118 public $mModuleScripts = array();
121 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
123 public $mModuleStyles = array();
126 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
128 public $mJsConfigVars = array();
131 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
133 public $mOutputHooks = array();
136 * @var array $mWarnings Warning text to be returned to the user.
137 * Wikitext formatted, in the key only.
139 public $mWarnings = array();
142 * @var array $mSections Table of contents
144 public $mSections = array();
147 * @var bool $mEditSectionTokens prefix/suffix markers if edit sections were output as tokens.
149 public $mEditSectionTokens = false;
152 * @var array $mProperties Name/value pairs to be cached in the DB.
154 public $mProperties = array();
157 * @var string $mTOCHTML HTML of the TOC.
159 public $mTOCHTML = '';
162 * @var string $mTimestamp Timestamp of the revision.
164 public $mTimestamp;
167 * @var bool $mTOCEnabled Whether TOC should be shown, can't override __NOTOC__.
169 public $mTOCEnabled = true;
172 * @var bool $mEnableOOUI Whether OOUI should be enabled.
174 public $mEnableOOUI = false;
177 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
179 private $mIndexPolicy = '';
182 * @var array $mAccessedOptions List of ParserOptions (stored in the keys).
184 private $mAccessedOptions = array();
187 * @var array $mExtensionData extra data used by extensions.
189 private $mExtensionData = array();
192 * @var array $mLimitReportData Parser limit report data.
194 private $mLimitReportData = array();
197 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
199 private $mParseStartTime = array();
202 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
204 private $mPreventClickjacking = false;
207 * @var array $mFlags Generic flags.
209 private $mFlags = array();
211 const EDITSECTION_REGEX =
212 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
214 public function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
215 $unused = false, $titletext = ''
217 $this->mText = $text;
218 $this->mLanguageLinks = $languageLinks;
219 $this->mCategories = $categoryLinks;
220 $this->mTitleText = $titletext;
223 public function getText() {
224 $text = $this->mText;
225 if ( $this->mEditSectionTokens ) {
226 $text = preg_replace_callback(
227 ParserOutput::EDITSECTION_REGEX,
228 function ( $m ) {
229 global $wgOut, $wgLang;
230 $editsectionPage = Title::newFromText( htmlspecialchars_decode( $m[1] ) );
231 $editsectionSection = htmlspecialchars_decode( $m[2] );
232 $editsectionContent = isset( $m[4] ) ? $m[3] : null;
234 if ( !is_object( $editsectionPage ) ) {
235 throw new MWException( "Bad parser output text." );
238 $skin = $wgOut->getSkin();
239 return call_user_func_array(
240 array( $skin, 'doEditSectionLink' ),
241 array( $editsectionPage, $editsectionSection,
242 $editsectionContent, $wgLang->getCode() )
245 $text
247 } else {
248 $text = preg_replace( ParserOutput::EDITSECTION_REGEX, '', $text );
251 // If you have an old cached version of this class - sorry, you can't disable the TOC
252 if ( isset( $this->mTOCEnabled ) && $this->mTOCEnabled ) {
253 $text = str_replace( array( Parser::TOC_START, Parser::TOC_END ), '', $text );
254 } else {
255 $text = preg_replace(
256 '#' . preg_quote( Parser::TOC_START, '#' ) . '.*?' . preg_quote( Parser::TOC_END, '#' ) . '#s',
258 $text
261 return $text;
264 public function &getLanguageLinks() {
265 return $this->mLanguageLinks;
268 public function getInterwikiLinks() {
269 return $this->mInterwikiLinks;
272 public function getCategoryLinks() {
273 return array_keys( $this->mCategories );
276 public function &getCategories() {
277 return $this->mCategories;
281 * @since 1.25
283 public function getIndicators() {
284 return $this->mIndicators;
287 public function getTitleText() {
288 return $this->mTitleText;
291 public function getSections() {
292 return $this->mSections;
295 public function getEditSectionTokens() {
296 return $this->mEditSectionTokens;
299 public function &getLinks() {
300 return $this->mLinks;
303 public function &getTemplates() {
304 return $this->mTemplates;
307 public function &getTemplateIds() {
308 return $this->mTemplateIds;
311 public function &getImages() {
312 return $this->mImages;
315 public function &getFileSearchOptions() {
316 return $this->mFileSearchOptions;
319 public function &getExternalLinks() {
320 return $this->mExternalLinks;
323 public function getNoGallery() {
324 return $this->mNoGallery;
327 public function getHeadItems() {
328 return $this->mHeadItems;
331 public function getModules() {
332 return $this->mModules;
335 public function getModuleScripts() {
336 return $this->mModuleScripts;
339 public function getModuleStyles() {
340 return $this->mModuleStyles;
344 * @deprecated since 1.26 Obsolete
345 * @return array
347 public function getModuleMessages() {
348 wfDeprecated( __METHOD__, '1.26' );
349 return array();
352 /** @since 1.23 */
353 public function getJsConfigVars() {
354 return $this->mJsConfigVars;
357 public function getOutputHooks() {
358 return (array)$this->mOutputHooks;
361 public function getWarnings() {
362 return array_keys( $this->mWarnings );
365 public function getIndexPolicy() {
366 return $this->mIndexPolicy;
369 public function getTOCHTML() {
370 return $this->mTOCHTML;
373 public function getTimestamp() {
374 return $this->mTimestamp;
377 public function getLimitReportData() {
378 return $this->mLimitReportData;
381 public function getTOCEnabled() {
382 return $this->mTOCEnabled;
385 public function getEnableOOUI() {
386 return $this->mEnableOOUI;
389 public function setText( $text ) {
390 return wfSetVar( $this->mText, $text );
393 public function setLanguageLinks( $ll ) {
394 return wfSetVar( $this->mLanguageLinks, $ll );
397 public function setCategoryLinks( $cl ) {
398 return wfSetVar( $this->mCategories, $cl );
401 public function setTitleText( $t ) {
402 return wfSetVar( $this->mTitleText, $t );
405 public function setSections( $toc ) {
406 return wfSetVar( $this->mSections, $toc );
409 public function setEditSectionTokens( $t ) {
410 return wfSetVar( $this->mEditSectionTokens, $t );
413 public function setIndexPolicy( $policy ) {
414 return wfSetVar( $this->mIndexPolicy, $policy );
417 public function setTOCHTML( $tochtml ) {
418 return wfSetVar( $this->mTOCHTML, $tochtml );
421 public function setTimestamp( $timestamp ) {
422 return wfSetVar( $this->mTimestamp, $timestamp );
425 public function setTOCEnabled( $flag ) {
426 return wfSetVar( $this->mTOCEnabled, $flag );
429 public function addCategory( $c, $sort ) {
430 $this->mCategories[$c] = $sort;
434 * @since 1.25
436 public function setIndicator( $id, $content ) {
437 $this->mIndicators[$id] = $content;
441 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
442 * object is added to.
444 * @since 1.26
445 * @param bool $enable If OOUI should be enabled or not
447 public function setEnableOOUI( $enable = false ) {
448 $this->mEnableOOUI = $enable;
451 public function addLanguageLink( $t ) {
452 $this->mLanguageLinks[] = $t;
455 public function addWarning( $s ) {
456 $this->mWarnings[$s] = 1;
459 public function addOutputHook( $hook, $data = false ) {
460 $this->mOutputHooks[] = array( $hook, $data );
463 public function setNewSection( $value ) {
464 $this->mNewSection = (bool)$value;
466 public function hideNewSection( $value ) {
467 $this->mHideNewSection = (bool)$value;
469 public function getHideNewSection() {
470 return (bool)$this->mHideNewSection;
472 public function getNewSection() {
473 return (bool)$this->mNewSection;
477 * Checks, if a url is pointing to the own server
479 * @param string $internal The server to check against
480 * @param string $url The url to check
481 * @return bool
483 public static function isLinkInternal( $internal, $url ) {
484 return (bool)preg_match( '/^' .
485 # If server is proto relative, check also for http/https links
486 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
487 preg_quote( $internal, '/' ) .
488 # check for query/path/anchor or end of link in each case
489 '(?:[\?\/\#]|$)/i',
490 $url
494 public function addExternalLink( $url ) {
495 # We don't register links pointing to our own server, unless... :-)
496 global $wgServer, $wgRegisterInternalExternals;
498 $registerExternalLink = true;
499 if ( !$wgRegisterInternalExternals ) {
500 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
502 if ( $registerExternalLink ) {
503 $this->mExternalLinks[$url] = 1;
508 * Record a local or interwiki inline link for saving in future link tables.
510 * @param Title $title
511 * @param int|null $id Optional known page_id so we can skip the lookup
513 public function addLink( Title $title, $id = null ) {
514 if ( $title->isExternal() ) {
515 // Don't record interwikis in pagelinks
516 $this->addInterwikiLink( $title );
517 return;
519 $ns = $title->getNamespace();
520 $dbk = $title->getDBkey();
521 if ( $ns == NS_MEDIA ) {
522 // Normalize this pseudo-alias if it makes it down here...
523 $ns = NS_FILE;
524 } elseif ( $ns == NS_SPECIAL ) {
525 // We don't record Special: links currently
526 // It might actually be wise to, but we'd need to do some normalization.
527 return;
528 } elseif ( $dbk === '' ) {
529 // Don't record self links - [[#Foo]]
530 return;
532 if ( !isset( $this->mLinks[$ns] ) ) {
533 $this->mLinks[$ns] = array();
535 if ( is_null( $id ) ) {
536 $id = $title->getArticleID();
538 $this->mLinks[$ns][$dbk] = $id;
542 * Register a file dependency for this output
543 * @param string $name Title dbKey
544 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
545 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
546 * @return void
548 public function addImage( $name, $timestamp = null, $sha1 = null ) {
549 $this->mImages[$name] = 1;
550 if ( $timestamp !== null && $sha1 !== null ) {
551 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
556 * Register a template dependency for this output
557 * @param Title $title
558 * @param int $page_id
559 * @param int $rev_id
560 * @return void
562 public function addTemplate( $title, $page_id, $rev_id ) {
563 $ns = $title->getNamespace();
564 $dbk = $title->getDBkey();
565 if ( !isset( $this->mTemplates[$ns] ) ) {
566 $this->mTemplates[$ns] = array();
568 $this->mTemplates[$ns][$dbk] = $page_id;
569 if ( !isset( $this->mTemplateIds[$ns] ) ) {
570 $this->mTemplateIds[$ns] = array();
572 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
576 * @param Title $title Title object, must be an interwiki link
577 * @throws MWException If given invalid input
579 public function addInterwikiLink( $title ) {
580 if ( !$title->isExternal() ) {
581 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
583 $prefix = $title->getInterwiki();
584 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
585 $this->mInterwikiLinks[$prefix] = array();
587 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
591 * Add some text to the "<head>".
592 * If $tag is set, the section with that tag will only be included once
593 * in a given page.
594 * @param string $section
595 * @param string|bool $tag
597 public function addHeadItem( $section, $tag = false ) {
598 if ( $tag !== false ) {
599 $this->mHeadItems[$tag] = $section;
600 } else {
601 $this->mHeadItems[] = $section;
605 public function addModules( $modules ) {
606 $this->mModules = array_merge( $this->mModules, (array)$modules );
609 public function addModuleScripts( $modules ) {
610 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
613 public function addModuleStyles( $modules ) {
614 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
618 * @deprecated since 1.26 Use addModules() instead
619 * @param string|array $modules
621 public function addModuleMessages( $modules ) {
622 wfDeprecated( __METHOD__, '1.26' );
626 * Add one or more variables to be set in mw.config in JavaScript.
628 * @param string|array $keys Key or array of key/value pairs.
629 * @param mixed $value [optional] Value of the configuration variable.
630 * @since 1.23
632 public function addJsConfigVars( $keys, $value = null ) {
633 if ( is_array( $keys ) ) {
634 foreach ( $keys as $key => $value ) {
635 $this->mJsConfigVars[$key] = $value;
637 return;
640 $this->mJsConfigVars[$keys] = $value;
644 * Copy items from the OutputPage object into this one
646 * @param OutputPage $out
648 public function addOutputPageMetadata( OutputPage $out ) {
649 $this->addModules( $out->getModules() );
650 $this->addModuleScripts( $out->getModuleScripts() );
651 $this->addModuleStyles( $out->getModuleStyles() );
652 $this->addJsConfigVars( $out->getJsConfigVars() );
654 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
655 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
659 * Add a tracking category, getting the title from a system message,
660 * or print a debug message if the title is invalid.
662 * Any message used with this function should be registered so it will
663 * show up on Special:TrackingCategories. Core messages should be added
664 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
665 * should add to "TrackingCategories" in their extension.json.
667 * @param string $msg Message key
668 * @param Title $title title of the page which is being tracked
669 * @return bool Whether the addition was successful
670 * @since 1.25
672 public function addTrackingCategory( $msg, $title ) {
673 if ( $title->getNamespace() === NS_SPECIAL ) {
674 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
675 return false;
678 // Important to parse with correct title (bug 31469)
679 $cat = wfMessage( $msg )
680 ->title( $title )
681 ->inContentLanguage()
682 ->text();
684 # Allow tracking categories to be disabled by setting them to "-"
685 if ( $cat === '-' ) {
686 return false;
689 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
690 if ( $containerCategory ) {
691 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
692 return true;
693 } else {
694 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
695 return false;
700 * Override the title to be used for display
702 * @note this is assumed to have been validated
703 * (check equal normalisation, etc.)
705 * @note this is expected to be safe HTML,
706 * ready to be served to the client.
708 * @param string $text Desired title text
710 public function setDisplayTitle( $text ) {
711 $this->setTitleText( $text );
712 $this->setProperty( 'displaytitle', $text );
716 * Get the title to be used for display.
718 * As per the contract of setDisplayTitle(), this is safe HTML,
719 * ready to be served to the client.
721 * @return string HTML
723 public function getDisplayTitle() {
724 $t = $this->getTitleText();
725 if ( $t === '' ) {
726 return false;
728 return $t;
732 * Fairly generic flag setter thingy.
733 * @param string $flag
735 public function setFlag( $flag ) {
736 $this->mFlags[$flag] = true;
739 public function getFlag( $flag ) {
740 return isset( $this->mFlags[$flag] );
744 * Set a property to be stored in the page_props database table.
746 * page_props is a key value store indexed by the page ID. This allows
747 * the parser to set a property on a page which can then be quickly
748 * retrieved given the page ID or via a DB join when given the page
749 * title.
751 * Since 1.23, page_props are also indexed by numeric value, to allow
752 * for efficient "top k" queries of pages wrt a given property.
754 * setProperty() is thus used to propagate properties from the parsed
755 * page to request contexts other than a page view of the currently parsed
756 * article.
758 * Some applications examples:
760 * * To implement hidden categories, hiding pages from category listings
761 * by storing a property.
763 * * Overriding the displayed article title.
764 * @see ParserOutput::setDisplayTitle()
766 * * To implement image tagging, for example displaying an icon on an
767 * image thumbnail to indicate that it is listed for deletion on
768 * Wikimedia Commons.
769 * This is not actually implemented, yet but would be pretty cool.
771 * @note Do not use setProperty() to set a property which is only used
772 * in a context where the ParserOutput object itself is already available,
773 * for example a normal page view. There is no need to save such a property
774 * in the database since the text is already parsed. You can just hook
775 * OutputPageParserOutput and get your data out of the ParserOutput object.
777 * If you are writing an extension where you want to set a property in the
778 * parser which is used by an OutputPageParserOutput hook, you have to
779 * associate the extension data directly with the ParserOutput object.
780 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
782 * @par Example:
783 * @code
784 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
785 * @endcode
787 * And then later, in OutputPageParserOutput or similar:
789 * @par Example:
790 * @code
791 * $output->getExtensionData( 'my_ext_foo' );
792 * @endcode
794 * In MediaWiki 1.20 and older, you have to use a custom member variable
795 * within the ParserOutput object:
797 * @par Example:
798 * @code
799 * $parser->getOutput()->my_ext_foo = '...';
800 * @endcode
803 public function setProperty( $name, $value ) {
804 $this->mProperties[$name] = $value;
808 * @param string $name The property name to look up.
810 * @return mixed|bool The value previously set using setProperty(). False if null or no value
811 * was set for the given property name.
813 * @note You need to use getProperties() to check for boolean and null properties.
815 public function getProperty( $name ) {
816 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
819 public function unsetProperty( $name ) {
820 unset( $this->mProperties[$name] );
823 public function getProperties() {
824 if ( !isset( $this->mProperties ) ) {
825 $this->mProperties = array();
827 return $this->mProperties;
831 * Returns the options from its ParserOptions which have been taken
832 * into account to produce this output or false if not available.
833 * @return array
835 public function getUsedOptions() {
836 if ( !isset( $this->mAccessedOptions ) ) {
837 return array();
839 return array_keys( $this->mAccessedOptions );
843 * Tags a parser option for use in the cache key for this parser output.
844 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
845 * The information gathered here is available via getUsedOptions(),
846 * and is used by ParserCache::save().
848 * @see ParserCache::getKey
849 * @see ParserCache::save
850 * @see ParserOptions::addExtraKey
851 * @see ParserOptions::optionsHash
852 * @param string $option
854 public function recordOption( $option ) {
855 $this->mAccessedOptions[$option] = true;
859 * @deprecated since 1.25. Instead, store any relevant data using setExtensionData,
860 * and implement Content::getSecondaryDataUpdates() if possible, or use the
861 * 'SecondaryDataUpdates' hook to construct the necessary update objects.
863 * @note Hard deprecation and removal without long deprecation period, since there are no
864 * known users, but known conceptual issues.
866 * @todo remove in 1.26
868 * @param DataUpdate $update
870 * @throws MWException
872 public function addSecondaryDataUpdate( DataUpdate $update ) {
873 wfDeprecated( __METHOD__, '1.25' );
874 throw new MWException(
875 'ParserOutput::addSecondaryDataUpdate() is no longer supported. ' .
876 'Override Content::getSecondaryDataUpdates() ' .
877 'or use the SecondaryDataUpdates hook instead.'
882 * @deprecated since 1.25.
884 * @note Hard deprecation and removal without long deprecation period, since there are no
885 * known users, but known conceptual issues.
887 * @todo remove in 1.26
889 * @return bool false (since 1.25)
891 public function hasCustomDataUpdates() {
892 wfDeprecated( __METHOD__, '1.25' );
893 return false;
897 * @deprecated since 1.25. Instead, store any relevant data using setExtensionData,
898 * and implement Content::getSecondaryDataUpdates() if possible, or use the
899 * 'SecondaryDataUpdates' hook to construct the necessary update objects.
901 * @note Hard deprecation and removal without long deprecation period, since there are no
902 * known users, but known conceptual issues.
904 * @todo remove in 1.26
906 * @param Title $title
907 * @param bool $recursive
909 * @return array An array of instances of DataUpdate
911 public function getSecondaryDataUpdates( Title $title = null, $recursive = true ) {
912 wfDeprecated( __METHOD__, '1.25' );
913 return array();
917 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
918 * the ParserOutput object for later use during page output. The data will be cached along with
919 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
920 * database.
922 * This method is provided to overcome the unsafe practice of attaching extra information to a
923 * ParserObject by directly assigning member variables.
925 * To use setExtensionData() to pass extension information from a hook inside the parser to a
926 * hook in the page output, use this in the parser hook:
928 * @par Example:
929 * @code
930 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
931 * @endcode
933 * And then later, in OutputPageParserOutput or similar:
935 * @par Example:
936 * @code
937 * $output->getExtensionData( 'my_ext_foo' );
938 * @endcode
940 * In MediaWiki 1.20 and older, you have to use a custom member variable
941 * within the ParserOutput object:
943 * @par Example:
944 * @code
945 * $parser->getOutput()->my_ext_foo = '...';
946 * @endcode
948 * @since 1.21
950 * @param string $key The key for accessing the data. Extensions should take care to avoid
951 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
953 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
954 * the value.
956 public function setExtensionData( $key, $value ) {
957 if ( $value === null ) {
958 unset( $this->mExtensionData[$key] );
959 } else {
960 $this->mExtensionData[$key] = $value;
965 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
966 * Typically, such data would be set while parsing the page, e.g. by a parser function.
968 * @since 1.21
970 * @param string $key The key to look up.
972 * @return mixed|null The value previously set for the given key using setExtensionData()
973 * or null if no value was set for this key.
975 public function getExtensionData( $key ) {
976 if ( isset( $this->mExtensionData[$key] ) ) {
977 return $this->mExtensionData[$key];
980 return null;
983 private static function getTimes( $clock = null ) {
984 $ret = array();
985 if ( !$clock || $clock === 'wall' ) {
986 $ret['wall'] = microtime( true );
988 if ( !$clock || $clock === 'cpu' ) {
989 $ru = wfGetRusage();
990 if ( $ru ) {
991 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
992 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
995 return $ret;
999 * Resets the parse start timestamps for future calls to getTimeSinceStart()
1000 * @since 1.22
1002 public function resetParseStartTime() {
1003 $this->mParseStartTime = self::getTimes();
1007 * Returns the time since resetParseStartTime() was last called
1009 * Clocks available are:
1010 * - wall: Wall clock time
1011 * - cpu: CPU time (requires getrusage)
1013 * @since 1.22
1014 * @param string $clock
1015 * @return float|null
1017 public function getTimeSinceStart( $clock ) {
1018 if ( !isset( $this->mParseStartTime[$clock] ) ) {
1019 return null;
1022 $end = self::getTimes( $clock );
1023 return $end[$clock] - $this->mParseStartTime[$clock];
1027 * Sets parser limit report data for a key
1029 * The key is used as the prefix for various messages used for formatting:
1030 * - $key: The label for the field in the limit report
1031 * - $key-value-text: Message used to format the value in the "NewPP limit
1032 * report" HTML comment. If missing, uses $key-format.
1033 * - $key-value-html: Message used to format the value in the preview
1034 * limit report table. If missing, uses $key-format.
1035 * - $key-value: Message used to format the value. If missing, uses "$1".
1037 * Note that all values are interpreted as wikitext, and so should be
1038 * encoded with htmlspecialchars() as necessary, but should avoid complex
1039 * HTML for sanity of display in the "NewPP limit report" comment.
1041 * @since 1.22
1042 * @param string $key Message key
1043 * @param mixed $value Appropriate for Message::params()
1045 public function setLimitReportData( $key, $value ) {
1046 $this->mLimitReportData[$key] = $value;
1050 * Check whether the cache TTL was lowered due to dynamic content
1052 * When content is determined by more than hard state (e.g. page edits),
1053 * such as template/file transclusions based on the current timestamp or
1054 * extension tags that generate lists based on queries, this return true.
1056 * @return bool
1057 * @since 1.25
1059 public function hasDynamicContent() {
1060 global $wgParserCacheExpireTime;
1062 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1066 * Get or set the prevent-clickjacking flag
1068 * @since 1.24
1069 * @param bool|null $flag New flag value, or null to leave it unchanged
1070 * @return bool Old flag value
1072 public function preventClickjacking( $flag = null ) {
1073 return wfSetVar( $this->mPreventClickjacking, $flag );
1077 * Save space for serialization by removing useless values
1078 * @return array
1080 public function __sleep() {
1081 return array_diff(
1082 array_keys( get_object_vars( $this ) ),
1083 array( 'mParseStartTime' )