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