Merge "Improve GlobalVarConfigTest"
[lhc/web/wiklou.git] / includes / parser / ParserOutput.php
1 <?php
2
3 /**
4 * Output of the PHP parser.
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @ingroup Parser
23 */
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 $mTitleText, # title text of the chosen language variant
29 $mLinks = array(), # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
30 $mTemplates = array(), # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
31 $mTemplateIds = array(), # 2-D map of NS/DBK to rev ID for the template references. ID=zero for broken.
32 $mImages = array(), # DB keys of the images used, in the array key only
33 $mFileSearchOptions = array(), # DB keys of the images used mapped to sha1 and MW timestamp
34 $mExternalLinks = array(), # External link URLs, in the key only
35 $mInterwikiLinks = array(), # 2-D map of prefix/DBK (in keys only) for the inline interwiki links in the document.
36 $mNewSection = false, # Show a new section link?
37 $mHideNewSection = false, # Hide the new section link?
38 $mNoGallery = false, # No gallery on category page? (__NOGALLERY__)
39 $mHeadItems = array(), # Items to put in the <head> section
40 $mModules = array(), # Modules to be loaded by the resource loader
41 $mModuleScripts = array(), # Modules of which only the JS will be loaded by the resource loader
42 $mModuleStyles = array(), # Modules of which only the CSSS will be loaded by the resource loader
43 $mModuleMessages = array(), # Modules of which only the messages will be loaded by the resource loader
44 $mJsConfigVars = array(), # JavaScript config variable for mw.config combined with this page
45 $mOutputHooks = array(), # Hook tags as per $wgParserOutputHooks
46 $mWarnings = array(), # Warning text to be returned to the user. Wikitext formatted, in the key only
47 $mSections = array(), # Table of contents
48 $mEditSectionTokens = false, # prefix/suffix markers if edit sections were output as tokens
49 $mProperties = array(), # Name/value pairs to be cached in the DB
50 $mTOCHTML = '', # HTML of the TOC
51 $mTimestamp, # Timestamp of the revision
52 $mTOCEnabled = true; # Whether TOC should be shown, can't override __NOTOC__
53 private $mIndexPolicy = ''; # 'index' or 'noindex'? Any other value will result in no change.
54 private $mAccessedOptions = array(); # List of ParserOptions (stored in the keys)
55 private $mSecondaryDataUpdates = array(); # List of DataUpdate, used to save info from the page somewhere else.
56 private $mExtensionData = array(); # extra data used by extensions
57 private $mLimitReportData = array(); # Parser limit report data
58 private $mParseStartTime = array(); # Timestamps for getTimeSinceStart()
59 private $mPreventClickjacking = false; # Whether to emit X-Frame-Options: DENY
60
61 const EDITSECTION_REGEX =
62 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
63
64 public function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
65 $containsOldMagic = false, $titletext = ''
66 ) {
67 $this->mText = $text;
68 $this->mLanguageLinks = $languageLinks;
69 $this->mCategories = $categoryLinks;
70 $this->mContainsOldMagic = $containsOldMagic;
71 $this->mTitleText = $titletext;
72 }
73
74 public function getText() {
75 wfProfileIn( __METHOD__ );
76 $text = $this->mText;
77 if ( $this->mEditSectionTokens ) {
78 $text = preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
79 array( &$this, 'replaceEditSectionLinksCallback' ), $text );
80 } else {
81 $text = preg_replace( ParserOutput::EDITSECTION_REGEX, '', $text );
82 }
83
84 // If you have an old cached version of this class - sorry, you can't disable the TOC
85 if ( isset( $this->mTOCEnabled ) && $this->mTOCEnabled ) {
86 $text = str_replace( array( Parser::TOC_START, Parser::TOC_END ), '', $text );
87 } else {
88 $text = preg_replace(
89 '#' . preg_quote( Parser::TOC_START ) . '.*?' . preg_quote( Parser::TOC_END ) . '#s',
90 '',
91 $text
92 );
93 }
94 wfProfileOut( __METHOD__ );
95 return $text;
96 }
97
98 /**
99 * callback used by getText to replace editsection tokens
100 * @private
101 * @param array $m
102 * @throws MWException
103 * @return mixed
104 */
105 public function replaceEditSectionLinksCallback( $m ) {
106 global $wgOut, $wgLang;
107 $args = array(
108 htmlspecialchars_decode( $m[1] ),
109 htmlspecialchars_decode( $m[2] ),
110 isset( $m[4] ) ? $m[3] : null,
111 );
112 $args[0] = Title::newFromText( $args[0] );
113 if ( !is_object( $args[0] ) ) {
114 throw new MWException( "Bad parser output text." );
115 }
116 $args[] = $wgLang->getCode();
117 $skin = $wgOut->getSkin();
118 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
119 }
120
121 public function &getLanguageLinks() {
122 return $this->mLanguageLinks;
123 }
124
125 public function getInterwikiLinks() {
126 return $this->mInterwikiLinks;
127 }
128
129 public function getCategoryLinks() {
130 return array_keys( $this->mCategories );
131 }
132
133 public function &getCategories() {
134 return $this->mCategories;
135 }
136
137 public function getTitleText() {
138 return $this->mTitleText;
139 }
140
141 public function getSections() {
142 return $this->mSections;
143 }
144
145 public function getEditSectionTokens() {
146 return $this->mEditSectionTokens;
147 }
148
149 public function &getLinks() {
150 return $this->mLinks;
151 }
152
153 public function &getTemplates() {
154 return $this->mTemplates;
155 }
156
157 public function &getTemplateIds() {
158 return $this->mTemplateIds;
159 }
160
161 public function &getImages() {
162 return $this->mImages;
163 }
164
165 public function &getFileSearchOptions() {
166 return $this->mFileSearchOptions;
167 }
168
169 public function &getExternalLinks() {
170 return $this->mExternalLinks;
171 }
172
173 public function getNoGallery() {
174 return $this->mNoGallery;
175 }
176
177 public function getHeadItems() {
178 return $this->mHeadItems;
179 }
180
181 public function getModules() {
182 return $this->mModules;
183 }
184
185 public function getModuleScripts() {
186 return $this->mModuleScripts;
187 }
188
189 public function getModuleStyles() {
190 return $this->mModuleStyles;
191 }
192
193 public function getModuleMessages() {
194 return $this->mModuleMessages;
195 }
196
197 /** @since 1.23 */
198 public function getJsConfigVars() {
199 return $this->mJsConfigVars;
200 }
201
202 public function getOutputHooks() {
203 return (array)$this->mOutputHooks;
204 }
205
206 public function getWarnings() {
207 return array_keys( $this->mWarnings );
208 }
209
210 public function getIndexPolicy() {
211 return $this->mIndexPolicy;
212 }
213
214 public function getTOCHTML() {
215 return $this->mTOCHTML;
216 }
217
218 public function getTimestamp() {
219 return $this->mTimestamp;
220 }
221
222 public function getLimitReportData() {
223 return $this->mLimitReportData;
224 }
225
226 public function getTOCEnabled() {
227 return $this->mTOCEnabled;
228 }
229
230 public function setText( $text ) {
231 return wfSetVar( $this->mText, $text );
232 }
233
234 public function setLanguageLinks( $ll ) {
235 return wfSetVar( $this->mLanguageLinks, $ll );
236 }
237
238 public function setCategoryLinks( $cl ) {
239 return wfSetVar( $this->mCategories, $cl );
240 }
241
242 public function setTitleText( $t ) {
243 return wfSetVar( $this->mTitleText, $t );
244 }
245
246 public function setSections( $toc ) {
247 return wfSetVar( $this->mSections, $toc );
248 }
249
250 public function setEditSectionTokens( $t ) {
251 return wfSetVar( $this->mEditSectionTokens, $t );
252 }
253
254 public function setIndexPolicy( $policy ) {
255 return wfSetVar( $this->mIndexPolicy, $policy );
256 }
257
258 public function setTOCHTML( $tochtml ) {
259 return wfSetVar( $this->mTOCHTML, $tochtml );
260 }
261
262 public function setTimestamp( $timestamp ) {
263 return wfSetVar( $this->mTimestamp, $timestamp );
264 }
265
266 public function setTOCEnabled( $flag ) {
267 return wfSetVar( $this->mTOCEnabled, $flag );
268 }
269
270 public function addCategory( $c, $sort ) {
271 $this->mCategories[$c] = $sort;
272 }
273
274 public function addLanguageLink( $t ) {
275 $this->mLanguageLinks[] = $t;
276 }
277
278 public function addWarning( $s ) {
279 $this->mWarnings[$s] = 1;
280 }
281
282 public function addOutputHook( $hook, $data = false ) {
283 $this->mOutputHooks[] = array( $hook, $data );
284 }
285
286 public function setNewSection( $value ) {
287 $this->mNewSection = (bool)$value;
288 }
289 public function hideNewSection( $value ) {
290 $this->mHideNewSection = (bool)$value;
291 }
292 public function getHideNewSection() {
293 return (bool)$this->mHideNewSection;
294 }
295 public function getNewSection() {
296 return (bool)$this->mNewSection;
297 }
298
299 /**
300 * Checks, if a url is pointing to the own server
301 *
302 * @param string $internal The server to check against
303 * @param string $url The url to check
304 * @return bool
305 */
306 public static function isLinkInternal( $internal, $url ) {
307 return (bool)preg_match( '/^' .
308 # If server is proto relative, check also for http/https links
309 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
310 preg_quote( $internal, '/' ) .
311 # check for query/path/anchor or end of link in each case
312 '(?:[\?\/\#]|$)/i',
313 $url
314 );
315 }
316
317 public function addExternalLink( $url ) {
318 # We don't register links pointing to our own server, unless... :-)
319 global $wgServer, $wgRegisterInternalExternals;
320
321 $registerExternalLink = true;
322 if ( !$wgRegisterInternalExternals ) {
323 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
324 }
325 if ( $registerExternalLink ) {
326 $this->mExternalLinks[$url] = 1;
327 }
328 }
329
330 /**
331 * Record a local or interwiki inline link for saving in future link tables.
332 *
333 * @param Title $title
334 * @param int|null $id Optional known page_id so we can skip the lookup
335 */
336 public function addLink( Title $title, $id = null ) {
337 if ( $title->isExternal() ) {
338 // Don't record interwikis in pagelinks
339 $this->addInterwikiLink( $title );
340 return;
341 }
342 $ns = $title->getNamespace();
343 $dbk = $title->getDBkey();
344 if ( $ns == NS_MEDIA ) {
345 // Normalize this pseudo-alias if it makes it down here...
346 $ns = NS_FILE;
347 } elseif ( $ns == NS_SPECIAL ) {
348 // We don't record Special: links currently
349 // It might actually be wise to, but we'd need to do some normalization.
350 return;
351 } elseif ( $dbk === '' ) {
352 // Don't record self links - [[#Foo]]
353 return;
354 }
355 if ( !isset( $this->mLinks[$ns] ) ) {
356 $this->mLinks[$ns] = array();
357 }
358 if ( is_null( $id ) ) {
359 $id = $title->getArticleID();
360 }
361 $this->mLinks[$ns][$dbk] = $id;
362 }
363
364 /**
365 * Register a file dependency for this output
366 * @param string $name Title dbKey
367 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
368 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
369 * @return void
370 */
371 public function addImage( $name, $timestamp = null, $sha1 = null ) {
372 $this->mImages[$name] = 1;
373 if ( $timestamp !== null && $sha1 !== null ) {
374 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
375 }
376 }
377
378 /**
379 * Register a template dependency for this output
380 * @param Title $title
381 * @param int $page_id
382 * @param int $rev_id
383 * @return void
384 */
385 public function addTemplate( $title, $page_id, $rev_id ) {
386 $ns = $title->getNamespace();
387 $dbk = $title->getDBkey();
388 if ( !isset( $this->mTemplates[$ns] ) ) {
389 $this->mTemplates[$ns] = array();
390 }
391 $this->mTemplates[$ns][$dbk] = $page_id;
392 if ( !isset( $this->mTemplateIds[$ns] ) ) {
393 $this->mTemplateIds[$ns] = array();
394 }
395 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
396 }
397
398 /**
399 * @param Title $title Title object, must be an interwiki link
400 * @throws MWException If given invalid input
401 */
402 public function addInterwikiLink( $title ) {
403 if ( !$title->isExternal() ) {
404 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
405 }
406 $prefix = $title->getInterwiki();
407 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
408 $this->mInterwikiLinks[$prefix] = array();
409 }
410 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
411 }
412
413 /**
414 * Add some text to the "<head>".
415 * If $tag is set, the section with that tag will only be included once
416 * in a given page.
417 * @param string $section
418 * @param string|bool $tag
419 */
420 public function addHeadItem( $section, $tag = false ) {
421 if ( $tag !== false ) {
422 $this->mHeadItems[$tag] = $section;
423 } else {
424 $this->mHeadItems[] = $section;
425 }
426 }
427
428 public function addModules( $modules ) {
429 $this->mModules = array_merge( $this->mModules, (array)$modules );
430 }
431
432 public function addModuleScripts( $modules ) {
433 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
434 }
435
436 public function addModuleStyles( $modules ) {
437 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
438 }
439
440 public function addModuleMessages( $modules ) {
441 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
442 }
443
444 /**
445 * Add one or more variables to be set in mw.config in JavaScript.
446 *
447 * @param string|array $keys Key or array of key/value pairs.
448 * @param mixed $value [optional] Value of the configuration variable.
449 * @since 1.23
450 */
451 public function addJsConfigVars( $keys, $value = null ) {
452 if ( is_array( $keys ) ) {
453 foreach ( $keys as $key => $value ) {
454 $this->mJsConfigVars[$key] = $value;
455 }
456 return;
457 }
458
459 $this->mJsConfigVars[$keys] = $value;
460 }
461
462 /**
463 * Copy items from the OutputPage object into this one
464 *
465 * @param OutputPage $out
466 */
467 public function addOutputPageMetadata( OutputPage $out ) {
468 $this->addModules( $out->getModules() );
469 $this->addModuleScripts( $out->getModuleScripts() );
470 $this->addModuleStyles( $out->getModuleStyles() );
471 $this->addModuleMessages( $out->getModuleMessages() );
472 $this->addJsConfigVars( $out->getJsConfigVars() );
473
474 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
475 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
476 }
477
478 /**
479 * Override the title to be used for display
480 * -- this is assumed to have been validated
481 * (check equal normalisation, etc.)
482 *
483 * @param string $text Desired title text
484 */
485 public function setDisplayTitle( $text ) {
486 $this->setTitleText( $text );
487 $this->setProperty( 'displaytitle', $text );
488 }
489
490 /**
491 * Get the title to be used for display
492 *
493 * @return string
494 */
495 public function getDisplayTitle() {
496 $t = $this->getTitleText();
497 if ( $t === '' ) {
498 return false;
499 }
500 return $t;
501 }
502
503 /**
504 * Fairly generic flag setter thingy.
505 * @param string $flag
506 */
507 public function setFlag( $flag ) {
508 $this->mFlags[$flag] = true;
509 }
510
511 public function getFlag( $flag ) {
512 return isset( $this->mFlags[$flag] );
513 }
514
515 /**
516 * Set a property to be stored in the page_props database table.
517 *
518 * page_props is a key value store indexed by the page ID. This allows
519 * the parser to set a property on a page which can then be quickly
520 * retrieved given the page ID or via a DB join when given the page
521 * title.
522 *
523 * Since 1.23, page_props are also indexed by numeric value, to allow
524 * for efficient "top k" queries of pages wrt a given property.
525 *
526 * setProperty() is thus used to propagate properties from the parsed
527 * page to request contexts other than a page view of the currently parsed
528 * article.
529 *
530 * Some applications examples:
531 *
532 * * To implement hidden categories, hiding pages from category listings
533 * by storing a property.
534 *
535 * * Overriding the displayed article title.
536 * @see ParserOutput::setDisplayTitle()
537 *
538 * * To implement image tagging, for example displaying an icon on an
539 * image thumbnail to indicate that it is listed for deletion on
540 * Wikimedia Commons.
541 * This is not actually implemented, yet but would be pretty cool.
542 *
543 * @note Do not use setProperty() to set a property which is only used
544 * in a context where the ParserOutput object itself is already available,
545 * for example a normal page view. There is no need to save such a property
546 * in the database since the text is already parsed. You can just hook
547 * OutputPageParserOutput and get your data out of the ParserOutput object.
548 *
549 * If you are writing an extension where you want to set a property in the
550 * parser which is used by an OutputPageParserOutput hook, you have to
551 * associate the extension data directly with the ParserOutput object.
552 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
553 *
554 * @par Example:
555 * @code
556 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
557 * @endcode
558 *
559 * And then later, in OutputPageParserOutput or similar:
560 *
561 * @par Example:
562 * @code
563 * $output->getExtensionData( 'my_ext_foo' );
564 * @endcode
565 *
566 * In MediaWiki 1.20 and older, you have to use a custom member variable
567 * within the ParserOutput object:
568 *
569 * @par Example:
570 * @code
571 * $parser->getOutput()->my_ext_foo = '...';
572 * @endcode
573 *
574 */
575 public function setProperty( $name, $value ) {
576 $this->mProperties[$name] = $value;
577 }
578
579 /**
580 * @param string $name The property name to look up.
581 *
582 * @return mixed|bool The value previously set using setProperty(). False if null or no value
583 * was set for the given property name.
584 *
585 * @note You need to use getProperties() to check for boolean and null properties.
586 */
587 public function getProperty( $name ) {
588 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
589 }
590
591 public function unsetProperty( $name ) {
592 unset( $this->mProperties[$name] );
593 }
594
595 public function getProperties() {
596 if ( !isset( $this->mProperties ) ) {
597 $this->mProperties = array();
598 }
599 return $this->mProperties;
600 }
601
602 /**
603 * Returns the options from its ParserOptions which have been taken
604 * into account to produce this output or false if not available.
605 * @return array
606 */
607 public function getUsedOptions() {
608 if ( !isset( $this->mAccessedOptions ) ) {
609 return array();
610 }
611 return array_keys( $this->mAccessedOptions );
612 }
613
614 /**
615 * Tags a parser option for use in the cache key for this parser output.
616 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
617 *
618 * @see ParserCache::getKey
619 * @see ParserCache::save
620 * @see ParserOptions::addExtraKey
621 * @see ParserOptions::optionsHash
622 * @param string $option
623 */
624 public function recordOption( $option ) {
625 $this->mAccessedOptions[$option] = true;
626 }
627
628 /**
629 * Adds an update job to the output. Any update jobs added to the output will
630 * eventually be executed in order to store any secondary information extracted
631 * from the page's content. This is triggered by calling getSecondaryDataUpdates()
632 * and is used for forward links updates on edit and backlink updates by jobs.
633 *
634 * @since 1.20
635 *
636 * @param DataUpdate $update
637 */
638 public function addSecondaryDataUpdate( DataUpdate $update ) {
639 $this->mSecondaryDataUpdates[] = $update;
640 }
641
642 /**
643 * Returns any DataUpdate jobs to be executed in order to store secondary information
644 * extracted from the page's content, including a LinksUpdate object for all links stored in
645 * this ParserOutput object.
646 *
647 * @note Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates()
648 * instead! The content handler may provide additional update objects.
649 *
650 * @since 1.20
651 *
652 * @param Title $title The title of the page we're updating. If not given, a title object will
653 * be created based on $this->getTitleText()
654 * @param bool $recursive Queue jobs for recursive updates?
655 *
656 * @return array An array of instances of DataUpdate
657 */
658 public function getSecondaryDataUpdates( Title $title = null, $recursive = true ) {
659 if ( is_null( $title ) ) {
660 $title = Title::newFromText( $this->getTitleText() );
661 }
662
663 $linksUpdate = new LinksUpdate( $title, $this, $recursive );
664
665 return array_merge( $this->mSecondaryDataUpdates, array( $linksUpdate ) );
666 }
667
668 /**
669 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
670 * the ParserOutput object for later use during page output. The data will be cached along with
671 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
672 * database.
673 *
674 * This method is provided to overcome the unsafe practice of attaching extra information to a
675 * ParserObject by directly assigning member variables.
676 *
677 * To use setExtensionData() to pass extension information from a hook inside the parser to a
678 * hook in the page output, use this in the parser hook:
679 *
680 * @par Example:
681 * @code
682 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
683 * @endcode
684 *
685 * And then later, in OutputPageParserOutput or similar:
686 *
687 * @par Example:
688 * @code
689 * $output->getExtensionData( 'my_ext_foo' );
690 * @endcode
691 *
692 * In MediaWiki 1.20 and older, you have to use a custom member variable
693 * within the ParserOutput object:
694 *
695 * @par Example:
696 * @code
697 * $parser->getOutput()->my_ext_foo = '...';
698 * @endcode
699 *
700 * @since 1.21
701 *
702 * @param string $key The key for accessing the data. Extensions should take care to avoid
703 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
704 *
705 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
706 * the value.
707 */
708 public function setExtensionData( $key, $value ) {
709 if ( $value === null ) {
710 unset( $this->mExtensionData[$key] );
711 } else {
712 $this->mExtensionData[$key] = $value;
713 }
714 }
715
716 /**
717 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
718 * Typically, such data would be set while parsing the page, e.g. by a parser function.
719 *
720 * @since 1.21
721 *
722 * @param string $key The key to look up.
723 *
724 * @return mixed|null The value previously set for the given key using setExtensionData()
725 * or null if no value was set for this key.
726 */
727 public function getExtensionData( $key ) {
728 if ( isset( $this->mExtensionData[$key] ) ) {
729 return $this->mExtensionData[$key];
730 }
731
732 return null;
733 }
734
735 private static function getTimes( $clock = null ) {
736 $ret = array();
737 if ( !$clock || $clock === 'wall' ) {
738 $ret['wall'] = microtime( true );
739 }
740 if ( ( !$clock || $clock === 'cpu' ) && function_exists( 'getrusage' ) ) {
741 $ru = getrusage();
742 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
743 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
744 }
745 return $ret;
746 }
747
748 /**
749 * Resets the parse start timestamps for future calls to getTimeSinceStart()
750 * @since 1.22
751 */
752 public function resetParseStartTime() {
753 $this->mParseStartTime = self::getTimes();
754 }
755
756 /**
757 * Returns the time since resetParseStartTime() was last called
758 *
759 * Clocks available are:
760 * - wall: Wall clock time
761 * - cpu: CPU time (requires getrusage)
762 *
763 * @since 1.22
764 * @param string $clock
765 * @return float|null
766 */
767 public function getTimeSinceStart( $clock ) {
768 if ( !isset( $this->mParseStartTime[$clock] ) ) {
769 return null;
770 }
771
772 $end = self::getTimes( $clock );
773 return $end[$clock] - $this->mParseStartTime[$clock];
774 }
775
776 /**
777 * Sets parser limit report data for a key
778 *
779 * The key is used as the prefix for various messages used for formatting:
780 * - $key: The label for the field in the limit report
781 * - $key-value-text: Message used to format the value in the "NewPP limit
782 * report" HTML comment. If missing, uses $key-format.
783 * - $key-value-html: Message used to format the value in the preview
784 * limit report table. If missing, uses $key-format.
785 * - $key-value: Message used to format the value. If missing, uses "$1".
786 *
787 * Note that all values are interpreted as wikitext, and so should be
788 * encoded with htmlspecialchars() as necessary, but should avoid complex
789 * HTML for sanity of display in the "NewPP limit report" comment.
790 *
791 * @since 1.22
792 * @param string $key Message key
793 * @param mixed $value Appropriate for Message::params()
794 */
795 public function setLimitReportData( $key, $value ) {
796 $this->mLimitReportData[$key] = $value;
797 }
798
799 /**
800 * Get or set the prevent-clickjacking flag
801 *
802 * @since 1.24
803 * @param bool|null $flag New flag value, or null to leave it unchanged
804 * @return bool Old flag value
805 */
806 public function preventClickjacking( $flag = null ) {
807 return wfSetVar( $this->mPreventClickjacking, $flag );
808 }
809
810 /**
811 * Save space for for serialization by removing useless values
812 * @return array
813 */
814 public function __sleep() {
815 return array_diff(
816 array_keys( get_object_vars( $this ) ),
817 array( 'mSecondaryDataUpdates', 'mParseStartTime' )
818 );
819 }
820 }