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