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