Remove getSecondaryDataUpdates and friends from ParserOutput.
[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 $containsOldMagic = false, $titletext = ''
66 ) {
67 $this->mText = $text;
68 $this->mLanguageLinks = $languageLinks;
69 $this->mCategories = $categoryLinks;
70 $this->mContainsOldMagic = $containsOldMagic;
71 $this->mTitleText = $titletext;
72 }
73
74 public function getText() {
75 $text = $this->mText;
76 if ( $this->mEditSectionTokens ) {
77 $text = preg_replace_callback(
78 ParserOutput::EDITSECTION_REGEX,
79 function ( $m ) {
80 global $wgOut, $wgLang;
81 $editsectionPage = Title::newFromText( htmlspecialchars_decode( $m[1] ) );
82 $editsectionSection = htmlspecialchars_decode( $m[2] );
83 $editsectionContent = isset( $m[4] ) ? $m[3] : null;
84
85 if ( !is_object( $editsectionPage ) ) {
86 throw new MWException( "Bad parser output text." );
87 }
88
89 $skin = $wgOut->getSkin();
90 return call_user_func_array(
91 array( $skin, 'doEditSectionLink' ),
92 array( $editsectionPage, $editsectionSection,
93 $editsectionContent, $wgLang->getCode() )
94 );
95 },
96 $text
97 );
98 } else {
99 $text = preg_replace( ParserOutput::EDITSECTION_REGEX, '', $text );
100 }
101
102 // If you have an old cached version of this class - sorry, you can't disable the TOC
103 if ( isset( $this->mTOCEnabled ) && $this->mTOCEnabled ) {
104 $text = str_replace( array( Parser::TOC_START, Parser::TOC_END ), '', $text );
105 } else {
106 $text = preg_replace(
107 '#' . preg_quote( Parser::TOC_START ) . '.*?' . preg_quote( Parser::TOC_END ) . '#s',
108 '',
109 $text
110 );
111 }
112 return $text;
113 }
114
115 public function &getLanguageLinks() {
116 return $this->mLanguageLinks;
117 }
118
119 public function getInterwikiLinks() {
120 return $this->mInterwikiLinks;
121 }
122
123 public function getCategoryLinks() {
124 return array_keys( $this->mCategories );
125 }
126
127 public function &getCategories() {
128 return $this->mCategories;
129 }
130
131 /**
132 * @since 1.25
133 */
134 public function getIndicators() {
135 return $this->mIndicators;
136 }
137
138 public function getTitleText() {
139 return $this->mTitleText;
140 }
141
142 public function getSections() {
143 return $this->mSections;
144 }
145
146 public function getEditSectionTokens() {
147 return $this->mEditSectionTokens;
148 }
149
150 public function &getLinks() {
151 return $this->mLinks;
152 }
153
154 public function &getTemplates() {
155 return $this->mTemplates;
156 }
157
158 public function &getTemplateIds() {
159 return $this->mTemplateIds;
160 }
161
162 public function &getImages() {
163 return $this->mImages;
164 }
165
166 public function &getFileSearchOptions() {
167 return $this->mFileSearchOptions;
168 }
169
170 public function &getExternalLinks() {
171 return $this->mExternalLinks;
172 }
173
174 public function getNoGallery() {
175 return $this->mNoGallery;
176 }
177
178 public function getHeadItems() {
179 return $this->mHeadItems;
180 }
181
182 public function getModules() {
183 return $this->mModules;
184 }
185
186 public function getModuleScripts() {
187 return $this->mModuleScripts;
188 }
189
190 public function getModuleStyles() {
191 return $this->mModuleStyles;
192 }
193
194 public function getModuleMessages() {
195 return $this->mModuleMessages;
196 }
197
198 /** @since 1.23 */
199 public function getJsConfigVars() {
200 return $this->mJsConfigVars;
201 }
202
203 public function getOutputHooks() {
204 return (array)$this->mOutputHooks;
205 }
206
207 public function getWarnings() {
208 return array_keys( $this->mWarnings );
209 }
210
211 public function getIndexPolicy() {
212 return $this->mIndexPolicy;
213 }
214
215 public function getTOCHTML() {
216 return $this->mTOCHTML;
217 }
218
219 public function getTimestamp() {
220 return $this->mTimestamp;
221 }
222
223 public function getLimitReportData() {
224 return $this->mLimitReportData;
225 }
226
227 public function getTOCEnabled() {
228 return $this->mTOCEnabled;
229 }
230
231 public function setText( $text ) {
232 return wfSetVar( $this->mText, $text );
233 }
234
235 public function setLanguageLinks( $ll ) {
236 return wfSetVar( $this->mLanguageLinks, $ll );
237 }
238
239 public function setCategoryLinks( $cl ) {
240 return wfSetVar( $this->mCategories, $cl );
241 }
242
243 public function setTitleText( $t ) {
244 return wfSetVar( $this->mTitleText, $t );
245 }
246
247 public function setSections( $toc ) {
248 return wfSetVar( $this->mSections, $toc );
249 }
250
251 public function setEditSectionTokens( $t ) {
252 return wfSetVar( $this->mEditSectionTokens, $t );
253 }
254
255 public function setIndexPolicy( $policy ) {
256 return wfSetVar( $this->mIndexPolicy, $policy );
257 }
258
259 public function setTOCHTML( $tochtml ) {
260 return wfSetVar( $this->mTOCHTML, $tochtml );
261 }
262
263 public function setTimestamp( $timestamp ) {
264 return wfSetVar( $this->mTimestamp, $timestamp );
265 }
266
267 public function setTOCEnabled( $flag ) {
268 return wfSetVar( $this->mTOCEnabled, $flag );
269 }
270
271 public function addCategory( $c, $sort ) {
272 $this->mCategories[$c] = $sort;
273 }
274
275 /**
276 * @since 1.25
277 */
278 public function setIndicator( $id, $content ) {
279 $this->mIndicators[$id] = $content;
280 }
281
282 public function addLanguageLink( $t ) {
283 $this->mLanguageLinks[] = $t;
284 }
285
286 public function addWarning( $s ) {
287 $this->mWarnings[$s] = 1;
288 }
289
290 public function addOutputHook( $hook, $data = false ) {
291 $this->mOutputHooks[] = array( $hook, $data );
292 }
293
294 public function setNewSection( $value ) {
295 $this->mNewSection = (bool)$value;
296 }
297 public function hideNewSection( $value ) {
298 $this->mHideNewSection = (bool)$value;
299 }
300 public function getHideNewSection() {
301 return (bool)$this->mHideNewSection;
302 }
303 public function getNewSection() {
304 return (bool)$this->mNewSection;
305 }
306
307 /**
308 * Checks, if a url is pointing to the own server
309 *
310 * @param string $internal The server to check against
311 * @param string $url The url to check
312 * @return bool
313 */
314 public static function isLinkInternal( $internal, $url ) {
315 return (bool)preg_match( '/^' .
316 # If server is proto relative, check also for http/https links
317 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
318 preg_quote( $internal, '/' ) .
319 # check for query/path/anchor or end of link in each case
320 '(?:[\?\/\#]|$)/i',
321 $url
322 );
323 }
324
325 public function addExternalLink( $url ) {
326 # We don't register links pointing to our own server, unless... :-)
327 global $wgServer, $wgRegisterInternalExternals;
328
329 $registerExternalLink = true;
330 if ( !$wgRegisterInternalExternals ) {
331 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
332 }
333 if ( $registerExternalLink ) {
334 $this->mExternalLinks[$url] = 1;
335 }
336 }
337
338 /**
339 * Record a local or interwiki inline link for saving in future link tables.
340 *
341 * @param Title $title
342 * @param int|null $id Optional known page_id so we can skip the lookup
343 */
344 public function addLink( Title $title, $id = null ) {
345 if ( $title->isExternal() ) {
346 // Don't record interwikis in pagelinks
347 $this->addInterwikiLink( $title );
348 return;
349 }
350 $ns = $title->getNamespace();
351 $dbk = $title->getDBkey();
352 if ( $ns == NS_MEDIA ) {
353 // Normalize this pseudo-alias if it makes it down here...
354 $ns = NS_FILE;
355 } elseif ( $ns == NS_SPECIAL ) {
356 // We don't record Special: links currently
357 // It might actually be wise to, but we'd need to do some normalization.
358 return;
359 } elseif ( $dbk === '' ) {
360 // Don't record self links - [[#Foo]]
361 return;
362 }
363 if ( !isset( $this->mLinks[$ns] ) ) {
364 $this->mLinks[$ns] = array();
365 }
366 if ( is_null( $id ) ) {
367 $id = $title->getArticleID();
368 }
369 $this->mLinks[$ns][$dbk] = $id;
370 }
371
372 /**
373 * Register a file dependency for this output
374 * @param string $name Title dbKey
375 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
376 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
377 * @return void
378 */
379 public function addImage( $name, $timestamp = null, $sha1 = null ) {
380 $this->mImages[$name] = 1;
381 if ( $timestamp !== null && $sha1 !== null ) {
382 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
383 }
384 }
385
386 /**
387 * Register a template dependency for this output
388 * @param Title $title
389 * @param int $page_id
390 * @param int $rev_id
391 * @return void
392 */
393 public function addTemplate( $title, $page_id, $rev_id ) {
394 $ns = $title->getNamespace();
395 $dbk = $title->getDBkey();
396 if ( !isset( $this->mTemplates[$ns] ) ) {
397 $this->mTemplates[$ns] = array();
398 }
399 $this->mTemplates[$ns][$dbk] = $page_id;
400 if ( !isset( $this->mTemplateIds[$ns] ) ) {
401 $this->mTemplateIds[$ns] = array();
402 }
403 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
404 }
405
406 /**
407 * @param Title $title Title object, must be an interwiki link
408 * @throws MWException If given invalid input
409 */
410 public function addInterwikiLink( $title ) {
411 if ( !$title->isExternal() ) {
412 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
413 }
414 $prefix = $title->getInterwiki();
415 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
416 $this->mInterwikiLinks[$prefix] = array();
417 }
418 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
419 }
420
421 /**
422 * Add some text to the "<head>".
423 * If $tag is set, the section with that tag will only be included once
424 * in a given page.
425 * @param string $section
426 * @param string|bool $tag
427 */
428 public function addHeadItem( $section, $tag = false ) {
429 if ( $tag !== false ) {
430 $this->mHeadItems[$tag] = $section;
431 } else {
432 $this->mHeadItems[] = $section;
433 }
434 }
435
436 public function addModules( $modules ) {
437 $this->mModules = array_merge( $this->mModules, (array)$modules );
438 }
439
440 public function addModuleScripts( $modules ) {
441 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
442 }
443
444 public function addModuleStyles( $modules ) {
445 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
446 }
447
448 public function addModuleMessages( $modules ) {
449 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
450 }
451
452 /**
453 * Add one or more variables to be set in mw.config in JavaScript.
454 *
455 * @param string|array $keys Key or array of key/value pairs.
456 * @param mixed $value [optional] Value of the configuration variable.
457 * @since 1.23
458 */
459 public function addJsConfigVars( $keys, $value = null ) {
460 if ( is_array( $keys ) ) {
461 foreach ( $keys as $key => $value ) {
462 $this->mJsConfigVars[$key] = $value;
463 }
464 return;
465 }
466
467 $this->mJsConfigVars[$keys] = $value;
468 }
469
470 /**
471 * Copy items from the OutputPage object into this one
472 *
473 * @param OutputPage $out
474 */
475 public function addOutputPageMetadata( OutputPage $out ) {
476 $this->addModules( $out->getModules() );
477 $this->addModuleScripts( $out->getModuleScripts() );
478 $this->addModuleStyles( $out->getModuleStyles() );
479 $this->addModuleMessages( $out->getModuleMessages() );
480 $this->addJsConfigVars( $out->getJsConfigVars() );
481
482 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
483 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
484 }
485
486 /**
487 * Add a tracking category, getting the title from a system message,
488 * or print a debug message if the title is invalid.
489 *
490 * Any message used with this function should be registered so it will
491 * show up on Special:TrackingCategories. Core messages should be added
492 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
493 * should add to "TrackingCategories" in their extension.json.
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 * @deprecated since 1.25. Instead, store any relevant data using setExtensionData,
679 * and implement Content::getSecondaryDataUpdates() if possible, or use the
680 * 'SecondaryDataUpdates' hook to construct the necessary update objects.
681 *
682 * @note Hard deprecation and removal without long deprecation period, since there are no
683 * known users, but known conceptual issues.
684 *
685 * @todo remove in 1.26
686 *
687 * @param DataUpdate $update
688 *
689 * @throws MWException
690 */
691 public function addSecondaryDataUpdate( DataUpdate $update ) {
692 wfDeprecated( __METHOD__, '1.25' );
693 throw new MWException( 'ParserOutput::addSecondaryDataUpdate() is no longer supported. Override Content::getSecondaryDataUpdates() or use the SecondaryDataUpdates hook instead.' );
694 }
695
696 /**
697 * @deprecated since 1.25.
698 *
699 * @note Hard deprecation and removal without long deprecation period, since there are no
700 * known users, but known conceptual issues.
701 *
702 * @todo remove in 1.26
703 *
704 * @return bool false (since 1.25)
705 */
706 public function hasCustomDataUpdates() {
707 wfDeprecated( __METHOD__, '1.25' );
708 return false;
709 }
710
711 /**
712 * @deprecated since 1.25. Instead, store any relevant data using setExtensionData,
713 * and implement Content::getSecondaryDataUpdates() if possible, or use the
714 * 'SecondaryDataUpdates' hook to construct the necessary update objects.
715 *
716 * @note Hard deprecation and removal without long deprecation period, since there are no
717 * known users, but known conceptual issues.
718 *
719 * @todo remove in 1.26
720 *
721 * @param Title $title
722 * @param bool $recursive
723 *
724 * @return array An array of instances of DataUpdate
725 */
726 public function getSecondaryDataUpdates( Title $title = null, $recursive = true ) {
727 wfDeprecated( __METHOD__, '1.25' );
728 return array();
729 }
730
731 /**
732 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
733 * the ParserOutput object for later use during page output. The data will be cached along with
734 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
735 * database.
736 *
737 * This method is provided to overcome the unsafe practice of attaching extra information to a
738 * ParserObject by directly assigning member variables.
739 *
740 * To use setExtensionData() to pass extension information from a hook inside the parser to a
741 * hook in the page output, use this in the parser hook:
742 *
743 * @par Example:
744 * @code
745 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
746 * @endcode
747 *
748 * And then later, in OutputPageParserOutput or similar:
749 *
750 * @par Example:
751 * @code
752 * $output->getExtensionData( 'my_ext_foo' );
753 * @endcode
754 *
755 * In MediaWiki 1.20 and older, you have to use a custom member variable
756 * within the ParserOutput object:
757 *
758 * @par Example:
759 * @code
760 * $parser->getOutput()->my_ext_foo = '...';
761 * @endcode
762 *
763 * @since 1.21
764 *
765 * @param string $key The key for accessing the data. Extensions should take care to avoid
766 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
767 *
768 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
769 * the value.
770 */
771 public function setExtensionData( $key, $value ) {
772 if ( $value === null ) {
773 unset( $this->mExtensionData[$key] );
774 } else {
775 $this->mExtensionData[$key] = $value;
776 }
777 }
778
779 /**
780 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
781 * Typically, such data would be set while parsing the page, e.g. by a parser function.
782 *
783 * @since 1.21
784 *
785 * @param string $key The key to look up.
786 *
787 * @return mixed|null The value previously set for the given key using setExtensionData()
788 * or null if no value was set for this key.
789 */
790 public function getExtensionData( $key ) {
791 if ( isset( $this->mExtensionData[$key] ) ) {
792 return $this->mExtensionData[$key];
793 }
794
795 return null;
796 }
797
798 private static function getTimes( $clock = null ) {
799 $ret = array();
800 if ( !$clock || $clock === 'wall' ) {
801 $ret['wall'] = microtime( true );
802 }
803 if ( !$clock || $clock === 'cpu' ) {
804 $ru = wfGetRusage();
805 if ( $ru ) {
806 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
807 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
808 }
809 }
810 return $ret;
811 }
812
813 /**
814 * Resets the parse start timestamps for future calls to getTimeSinceStart()
815 * @since 1.22
816 */
817 public function resetParseStartTime() {
818 $this->mParseStartTime = self::getTimes();
819 }
820
821 /**
822 * Returns the time since resetParseStartTime() was last called
823 *
824 * Clocks available are:
825 * - wall: Wall clock time
826 * - cpu: CPU time (requires getrusage)
827 *
828 * @since 1.22
829 * @param string $clock
830 * @return float|null
831 */
832 public function getTimeSinceStart( $clock ) {
833 if ( !isset( $this->mParseStartTime[$clock] ) ) {
834 return null;
835 }
836
837 $end = self::getTimes( $clock );
838 return $end[$clock] - $this->mParseStartTime[$clock];
839 }
840
841 /**
842 * Sets parser limit report data for a key
843 *
844 * The key is used as the prefix for various messages used for formatting:
845 * - $key: The label for the field in the limit report
846 * - $key-value-text: Message used to format the value in the "NewPP limit
847 * report" HTML comment. If missing, uses $key-format.
848 * - $key-value-html: Message used to format the value in the preview
849 * limit report table. If missing, uses $key-format.
850 * - $key-value: Message used to format the value. If missing, uses "$1".
851 *
852 * Note that all values are interpreted as wikitext, and so should be
853 * encoded with htmlspecialchars() as necessary, but should avoid complex
854 * HTML for sanity of display in the "NewPP limit report" comment.
855 *
856 * @since 1.22
857 * @param string $key Message key
858 * @param mixed $value Appropriate for Message::params()
859 */
860 public function setLimitReportData( $key, $value ) {
861 $this->mLimitReportData[$key] = $value;
862 }
863
864 /**
865 * Check whether the cache TTL was lowered due to dynamic content
866 *
867 * When content is determined by more than hard state (e.g. page edits),
868 * such as template/file transclusions based on the current timestamp or
869 * extension tags that generate lists based on queries, this return true.
870 *
871 * @return bool
872 * @since 1.25
873 */
874 public function hasDynamicContent() {
875 global $wgParserCacheExpireTime;
876
877 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
878 }
879
880 /**
881 * Get or set the prevent-clickjacking flag
882 *
883 * @since 1.24
884 * @param bool|null $flag New flag value, or null to leave it unchanged
885 * @return bool Old flag value
886 */
887 public function preventClickjacking( $flag = null ) {
888 return wfSetVar( $this->mPreventClickjacking, $flag );
889 }
890
891 /**
892 * Save space for serialization by removing useless values
893 * @return array
894 */
895 public function __sleep() {
896 return array_diff(
897 array_keys( get_object_vars( $this ) ),
898 array( 'mParseStartTime' )
899 );
900 }
901 }