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