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