HTMLForm: Separate VForm code to a subclass
[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 * Please add any message that you use with this function to
493 * $wgTrackingCategories. That way they will be listed on
494 * Special:TrackingCategories.
495 *
496 * @param string $msg Message key
497 * @param Title $title title of the page which is being tracked
498 * @return bool Whether the addition was successful
499 * @since 1.25
500 */
501 public function addTrackingCategory( $msg, $title ) {
502 if ( $title->getNamespace() === NS_SPECIAL ) {
503 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
504 return false;
505 }
506
507 // Important to parse with correct title (bug 31469)
508 $cat = wfMessage( $msg )
509 ->title( $title )
510 ->inContentLanguage()
511 ->text();
512
513 # Allow tracking categories to be disabled by setting them to "-"
514 if ( $cat === '-' ) {
515 return false;
516 }
517
518 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
519 if ( $containerCategory ) {
520 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
521 return true;
522 } else {
523 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
524 return false;
525 }
526 }
527
528 /**
529 * Override the title to be used for display
530 * -- this is assumed to have been validated
531 * (check equal normalisation, etc.)
532 *
533 * @param string $text Desired title text
534 */
535 public function setDisplayTitle( $text ) {
536 $this->setTitleText( $text );
537 $this->setProperty( 'displaytitle', $text );
538 }
539
540 /**
541 * Get the title to be used for display
542 *
543 * @return string
544 */
545 public function getDisplayTitle() {
546 $t = $this->getTitleText();
547 if ( $t === '' ) {
548 return false;
549 }
550 return $t;
551 }
552
553 /**
554 * Fairly generic flag setter thingy.
555 * @param string $flag
556 */
557 public function setFlag( $flag ) {
558 $this->mFlags[$flag] = true;
559 }
560
561 public function getFlag( $flag ) {
562 return isset( $this->mFlags[$flag] );
563 }
564
565 /**
566 * Set a property to be stored in the page_props database table.
567 *
568 * page_props is a key value store indexed by the page ID. This allows
569 * the parser to set a property on a page which can then be quickly
570 * retrieved given the page ID or via a DB join when given the page
571 * title.
572 *
573 * Since 1.23, page_props are also indexed by numeric value, to allow
574 * for efficient "top k" queries of pages wrt a given property.
575 *
576 * setProperty() is thus used to propagate properties from the parsed
577 * page to request contexts other than a page view of the currently parsed
578 * article.
579 *
580 * Some applications examples:
581 *
582 * * To implement hidden categories, hiding pages from category listings
583 * by storing a property.
584 *
585 * * Overriding the displayed article title.
586 * @see ParserOutput::setDisplayTitle()
587 *
588 * * To implement image tagging, for example displaying an icon on an
589 * image thumbnail to indicate that it is listed for deletion on
590 * Wikimedia Commons.
591 * This is not actually implemented, yet but would be pretty cool.
592 *
593 * @note Do not use setProperty() to set a property which is only used
594 * in a context where the ParserOutput object itself is already available,
595 * for example a normal page view. There is no need to save such a property
596 * in the database since the text is already parsed. You can just hook
597 * OutputPageParserOutput and get your data out of the ParserOutput object.
598 *
599 * If you are writing an extension where you want to set a property in the
600 * parser which is used by an OutputPageParserOutput hook, you have to
601 * associate the extension data directly with the ParserOutput object.
602 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
603 *
604 * @par Example:
605 * @code
606 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
607 * @endcode
608 *
609 * And then later, in OutputPageParserOutput or similar:
610 *
611 * @par Example:
612 * @code
613 * $output->getExtensionData( 'my_ext_foo' );
614 * @endcode
615 *
616 * In MediaWiki 1.20 and older, you have to use a custom member variable
617 * within the ParserOutput object:
618 *
619 * @par Example:
620 * @code
621 * $parser->getOutput()->my_ext_foo = '...';
622 * @endcode
623 *
624 */
625 public function setProperty( $name, $value ) {
626 $this->mProperties[$name] = $value;
627 }
628
629 /**
630 * @param string $name The property name to look up.
631 *
632 * @return mixed|bool The value previously set using setProperty(). False if null or no value
633 * was set for the given property name.
634 *
635 * @note You need to use getProperties() to check for boolean and null properties.
636 */
637 public function getProperty( $name ) {
638 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
639 }
640
641 public function unsetProperty( $name ) {
642 unset( $this->mProperties[$name] );
643 }
644
645 public function getProperties() {
646 if ( !isset( $this->mProperties ) ) {
647 $this->mProperties = array();
648 }
649 return $this->mProperties;
650 }
651
652 /**
653 * Returns the options from its ParserOptions which have been taken
654 * into account to produce this output or false if not available.
655 * @return array
656 */
657 public function getUsedOptions() {
658 if ( !isset( $this->mAccessedOptions ) ) {
659 return array();
660 }
661 return array_keys( $this->mAccessedOptions );
662 }
663
664 /**
665 * Tags a parser option for use in the cache key for this parser output.
666 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
667 *
668 * @see ParserCache::getKey
669 * @see ParserCache::save
670 * @see ParserOptions::addExtraKey
671 * @see ParserOptions::optionsHash
672 * @param string $option
673 */
674 public function recordOption( $option ) {
675 $this->mAccessedOptions[$option] = true;
676 }
677
678 /**
679 * Adds an update job to the output. Any update jobs added to the output will
680 * eventually be executed in order to store any secondary information extracted
681 * from the page's content. This is triggered by calling getSecondaryDataUpdates()
682 * and is used for forward links updates on edit and backlink updates by jobs.
683 *
684 * @note: custom DataUpdates do not survive serialization of the ParserOutput!
685 * This is especially relevant when using a cached ParserOutput for updating
686 * the database, as WikiPage does if $wgAjaxStashEdit is enabled. For this
687 * reason, ApiStashEdit will skip any ParserOutput that has custom DataUpdates.
688 *
689 * @since 1.20
690 *
691 * @param DataUpdate $update
692 */
693 public function addSecondaryDataUpdate( DataUpdate $update ) {
694 $this->mSecondaryDataUpdates[] = $update;
695 $this->mCustomDataUpdateCount = count( $this->mSecondaryDataUpdates );
696 }
697
698 /**
699 * Whether this ParserOutput contains custom DataUpdate objects that may not survive
700 * serialization of the ParserOutput.
701 *
702 * @see __sleep()
703 *
704 * @return bool
705 */
706 public function hasCustomDataUpdates() {
707 return ( $this->mCustomDataUpdateCount > 0 );
708 }
709
710 /**
711 * Returns any DataUpdate jobs to be executed in order to store secondary information
712 * extracted from the page's content, including a LinksUpdate object for all links stored in
713 * this ParserOutput object.
714 *
715 * @note Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates()
716 * instead! The content handler may provide additional update objects.
717 *
718 * @since 1.20
719 *
720 * @param Title $title The title of the page we're updating. If not given, a title object will
721 * be created based on $this->getTitleText()
722 * @param bool $recursive Queue jobs for recursive updates?
723 *
724 * @throws MWException if called on a ParserOutput instance that was restored from serialization.
725 * DataUpdates are generally not serializable, so after serialization, they are undefined.
726 *
727 * @return array An array of instances of DataUpdate
728 */
729 public function getSecondaryDataUpdates( Title $title = null, $recursive = true ) {
730 if ( is_null( $title ) ) {
731 $title = Title::newFromText( $this->getTitleText() );
732 }
733
734 if ( count( $this->mSecondaryDataUpdates ) !== $this->mCustomDataUpdateCount ) {
735 // NOTE: This happens when mSecondaryDataUpdates are lost during serialization
736 // (see __sleep below). After (un)serialization, getSecondaryDataUpdates()
737 // has no defined behavior in that case, and should throw an exception.
738 throw new MWException( 'getSecondaryDataUpdates() must not be called on ParserOutput restored from serialization.' );
739 }
740
741 // NOTE: ApiStashEdit knows about this "magic" update object. If this goes away,
742 // ApiStashEdit::buildStashValue needs to be adjusted.
743 $linksUpdate = new LinksUpdate( $title, $this, $recursive );
744
745 return array_merge( $this->mSecondaryDataUpdates, array( $linksUpdate ) );
746 }
747
748 /**
749 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
750 * the ParserOutput object for later use during page output. The data will be cached along with
751 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
752 * database.
753 *
754 * This method is provided to overcome the unsafe practice of attaching extra information to a
755 * ParserObject by directly assigning member variables.
756 *
757 * To use setExtensionData() to pass extension information from a hook inside the parser to a
758 * hook in the page output, use this in the parser hook:
759 *
760 * @par Example:
761 * @code
762 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
763 * @endcode
764 *
765 * And then later, in OutputPageParserOutput or similar:
766 *
767 * @par Example:
768 * @code
769 * $output->getExtensionData( 'my_ext_foo' );
770 * @endcode
771 *
772 * In MediaWiki 1.20 and older, you have to use a custom member variable
773 * within the ParserOutput object:
774 *
775 * @par Example:
776 * @code
777 * $parser->getOutput()->my_ext_foo = '...';
778 * @endcode
779 *
780 * @since 1.21
781 *
782 * @param string $key The key for accessing the data. Extensions should take care to avoid
783 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
784 *
785 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
786 * the value.
787 */
788 public function setExtensionData( $key, $value ) {
789 if ( $value === null ) {
790 unset( $this->mExtensionData[$key] );
791 } else {
792 $this->mExtensionData[$key] = $value;
793 }
794 }
795
796 /**
797 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
798 * Typically, such data would be set while parsing the page, e.g. by a parser function.
799 *
800 * @since 1.21
801 *
802 * @param string $key The key to look up.
803 *
804 * @return mixed|null The value previously set for the given key using setExtensionData()
805 * or null if no value was set for this key.
806 */
807 public function getExtensionData( $key ) {
808 if ( isset( $this->mExtensionData[$key] ) ) {
809 return $this->mExtensionData[$key];
810 }
811
812 return null;
813 }
814
815 private static function getTimes( $clock = null ) {
816 $ret = array();
817 if ( !$clock || $clock === 'wall' ) {
818 $ret['wall'] = microtime( true );
819 }
820 if ( !$clock || $clock === 'cpu' ) {
821 $ru = wfGetRusage();
822 if ( $ru ) {
823 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
824 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
825 }
826 }
827 return $ret;
828 }
829
830 /**
831 * Resets the parse start timestamps for future calls to getTimeSinceStart()
832 * @since 1.22
833 */
834 public function resetParseStartTime() {
835 $this->mParseStartTime = self::getTimes();
836 }
837
838 /**
839 * Returns the time since resetParseStartTime() was last called
840 *
841 * Clocks available are:
842 * - wall: Wall clock time
843 * - cpu: CPU time (requires getrusage)
844 *
845 * @since 1.22
846 * @param string $clock
847 * @return float|null
848 */
849 public function getTimeSinceStart( $clock ) {
850 if ( !isset( $this->mParseStartTime[$clock] ) ) {
851 return null;
852 }
853
854 $end = self::getTimes( $clock );
855 return $end[$clock] - $this->mParseStartTime[$clock];
856 }
857
858 /**
859 * Sets parser limit report data for a key
860 *
861 * The key is used as the prefix for various messages used for formatting:
862 * - $key: The label for the field in the limit report
863 * - $key-value-text: Message used to format the value in the "NewPP limit
864 * report" HTML comment. If missing, uses $key-format.
865 * - $key-value-html: Message used to format the value in the preview
866 * limit report table. If missing, uses $key-format.
867 * - $key-value: Message used to format the value. If missing, uses "$1".
868 *
869 * Note that all values are interpreted as wikitext, and so should be
870 * encoded with htmlspecialchars() as necessary, but should avoid complex
871 * HTML for sanity of display in the "NewPP limit report" comment.
872 *
873 * @since 1.22
874 * @param string $key Message key
875 * @param mixed $value Appropriate for Message::params()
876 */
877 public function setLimitReportData( $key, $value ) {
878 $this->mLimitReportData[$key] = $value;
879 }
880
881 /**
882 * Get or set the prevent-clickjacking flag
883 *
884 * @since 1.24
885 * @param bool|null $flag New flag value, or null to leave it unchanged
886 * @return bool Old flag value
887 */
888 public function preventClickjacking( $flag = null ) {
889 return wfSetVar( $this->mPreventClickjacking, $flag );
890 }
891
892 /**
893 * Save space for serialization by removing useless values
894 * @return array
895 */
896 public function __sleep() {
897 return array_diff(
898 array_keys( get_object_vars( $this ) ),
899 array( 'mSecondaryDataUpdates', 'mParseStartTime' )
900 );
901 }
902 }