SpecialLinkSearch: clean up munged query variable handling
[mediawiki.git] / includes / parser / ParserOutput.php
blobe9e72beca8d806035d36d5ce45744b69ae1770cc
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 public $mText, # The output text
26 $mLanguageLinks, # List of the full text of language links, in the order they appear
27 $mCategories, # Map of category names to sort keys
28 $mIndicators = array(), # Page status indicators, usually displayed in top-right corner
29 $mTitleText, # title text of the chosen language variant
30 $mLinks = array(), # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
31 $mTemplates = array(), # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
32 $mTemplateIds = array(), # 2-D map of NS/DBK to rev ID for the template references. ID=zero for broken.
33 $mImages = array(), # DB keys of the images used, in the array key only
34 $mFileSearchOptions = array(), # DB keys of the images used mapped to sha1 and MW timestamp
35 $mExternalLinks = array(), # External link URLs, in the key only
36 $mInterwikiLinks = array(), # 2-D map of prefix/DBK (in keys only) for the inline interwiki links in the document.
37 $mNewSection = false, # Show a new section link?
38 $mHideNewSection = false, # Hide the new section link?
39 $mNoGallery = false, # No gallery on category page? (__NOGALLERY__)
40 $mHeadItems = array(), # Items to put in the <head> section
41 $mModules = array(), # Modules to be loaded by the resource loader
42 $mModuleScripts = array(), # Modules of which only the JS will be loaded by the resource loader
43 $mModuleStyles = array(), # Modules of which only the CSSS will be loaded by the resource loader
44 $mModuleMessages = array(), # Modules of which only the messages will be loaded by the resource loader
45 $mJsConfigVars = array(), # JavaScript config variable for mw.config combined with this page
46 $mOutputHooks = array(), # Hook tags as per $wgParserOutputHooks
47 $mWarnings = array(), # Warning text to be returned to the user. Wikitext formatted, in the key only
48 $mSections = array(), # Table of contents
49 $mEditSectionTokens = false, # prefix/suffix markers if edit sections were output as tokens
50 $mProperties = array(), # Name/value pairs to be cached in the DB
51 $mTOCHTML = '', # HTML of the TOC
52 $mTimestamp, # Timestamp of the revision
53 $mTOCEnabled = true; # Whether TOC should be shown, can't override __NOTOC__
54 private $mIndexPolicy = ''; # 'index' or 'noindex'? Any other value will result in no change.
55 private $mAccessedOptions = array(); # List of ParserOptions (stored in the keys)
56 private $mSecondaryDataUpdates = array(); # List of DataUpdate, used to save info from the page somewhere else.
57 private $mCustomDataUpdateCount = 0; # Number of custom updaters in $mSecondaryDataUpdates.
58 private $mExtensionData = array(); # extra data used by extensions
59 private $mLimitReportData = array(); # Parser limit report data
60 private $mParseStartTime = array(); # Timestamps for getTimeSinceStart()
61 private $mPreventClickjacking = false; # Whether to emit X-Frame-Options: DENY
63 const EDITSECTION_REGEX =
64 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
66 public function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
67 $containsOldMagic = false, $titletext = ''
68 ) {
69 $this->mText = $text;
70 $this->mLanguageLinks = $languageLinks;
71 $this->mCategories = $categoryLinks;
72 $this->mContainsOldMagic = $containsOldMagic;
73 $this->mTitleText = $titletext;
76 public function getText() {
77 $text = $this->mText;
78 if ( $this->mEditSectionTokens ) {
79 $text = preg_replace_callback(
80 ParserOutput::EDITSECTION_REGEX,
81 function ( $m ) {
82 global $wgOut, $wgLang;
83 $editsectionPage = Title::newFromText( htmlspecialchars_decode( $m[1] ) );
84 $editsectionSection = htmlspecialchars_decode( $m[2] );
85 $editsectionContent = isset( $m[4] ) ? $m[3] : null;
87 if ( !is_object( $editsectionPage ) ) {
88 throw new MWException( "Bad parser output text." );
91 $skin = $wgOut->getSkin();
92 return call_user_func_array(
93 array( $skin, 'doEditSectionLink' ),
94 array( $editsectionPage, $editsectionSection,
95 $editsectionContent, $wgLang->getCode() )
98 $text
100 } else {
101 $text = preg_replace( ParserOutput::EDITSECTION_REGEX, '', $text );
104 // If you have an old cached version of this class - sorry, you can't disable the TOC
105 if ( isset( $this->mTOCEnabled ) && $this->mTOCEnabled ) {
106 $text = str_replace( array( Parser::TOC_START, Parser::TOC_END ), '', $text );
107 } else {
108 $text = preg_replace(
109 '#' . preg_quote( Parser::TOC_START ) . '.*?' . preg_quote( Parser::TOC_END ) . '#s',
111 $text
114 return $text;
117 public function &getLanguageLinks() {
118 return $this->mLanguageLinks;
121 public function getInterwikiLinks() {
122 return $this->mInterwikiLinks;
125 public function getCategoryLinks() {
126 return array_keys( $this->mCategories );
129 public function &getCategories() {
130 return $this->mCategories;
134 * @since 1.25
136 public function getIndicators() {
137 return $this->mIndicators;
140 public function getTitleText() {
141 return $this->mTitleText;
144 public function getSections() {
145 return $this->mSections;
148 public function getEditSectionTokens() {
149 return $this->mEditSectionTokens;
152 public function &getLinks() {
153 return $this->mLinks;
156 public function &getTemplates() {
157 return $this->mTemplates;
160 public function &getTemplateIds() {
161 return $this->mTemplateIds;
164 public function &getImages() {
165 return $this->mImages;
168 public function &getFileSearchOptions() {
169 return $this->mFileSearchOptions;
172 public function &getExternalLinks() {
173 return $this->mExternalLinks;
176 public function getNoGallery() {
177 return $this->mNoGallery;
180 public function getHeadItems() {
181 return $this->mHeadItems;
184 public function getModules() {
185 return $this->mModules;
188 public function getModuleScripts() {
189 return $this->mModuleScripts;
192 public function getModuleStyles() {
193 return $this->mModuleStyles;
196 public function getModuleMessages() {
197 return $this->mModuleMessages;
200 /** @since 1.23 */
201 public function getJsConfigVars() {
202 return $this->mJsConfigVars;
205 public function getOutputHooks() {
206 return (array)$this->mOutputHooks;
209 public function getWarnings() {
210 return array_keys( $this->mWarnings );
213 public function getIndexPolicy() {
214 return $this->mIndexPolicy;
217 public function getTOCHTML() {
218 return $this->mTOCHTML;
221 public function getTimestamp() {
222 return $this->mTimestamp;
225 public function getLimitReportData() {
226 return $this->mLimitReportData;
229 public function getTOCEnabled() {
230 return $this->mTOCEnabled;
233 public function setText( $text ) {
234 return wfSetVar( $this->mText, $text );
237 public function setLanguageLinks( $ll ) {
238 return wfSetVar( $this->mLanguageLinks, $ll );
241 public function setCategoryLinks( $cl ) {
242 return wfSetVar( $this->mCategories, $cl );
245 public function setTitleText( $t ) {
246 return wfSetVar( $this->mTitleText, $t );
249 public function setSections( $toc ) {
250 return wfSetVar( $this->mSections, $toc );
253 public function setEditSectionTokens( $t ) {
254 return wfSetVar( $this->mEditSectionTokens, $t );
257 public function setIndexPolicy( $policy ) {
258 return wfSetVar( $this->mIndexPolicy, $policy );
261 public function setTOCHTML( $tochtml ) {
262 return wfSetVar( $this->mTOCHTML, $tochtml );
265 public function setTimestamp( $timestamp ) {
266 return wfSetVar( $this->mTimestamp, $timestamp );
269 public function setTOCEnabled( $flag ) {
270 return wfSetVar( $this->mTOCEnabled, $flag );
273 public function addCategory( $c, $sort ) {
274 $this->mCategories[$c] = $sort;
278 * @since 1.25
280 public function setIndicator( $id, $content ) {
281 $this->mIndicators[$id] = $content;
284 public function addLanguageLink( $t ) {
285 $this->mLanguageLinks[] = $t;
288 public function addWarning( $s ) {
289 $this->mWarnings[$s] = 1;
292 public function addOutputHook( $hook, $data = false ) {
293 $this->mOutputHooks[] = array( $hook, $data );
296 public function setNewSection( $value ) {
297 $this->mNewSection = (bool)$value;
299 public function hideNewSection( $value ) {
300 $this->mHideNewSection = (bool)$value;
302 public function getHideNewSection() {
303 return (bool)$this->mHideNewSection;
305 public function getNewSection() {
306 return (bool)$this->mNewSection;
310 * Checks, if a url is pointing to the own server
312 * @param string $internal The server to check against
313 * @param string $url The url to check
314 * @return bool
316 public static function isLinkInternal( $internal, $url ) {
317 return (bool)preg_match( '/^' .
318 # If server is proto relative, check also for http/https links
319 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
320 preg_quote( $internal, '/' ) .
321 # check for query/path/anchor or end of link in each case
322 '(?:[\?\/\#]|$)/i',
323 $url
327 public function addExternalLink( $url ) {
328 # We don't register links pointing to our own server, unless... :-)
329 global $wgServer, $wgRegisterInternalExternals;
331 $registerExternalLink = true;
332 if ( !$wgRegisterInternalExternals ) {
333 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
335 if ( $registerExternalLink ) {
336 $this->mExternalLinks[$url] = 1;
341 * Record a local or interwiki inline link for saving in future link tables.
343 * @param Title $title
344 * @param int|null $id Optional known page_id so we can skip the lookup
346 public function addLink( Title $title, $id = null ) {
347 if ( $title->isExternal() ) {
348 // Don't record interwikis in pagelinks
349 $this->addInterwikiLink( $title );
350 return;
352 $ns = $title->getNamespace();
353 $dbk = $title->getDBkey();
354 if ( $ns == NS_MEDIA ) {
355 // Normalize this pseudo-alias if it makes it down here...
356 $ns = NS_FILE;
357 } elseif ( $ns == NS_SPECIAL ) {
358 // We don't record Special: links currently
359 // It might actually be wise to, but we'd need to do some normalization.
360 return;
361 } elseif ( $dbk === '' ) {
362 // Don't record self links - [[#Foo]]
363 return;
365 if ( !isset( $this->mLinks[$ns] ) ) {
366 $this->mLinks[$ns] = array();
368 if ( is_null( $id ) ) {
369 $id = $title->getArticleID();
371 $this->mLinks[$ns][$dbk] = $id;
375 * Register a file dependency for this output
376 * @param string $name Title dbKey
377 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
378 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
379 * @return void
381 public function addImage( $name, $timestamp = null, $sha1 = null ) {
382 $this->mImages[$name] = 1;
383 if ( $timestamp !== null && $sha1 !== null ) {
384 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
389 * Register a template dependency for this output
390 * @param Title $title
391 * @param int $page_id
392 * @param int $rev_id
393 * @return void
395 public function addTemplate( $title, $page_id, $rev_id ) {
396 $ns = $title->getNamespace();
397 $dbk = $title->getDBkey();
398 if ( !isset( $this->mTemplates[$ns] ) ) {
399 $this->mTemplates[$ns] = array();
401 $this->mTemplates[$ns][$dbk] = $page_id;
402 if ( !isset( $this->mTemplateIds[$ns] ) ) {
403 $this->mTemplateIds[$ns] = array();
405 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
409 * @param Title $title Title object, must be an interwiki link
410 * @throws MWException If given invalid input
412 public function addInterwikiLink( $title ) {
413 if ( !$title->isExternal() ) {
414 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
416 $prefix = $title->getInterwiki();
417 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
418 $this->mInterwikiLinks[$prefix] = array();
420 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
424 * Add some text to the "<head>".
425 * If $tag is set, the section with that tag will only be included once
426 * in a given page.
427 * @param string $section
428 * @param string|bool $tag
430 public function addHeadItem( $section, $tag = false ) {
431 if ( $tag !== false ) {
432 $this->mHeadItems[$tag] = $section;
433 } else {
434 $this->mHeadItems[] = $section;
438 public function addModules( $modules ) {
439 $this->mModules = array_merge( $this->mModules, (array)$modules );
442 public function addModuleScripts( $modules ) {
443 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
446 public function addModuleStyles( $modules ) {
447 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
450 public function addModuleMessages( $modules ) {
451 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
455 * Add one or more variables to be set in mw.config in JavaScript.
457 * @param string|array $keys Key or array of key/value pairs.
458 * @param mixed $value [optional] Value of the configuration variable.
459 * @since 1.23
461 public function addJsConfigVars( $keys, $value = null ) {
462 if ( is_array( $keys ) ) {
463 foreach ( $keys as $key => $value ) {
464 $this->mJsConfigVars[$key] = $value;
466 return;
469 $this->mJsConfigVars[$keys] = $value;
473 * Copy items from the OutputPage object into this one
475 * @param OutputPage $out
477 public function addOutputPageMetadata( OutputPage $out ) {
478 $this->addModules( $out->getModules() );
479 $this->addModuleScripts( $out->getModuleScripts() );
480 $this->addModuleStyles( $out->getModuleStyles() );
481 $this->addModuleMessages( $out->getModuleMessages() );
482 $this->addJsConfigVars( $out->getJsConfigVars() );
484 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
485 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
489 * Add a tracking category, getting the title from a system message,
490 * or print a debug message if the title is invalid.
492 * Any message used with this function should be registered so it will
493 * show up on Special:TrackingCategories. Core messages should be added
494 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
495 * should add to "TrackingCategories" in their extension.json.
497 * @param string $msg Message key
498 * @param Title $title title of the page which is being tracked
499 * @return bool Whether the addition was successful
500 * @since 1.25
502 public function addTrackingCategory( $msg, $title ) {
503 if ( $title->getNamespace() === NS_SPECIAL ) {
504 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
505 return false;
508 // Important to parse with correct title (bug 31469)
509 $cat = wfMessage( $msg )
510 ->title( $title )
511 ->inContentLanguage()
512 ->text();
514 # Allow tracking categories to be disabled by setting them to "-"
515 if ( $cat === '-' ) {
516 return false;
519 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
520 if ( $containerCategory ) {
521 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
522 return true;
523 } else {
524 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
525 return false;
530 * Override the title to be used for display
531 * -- this is assumed to have been validated
532 * (check equal normalisation, etc.)
534 * @param string $text Desired title text
536 public function setDisplayTitle( $text ) {
537 $this->setTitleText( $text );
538 $this->setProperty( 'displaytitle', $text );
542 * Get the title to be used for display
544 * @return string
546 public function getDisplayTitle() {
547 $t = $this->getTitleText();
548 if ( $t === '' ) {
549 return false;
551 return $t;
555 * Fairly generic flag setter thingy.
556 * @param string $flag
558 public function setFlag( $flag ) {
559 $this->mFlags[$flag] = true;
562 public function getFlag( $flag ) {
563 return isset( $this->mFlags[$flag] );
567 * Set a property to be stored in the page_props database table.
569 * page_props is a key value store indexed by the page ID. This allows
570 * the parser to set a property on a page which can then be quickly
571 * retrieved given the page ID or via a DB join when given the page
572 * title.
574 * Since 1.23, page_props are also indexed by numeric value, to allow
575 * for efficient "top k" queries of pages wrt a given property.
577 * setProperty() is thus used to propagate properties from the parsed
578 * page to request contexts other than a page view of the currently parsed
579 * article.
581 * Some applications examples:
583 * * To implement hidden categories, hiding pages from category listings
584 * by storing a property.
586 * * Overriding the displayed article title.
587 * @see ParserOutput::setDisplayTitle()
589 * * To implement image tagging, for example displaying an icon on an
590 * image thumbnail to indicate that it is listed for deletion on
591 * Wikimedia Commons.
592 * This is not actually implemented, yet but would be pretty cool.
594 * @note Do not use setProperty() to set a property which is only used
595 * in a context where the ParserOutput object itself is already available,
596 * for example a normal page view. There is no need to save such a property
597 * in the database since the text is already parsed. You can just hook
598 * OutputPageParserOutput and get your data out of the ParserOutput object.
600 * If you are writing an extension where you want to set a property in the
601 * parser which is used by an OutputPageParserOutput hook, you have to
602 * associate the extension data directly with the ParserOutput object.
603 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
605 * @par Example:
606 * @code
607 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
608 * @endcode
610 * And then later, in OutputPageParserOutput or similar:
612 * @par Example:
613 * @code
614 * $output->getExtensionData( 'my_ext_foo' );
615 * @endcode
617 * In MediaWiki 1.20 and older, you have to use a custom member variable
618 * within the ParserOutput object:
620 * @par Example:
621 * @code
622 * $parser->getOutput()->my_ext_foo = '...';
623 * @endcode
626 public function setProperty( $name, $value ) {
627 $this->mProperties[$name] = $value;
631 * @param string $name The property name to look up.
633 * @return mixed|bool The value previously set using setProperty(). False if null or no value
634 * was set for the given property name.
636 * @note You need to use getProperties() to check for boolean and null properties.
638 public function getProperty( $name ) {
639 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
642 public function unsetProperty( $name ) {
643 unset( $this->mProperties[$name] );
646 public function getProperties() {
647 if ( !isset( $this->mProperties ) ) {
648 $this->mProperties = array();
650 return $this->mProperties;
654 * Returns the options from its ParserOptions which have been taken
655 * into account to produce this output or false if not available.
656 * @return array
658 public function getUsedOptions() {
659 if ( !isset( $this->mAccessedOptions ) ) {
660 return array();
662 return array_keys( $this->mAccessedOptions );
666 * Tags a parser option for use in the cache key for this parser output.
667 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
669 * @see ParserCache::getKey
670 * @see ParserCache::save
671 * @see ParserOptions::addExtraKey
672 * @see ParserOptions::optionsHash
673 * @param string $option
675 public function recordOption( $option ) {
676 $this->mAccessedOptions[$option] = true;
680 * Adds an update job to the output. Any update jobs added to the output will
681 * eventually be executed in order to store any secondary information extracted
682 * from the page's content. This is triggered by calling getSecondaryDataUpdates()
683 * and is used for forward links updates on edit and backlink updates by jobs.
685 * @note: custom DataUpdates do not survive serialization of the ParserOutput!
686 * This is especially relevant when using a cached ParserOutput for updating
687 * the database, as WikiPage does if $wgAjaxStashEdit is enabled. For this
688 * reason, ApiStashEdit will skip any ParserOutput that has custom DataUpdates.
690 * @since 1.20
692 * @param DataUpdate $update
694 public function addSecondaryDataUpdate( DataUpdate $update ) {
695 $this->mSecondaryDataUpdates[] = $update;
696 $this->mCustomDataUpdateCount = count( $this->mSecondaryDataUpdates );
700 * Whether this ParserOutput contains custom DataUpdate objects that may not survive
701 * serialization of the ParserOutput.
703 * @see __sleep()
705 * @return bool
707 public function hasCustomDataUpdates() {
708 return ( $this->mCustomDataUpdateCount > 0 );
712 * Returns any DataUpdate jobs to be executed in order to store secondary information
713 * extracted from the page's content, including a LinksUpdate object for all links stored in
714 * this ParserOutput object.
716 * @note Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates()
717 * instead! The content handler may provide additional update objects.
719 * @since 1.20
721 * @param Title $title The title of the page we're updating. If not given, a title object will
722 * be created based on $this->getTitleText()
723 * @param bool $recursive Queue jobs for recursive updates?
725 * @throws MWException if called on a ParserOutput instance that was restored from serialization.
726 * DataUpdates are generally not serializable, so after serialization, they are undefined.
728 * @return array An array of instances of DataUpdate
730 public function getSecondaryDataUpdates( Title $title = null, $recursive = true ) {
731 if ( is_null( $title ) ) {
732 $title = Title::newFromText( $this->getTitleText() );
735 if ( count( $this->mSecondaryDataUpdates ) !== $this->mCustomDataUpdateCount ) {
736 // NOTE: This happens when mSecondaryDataUpdates are lost during serialization
737 // (see __sleep below). After (un)serialization, getSecondaryDataUpdates()
738 // has no defined behavior in that case, and should throw an exception.
739 throw new MWException( 'getSecondaryDataUpdates() must not be called on ParserOutput restored from serialization.' );
742 // NOTE: ApiStashEdit knows about this "magic" update object. If this goes away,
743 // ApiStashEdit::buildStashValue needs to be adjusted.
744 $linksUpdate = new LinksUpdate( $title, $this, $recursive );
746 return array_merge( $this->mSecondaryDataUpdates, array( $linksUpdate ) );
750 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
751 * the ParserOutput object for later use during page output. The data will be cached along with
752 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
753 * database.
755 * This method is provided to overcome the unsafe practice of attaching extra information to a
756 * ParserObject by directly assigning member variables.
758 * To use setExtensionData() to pass extension information from a hook inside the parser to a
759 * hook in the page output, use this in the parser hook:
761 * @par Example:
762 * @code
763 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
764 * @endcode
766 * And then later, in OutputPageParserOutput or similar:
768 * @par Example:
769 * @code
770 * $output->getExtensionData( 'my_ext_foo' );
771 * @endcode
773 * In MediaWiki 1.20 and older, you have to use a custom member variable
774 * within the ParserOutput object:
776 * @par Example:
777 * @code
778 * $parser->getOutput()->my_ext_foo = '...';
779 * @endcode
781 * @since 1.21
783 * @param string $key The key for accessing the data. Extensions should take care to avoid
784 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
786 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
787 * the value.
789 public function setExtensionData( $key, $value ) {
790 if ( $value === null ) {
791 unset( $this->mExtensionData[$key] );
792 } else {
793 $this->mExtensionData[$key] = $value;
798 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
799 * Typically, such data would be set while parsing the page, e.g. by a parser function.
801 * @since 1.21
803 * @param string $key The key to look up.
805 * @return mixed|null The value previously set for the given key using setExtensionData()
806 * or null if no value was set for this key.
808 public function getExtensionData( $key ) {
809 if ( isset( $this->mExtensionData[$key] ) ) {
810 return $this->mExtensionData[$key];
813 return null;
816 private static function getTimes( $clock = null ) {
817 $ret = array();
818 if ( !$clock || $clock === 'wall' ) {
819 $ret['wall'] = microtime( true );
821 if ( !$clock || $clock === 'cpu' ) {
822 $ru = wfGetRusage();
823 if ( $ru ) {
824 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
825 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
828 return $ret;
832 * Resets the parse start timestamps for future calls to getTimeSinceStart()
833 * @since 1.22
835 public function resetParseStartTime() {
836 $this->mParseStartTime = self::getTimes();
840 * Returns the time since resetParseStartTime() was last called
842 * Clocks available are:
843 * - wall: Wall clock time
844 * - cpu: CPU time (requires getrusage)
846 * @since 1.22
847 * @param string $clock
848 * @return float|null
850 public function getTimeSinceStart( $clock ) {
851 if ( !isset( $this->mParseStartTime[$clock] ) ) {
852 return null;
855 $end = self::getTimes( $clock );
856 return $end[$clock] - $this->mParseStartTime[$clock];
860 * Sets parser limit report data for a key
862 * The key is used as the prefix for various messages used for formatting:
863 * - $key: The label for the field in the limit report
864 * - $key-value-text: Message used to format the value in the "NewPP limit
865 * report" HTML comment. If missing, uses $key-format.
866 * - $key-value-html: Message used to format the value in the preview
867 * limit report table. If missing, uses $key-format.
868 * - $key-value: Message used to format the value. If missing, uses "$1".
870 * Note that all values are interpreted as wikitext, and so should be
871 * encoded with htmlspecialchars() as necessary, but should avoid complex
872 * HTML for sanity of display in the "NewPP limit report" comment.
874 * @since 1.22
875 * @param string $key Message key
876 * @param mixed $value Appropriate for Message::params()
878 public function setLimitReportData( $key, $value ) {
879 $this->mLimitReportData[$key] = $value;
883 * Get or set the prevent-clickjacking flag
885 * @since 1.24
886 * @param bool|null $flag New flag value, or null to leave it unchanged
887 * @return bool Old flag value
889 public function preventClickjacking( $flag = null ) {
890 return wfSetVar( $this->mPreventClickjacking, $flag );
894 * Save space for serialization by removing useless values
895 * @return array
897 public function __sleep() {
898 return array_diff(
899 array_keys( get_object_vars( $this ) ),
900 array( 'mSecondaryDataUpdates', 'mParseStartTime' )