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