Merge "jquery.makeCollapsible: Support for .mw-collapsible-toggle inside <li>"
[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 /**
26 * @var string $mText The output text
27 */
28 public $mText;
29
30 /**
31 * @var array $mLanguageLinks List of the full text of language links,
32 * in the order they appear.
33 */
34 public $mLanguageLinks;
35
36 /**
37 * @var array $mCategoriesMap of category names to sort keys
38 */
39 public $mCategories;
40
41 /**
42 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
43 */
44 public $mIndicators = [];
45
46 /**
47 * @var string $mTitleText Title text of the chosen language variant, as HTML.
48 */
49 public $mTitleText;
50
51 /**
52 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
53 * ID=zero for broken.
54 */
55 public $mLinks = [];
56
57 /**
58 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
59 * ID=zero for broken.
60 */
61 public $mTemplates = [];
62
63 /**
64 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
65 * ID=zero for broken.
66 */
67 public $mTemplateIds = [];
68
69 /**
70 * @var array $mImages DB keys of the images used, in the array key only
71 */
72 public $mImages = [];
73
74 /**
75 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
76 */
77 public $mFileSearchOptions = [];
78
79 /**
80 * @var array $mExternalLinks External link URLs, in the key only.
81 */
82 public $mExternalLinks = [];
83
84 /**
85 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
86 * for the inline interwiki links in the document.
87 */
88 public $mInterwikiLinks = [];
89
90 /**
91 * @var bool $mNewSection Show a new section link?
92 */
93 public $mNewSection = false;
94
95 /**
96 * @var bool $mHideNewSection Hide the new section link?
97 */
98 public $mHideNewSection = false;
99
100 /**
101 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
102 */
103 public $mNoGallery = false;
104
105 /**
106 * @var array $mHeadItems Items to put in the <head> section
107 */
108 public $mHeadItems = [];
109
110 /**
111 * @var array $mModules Modules to be loaded by ResourceLoader
112 */
113 public $mModules = [];
114
115 /**
116 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
117 */
118 public $mModuleScripts = [];
119
120 /**
121 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
122 */
123 public $mModuleStyles = [];
124
125 /**
126 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
127 */
128 public $mJsConfigVars = [];
129
130 /**
131 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
132 */
133 public $mOutputHooks = [];
134
135 /**
136 * @var array $mWarnings Warning text to be returned to the user.
137 * Wikitext formatted, in the key only.
138 */
139 public $mWarnings = [];
140
141 /**
142 * @var array $mSections Table of contents
143 */
144 public $mSections = [];
145
146 /**
147 * @var bool $mEditSectionTokens prefix/suffix markers if edit sections were output as tokens.
148 */
149 public $mEditSectionTokens = false;
150
151 /**
152 * @var array $mProperties Name/value pairs to be cached in the DB.
153 */
154 public $mProperties = [];
155
156 /**
157 * @var string $mTOCHTML HTML of the TOC.
158 */
159 public $mTOCHTML = '';
160
161 /**
162 * @var string $mTimestamp Timestamp of the revision.
163 */
164 public $mTimestamp;
165
166 /**
167 * @var bool $mTOCEnabled Whether TOC should be shown, can't override __NOTOC__.
168 */
169 public $mTOCEnabled = true;
170
171 /**
172 * @var bool $mEnableOOUI Whether OOUI should be enabled.
173 */
174 public $mEnableOOUI = false;
175
176 /**
177 * @var string $mIndexPolicy 'index' or 'noindex'? Any other value will result in no change.
178 */
179 private $mIndexPolicy = '';
180
181 /**
182 * @var array $mAccessedOptions List of ParserOptions (stored in the keys).
183 */
184 private $mAccessedOptions = [];
185
186 /**
187 * @var array $mExtensionData extra data used by extensions.
188 */
189 private $mExtensionData = [];
190
191 /** @var array $mLimitReportData Parser limit report data. */
192 private $mLimitReportData = [];
193
194 /**
195 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
196 */
197 private $mParseStartTime = [];
198
199 /**
200 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
201 */
202 private $mPreventClickjacking = false;
203
204 /**
205 * @var array $mFlags Generic flags.
206 */
207 private $mFlags = [];
208
209 /** @var integer|null Assumed rev ID for {{REVISIONID}} if no revision is set */
210 private $mSpeculativeRevId;
211
212 const EDITSECTION_REGEX =
213 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
214
215 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
216 $unused = false, $titletext = ''
217 ) {
218 $this->mText = $text;
219 $this->mLanguageLinks = $languageLinks;
220 $this->mCategories = $categoryLinks;
221 $this->mTitleText = $titletext;
222 }
223
224 /**
225 * Get the cacheable text with <mw:editsection> markers still in it. The
226 * return value is suitable for writing back via setText() but is not valid
227 * for display to the user.
228 *
229 * @since 1.27
230 */
231 public function getRawText() {
232 return $this->mText;
233 }
234
235 public function getText() {
236 $text = $this->mText;
237 if ( $this->mEditSectionTokens ) {
238 $text = preg_replace_callback(
239 ParserOutput::EDITSECTION_REGEX,
240 function ( $m ) {
241 global $wgOut, $wgLang;
242 $editsectionPage = Title::newFromText( htmlspecialchars_decode( $m[1] ) );
243 $editsectionSection = htmlspecialchars_decode( $m[2] );
244 $editsectionContent = isset( $m[4] ) ? $m[3] : null;
245
246 if ( !is_object( $editsectionPage ) ) {
247 throw new MWException( "Bad parser output text." );
248 }
249
250 $skin = $wgOut->getSkin();
251 return call_user_func_array(
252 [ $skin, 'doEditSectionLink' ],
253 [ $editsectionPage, $editsectionSection,
254 $editsectionContent, $wgLang->getCode() ]
255 );
256 },
257 $text
258 );
259 } else {
260 $text = preg_replace( ParserOutput::EDITSECTION_REGEX, '', $text );
261 }
262
263 // If you have an old cached version of this class - sorry, you can't disable the TOC
264 if ( isset( $this->mTOCEnabled ) && $this->mTOCEnabled ) {
265 $text = str_replace( [ Parser::TOC_START, Parser::TOC_END ], '', $text );
266 } else {
267 $text = preg_replace(
268 '#' . preg_quote( Parser::TOC_START, '#' ) . '.*?' . preg_quote( Parser::TOC_END, '#' ) . '#s',
269 '',
270 $text
271 );
272 }
273 return $text;
274 }
275
276 /**
277 * @param integer $id
278 * @since 1.28
279 */
280 public function setSpeculativeRevIdUsed( $id ) {
281 $this->mSpeculativeRevId = $id;
282 }
283
284 /** @since 1.28 */
285 public function getSpeculativeRevIdUsed() {
286 return $this->mSpeculativeRevId;
287 }
288
289 public function &getLanguageLinks() {
290 return $this->mLanguageLinks;
291 }
292
293 public function getInterwikiLinks() {
294 return $this->mInterwikiLinks;
295 }
296
297 public function getCategoryLinks() {
298 return array_keys( $this->mCategories );
299 }
300
301 public function &getCategories() {
302 return $this->mCategories;
303 }
304
305 /**
306 * @since 1.25
307 */
308 public function getIndicators() {
309 return $this->mIndicators;
310 }
311
312 public function getTitleText() {
313 return $this->mTitleText;
314 }
315
316 public function getSections() {
317 return $this->mSections;
318 }
319
320 public function getEditSectionTokens() {
321 return $this->mEditSectionTokens;
322 }
323
324 public function &getLinks() {
325 return $this->mLinks;
326 }
327
328 public function &getTemplates() {
329 return $this->mTemplates;
330 }
331
332 public function &getTemplateIds() {
333 return $this->mTemplateIds;
334 }
335
336 public function &getImages() {
337 return $this->mImages;
338 }
339
340 public function &getFileSearchOptions() {
341 return $this->mFileSearchOptions;
342 }
343
344 public function &getExternalLinks() {
345 return $this->mExternalLinks;
346 }
347
348 public function getNoGallery() {
349 return $this->mNoGallery;
350 }
351
352 public function getHeadItems() {
353 return $this->mHeadItems;
354 }
355
356 public function getModules() {
357 return $this->mModules;
358 }
359
360 public function getModuleScripts() {
361 return $this->mModuleScripts;
362 }
363
364 public function getModuleStyles() {
365 return $this->mModuleStyles;
366 }
367
368 /** @since 1.23 */
369 public function getJsConfigVars() {
370 return $this->mJsConfigVars;
371 }
372
373 public function getOutputHooks() {
374 return (array)$this->mOutputHooks;
375 }
376
377 public function getWarnings() {
378 return array_keys( $this->mWarnings );
379 }
380
381 public function getIndexPolicy() {
382 return $this->mIndexPolicy;
383 }
384
385 public function getTOCHTML() {
386 return $this->mTOCHTML;
387 }
388
389 /**
390 * @return string|null TS_MW timestamp of the revision content
391 */
392 public function getTimestamp() {
393 return $this->mTimestamp;
394 }
395
396 public function getLimitReportData() {
397 return $this->mLimitReportData;
398 }
399
400 public function getTOCEnabled() {
401 return $this->mTOCEnabled;
402 }
403
404 public function getEnableOOUI() {
405 return $this->mEnableOOUI;
406 }
407
408 public function setText( $text ) {
409 return wfSetVar( $this->mText, $text );
410 }
411
412 public function setLanguageLinks( $ll ) {
413 return wfSetVar( $this->mLanguageLinks, $ll );
414 }
415
416 public function setCategoryLinks( $cl ) {
417 return wfSetVar( $this->mCategories, $cl );
418 }
419
420 public function setTitleText( $t ) {
421 return wfSetVar( $this->mTitleText, $t );
422 }
423
424 public function setSections( $toc ) {
425 return wfSetVar( $this->mSections, $toc );
426 }
427
428 public function setEditSectionTokens( $t ) {
429 return wfSetVar( $this->mEditSectionTokens, $t );
430 }
431
432 public function setIndexPolicy( $policy ) {
433 return wfSetVar( $this->mIndexPolicy, $policy );
434 }
435
436 public function setTOCHTML( $tochtml ) {
437 return wfSetVar( $this->mTOCHTML, $tochtml );
438 }
439
440 public function setTimestamp( $timestamp ) {
441 return wfSetVar( $this->mTimestamp, $timestamp );
442 }
443
444 public function setTOCEnabled( $flag ) {
445 return wfSetVar( $this->mTOCEnabled, $flag );
446 }
447
448 public function addCategory( $c, $sort ) {
449 $this->mCategories[$c] = $sort;
450 }
451
452 /**
453 * @since 1.25
454 */
455 public function setIndicator( $id, $content ) {
456 $this->mIndicators[$id] = $content;
457 }
458
459 /**
460 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
461 * object is added to.
462 *
463 * @since 1.26
464 * @param bool $enable If OOUI should be enabled or not
465 */
466 public function setEnableOOUI( $enable = false ) {
467 $this->mEnableOOUI = $enable;
468 }
469
470 public function addLanguageLink( $t ) {
471 $this->mLanguageLinks[] = $t;
472 }
473
474 public function addWarning( $s ) {
475 $this->mWarnings[$s] = 1;
476 }
477
478 public function addOutputHook( $hook, $data = false ) {
479 $this->mOutputHooks[] = [ $hook, $data ];
480 }
481
482 public function setNewSection( $value ) {
483 $this->mNewSection = (bool)$value;
484 }
485 public function hideNewSection( $value ) {
486 $this->mHideNewSection = (bool)$value;
487 }
488 public function getHideNewSection() {
489 return (bool)$this->mHideNewSection;
490 }
491 public function getNewSection() {
492 return (bool)$this->mNewSection;
493 }
494
495 /**
496 * Checks, if a url is pointing to the own server
497 *
498 * @param string $internal The server to check against
499 * @param string $url The url to check
500 * @return bool
501 */
502 public static function isLinkInternal( $internal, $url ) {
503 return (bool)preg_match( '/^' .
504 # If server is proto relative, check also for http/https links
505 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
506 preg_quote( $internal, '/' ) .
507 # check for query/path/anchor or end of link in each case
508 '(?:[\?\/\#]|$)/i',
509 $url
510 );
511 }
512
513 public function addExternalLink( $url ) {
514 # We don't register links pointing to our own server, unless... :-)
515 global $wgServer, $wgRegisterInternalExternals;
516
517 $registerExternalLink = true;
518 if ( !$wgRegisterInternalExternals ) {
519 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
520 }
521 if ( $registerExternalLink ) {
522 $this->mExternalLinks[$url] = 1;
523 }
524 }
525
526 /**
527 * Record a local or interwiki inline link for saving in future link tables.
528 *
529 * @param Title $title
530 * @param int|null $id Optional known page_id so we can skip the lookup
531 */
532 public function addLink( Title $title, $id = null ) {
533 if ( $title->isExternal() ) {
534 // Don't record interwikis in pagelinks
535 $this->addInterwikiLink( $title );
536 return;
537 }
538 $ns = $title->getNamespace();
539 $dbk = $title->getDBkey();
540 if ( $ns == NS_MEDIA ) {
541 // Normalize this pseudo-alias if it makes it down here...
542 $ns = NS_FILE;
543 } elseif ( $ns == NS_SPECIAL ) {
544 // We don't record Special: links currently
545 // It might actually be wise to, but we'd need to do some normalization.
546 return;
547 } elseif ( $dbk === '' ) {
548 // Don't record self links - [[#Foo]]
549 return;
550 }
551 if ( !isset( $this->mLinks[$ns] ) ) {
552 $this->mLinks[$ns] = [];
553 }
554 if ( is_null( $id ) ) {
555 $id = $title->getArticleID();
556 }
557 $this->mLinks[$ns][$dbk] = $id;
558 }
559
560 /**
561 * Register a file dependency for this output
562 * @param string $name Title dbKey
563 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
564 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
565 * @return void
566 */
567 public function addImage( $name, $timestamp = null, $sha1 = null ) {
568 $this->mImages[$name] = 1;
569 if ( $timestamp !== null && $sha1 !== null ) {
570 $this->mFileSearchOptions[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
571 }
572 }
573
574 /**
575 * Register a template dependency for this output
576 * @param Title $title
577 * @param int $page_id
578 * @param int $rev_id
579 * @return void
580 */
581 public function addTemplate( $title, $page_id, $rev_id ) {
582 $ns = $title->getNamespace();
583 $dbk = $title->getDBkey();
584 if ( !isset( $this->mTemplates[$ns] ) ) {
585 $this->mTemplates[$ns] = [];
586 }
587 $this->mTemplates[$ns][$dbk] = $page_id;
588 if ( !isset( $this->mTemplateIds[$ns] ) ) {
589 $this->mTemplateIds[$ns] = [];
590 }
591 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
592 }
593
594 /**
595 * @param Title $title Title object, must be an interwiki link
596 * @throws MWException If given invalid input
597 */
598 public function addInterwikiLink( $title ) {
599 if ( !$title->isExternal() ) {
600 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
601 }
602 $prefix = $title->getInterwiki();
603 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
604 $this->mInterwikiLinks[$prefix] = [];
605 }
606 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
607 }
608
609 /**
610 * Add some text to the "<head>".
611 * If $tag is set, the section with that tag will only be included once
612 * in a given page.
613 * @param string $section
614 * @param string|bool $tag
615 */
616 public function addHeadItem( $section, $tag = false ) {
617 if ( $tag !== false ) {
618 $this->mHeadItems[$tag] = $section;
619 } else {
620 $this->mHeadItems[] = $section;
621 }
622 }
623
624 public function addModules( $modules ) {
625 $this->mModules = array_merge( $this->mModules, (array)$modules );
626 }
627
628 public function addModuleScripts( $modules ) {
629 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
630 }
631
632 public function addModuleStyles( $modules ) {
633 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
634 }
635
636 /**
637 * Add one or more variables to be set in mw.config in JavaScript.
638 *
639 * @param string|array $keys Key or array of key/value pairs.
640 * @param mixed $value [optional] Value of the configuration variable.
641 * @since 1.23
642 */
643 public function addJsConfigVars( $keys, $value = null ) {
644 if ( is_array( $keys ) ) {
645 foreach ( $keys as $key => $value ) {
646 $this->mJsConfigVars[$key] = $value;
647 }
648 return;
649 }
650
651 $this->mJsConfigVars[$keys] = $value;
652 }
653
654 /**
655 * Copy items from the OutputPage object into this one
656 *
657 * @param OutputPage $out
658 */
659 public function addOutputPageMetadata( OutputPage $out ) {
660 $this->addModules( $out->getModules() );
661 $this->addModuleScripts( $out->getModuleScripts() );
662 $this->addModuleStyles( $out->getModuleStyles() );
663 $this->addJsConfigVars( $out->getJsConfigVars() );
664
665 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
666 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
667 }
668
669 /**
670 * Add a tracking category, getting the title from a system message,
671 * or print a debug message if the title is invalid.
672 *
673 * Any message used with this function should be registered so it will
674 * show up on Special:TrackingCategories. Core messages should be added
675 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
676 * should add to "TrackingCategories" in their extension.json.
677 *
678 * @param string $msg Message key
679 * @param Title $title title of the page which is being tracked
680 * @return bool Whether the addition was successful
681 * @since 1.25
682 */
683 public function addTrackingCategory( $msg, $title ) {
684 if ( $title->getNamespace() === NS_SPECIAL ) {
685 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
686 return false;
687 }
688
689 // Important to parse with correct title (bug 31469)
690 $cat = wfMessage( $msg )
691 ->title( $title )
692 ->inContentLanguage()
693 ->text();
694
695 # Allow tracking categories to be disabled by setting them to "-"
696 if ( $cat === '-' ) {
697 return false;
698 }
699
700 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
701 if ( $containerCategory ) {
702 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
703 return true;
704 } else {
705 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
706 return false;
707 }
708 }
709
710 /**
711 * Override the title to be used for display
712 *
713 * @note this is assumed to have been validated
714 * (check equal normalisation, etc.)
715 *
716 * @note this is expected to be safe HTML,
717 * ready to be served to the client.
718 *
719 * @param string $text Desired title text
720 */
721 public function setDisplayTitle( $text ) {
722 $this->setTitleText( $text );
723 $this->setProperty( 'displaytitle', $text );
724 }
725
726 /**
727 * Get the title to be used for display.
728 *
729 * As per the contract of setDisplayTitle(), this is safe HTML,
730 * ready to be served to the client.
731 *
732 * @return string HTML
733 */
734 public function getDisplayTitle() {
735 $t = $this->getTitleText();
736 if ( $t === '' ) {
737 return false;
738 }
739 return $t;
740 }
741
742 /**
743 * Fairly generic flag setter thingy.
744 * @param string $flag
745 */
746 public function setFlag( $flag ) {
747 $this->mFlags[$flag] = true;
748 }
749
750 public function getFlag( $flag ) {
751 return isset( $this->mFlags[$flag] );
752 }
753
754 /**
755 * Set a property to be stored in the page_props database table.
756 *
757 * page_props is a key value store indexed by the page ID. This allows
758 * the parser to set a property on a page which can then be quickly
759 * retrieved given the page ID or via a DB join when given the page
760 * title.
761 *
762 * Since 1.23, page_props are also indexed by numeric value, to allow
763 * for efficient "top k" queries of pages wrt a given property.
764 *
765 * setProperty() is thus used to propagate properties from the parsed
766 * page to request contexts other than a page view of the currently parsed
767 * article.
768 *
769 * Some applications examples:
770 *
771 * * To implement hidden categories, hiding pages from category listings
772 * by storing a property.
773 *
774 * * Overriding the displayed article title.
775 * @see ParserOutput::setDisplayTitle()
776 *
777 * * To implement image tagging, for example displaying an icon on an
778 * image thumbnail to indicate that it is listed for deletion on
779 * Wikimedia Commons.
780 * This is not actually implemented, yet but would be pretty cool.
781 *
782 * @note Do not use setProperty() to set a property which is only used
783 * in a context where the ParserOutput object itself is already available,
784 * for example a normal page view. There is no need to save such a property
785 * in the database since the text is already parsed. You can just hook
786 * OutputPageParserOutput and get your data out of the ParserOutput object.
787 *
788 * If you are writing an extension where you want to set a property in the
789 * parser which is used by an OutputPageParserOutput hook, you have to
790 * associate the extension data directly with the ParserOutput object.
791 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
792 *
793 * @par Example:
794 * @code
795 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
796 * @endcode
797 *
798 * And then later, in OutputPageParserOutput or similar:
799 *
800 * @par Example:
801 * @code
802 * $output->getExtensionData( 'my_ext_foo' );
803 * @endcode
804 *
805 * In MediaWiki 1.20 and older, you have to use a custom member variable
806 * within the ParserOutput object:
807 *
808 * @par Example:
809 * @code
810 * $parser->getOutput()->my_ext_foo = '...';
811 * @endcode
812 *
813 */
814 public function setProperty( $name, $value ) {
815 $this->mProperties[$name] = $value;
816 }
817
818 /**
819 * @param string $name The property name to look up.
820 *
821 * @return mixed|bool The value previously set using setProperty(). False if null or no value
822 * was set for the given property name.
823 *
824 * @note You need to use getProperties() to check for boolean and null properties.
825 */
826 public function getProperty( $name ) {
827 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
828 }
829
830 public function unsetProperty( $name ) {
831 unset( $this->mProperties[$name] );
832 }
833
834 public function getProperties() {
835 if ( !isset( $this->mProperties ) ) {
836 $this->mProperties = [];
837 }
838 return $this->mProperties;
839 }
840
841 /**
842 * Returns the options from its ParserOptions which have been taken
843 * into account to produce this output or false if not available.
844 * @return array
845 */
846 public function getUsedOptions() {
847 if ( !isset( $this->mAccessedOptions ) ) {
848 return [];
849 }
850 return array_keys( $this->mAccessedOptions );
851 }
852
853 /**
854 * Tags a parser option for use in the cache key for this parser output.
855 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
856 * The information gathered here is available via getUsedOptions(),
857 * and is used by ParserCache::save().
858 *
859 * @see ParserCache::getKey
860 * @see ParserCache::save
861 * @see ParserOptions::addExtraKey
862 * @see ParserOptions::optionsHash
863 * @param string $option
864 */
865 public function recordOption( $option ) {
866 $this->mAccessedOptions[$option] = true;
867 }
868
869 /**
870 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
871 * the ParserOutput object for later use during page output. The data will be cached along with
872 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
873 * database.
874 *
875 * This method is provided to overcome the unsafe practice of attaching extra information to a
876 * ParserObject by directly assigning member variables.
877 *
878 * To use setExtensionData() to pass extension information from a hook inside the parser to a
879 * hook in the page output, use this in the parser hook:
880 *
881 * @par Example:
882 * @code
883 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
884 * @endcode
885 *
886 * And then later, in OutputPageParserOutput or similar:
887 *
888 * @par Example:
889 * @code
890 * $output->getExtensionData( 'my_ext_foo' );
891 * @endcode
892 *
893 * In MediaWiki 1.20 and older, you have to use a custom member variable
894 * within the ParserOutput object:
895 *
896 * @par Example:
897 * @code
898 * $parser->getOutput()->my_ext_foo = '...';
899 * @endcode
900 *
901 * @since 1.21
902 *
903 * @param string $key The key for accessing the data. Extensions should take care to avoid
904 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
905 *
906 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
907 * the value.
908 */
909 public function setExtensionData( $key, $value ) {
910 if ( $value === null ) {
911 unset( $this->mExtensionData[$key] );
912 } else {
913 $this->mExtensionData[$key] = $value;
914 }
915 }
916
917 /**
918 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
919 * Typically, such data would be set while parsing the page, e.g. by a parser function.
920 *
921 * @since 1.21
922 *
923 * @param string $key The key to look up.
924 *
925 * @return mixed|null The value previously set for the given key using setExtensionData()
926 * or null if no value was set for this key.
927 */
928 public function getExtensionData( $key ) {
929 if ( isset( $this->mExtensionData[$key] ) ) {
930 return $this->mExtensionData[$key];
931 }
932
933 return null;
934 }
935
936 private static function getTimes( $clock = null ) {
937 $ret = [];
938 if ( !$clock || $clock === 'wall' ) {
939 $ret['wall'] = microtime( true );
940 }
941 if ( !$clock || $clock === 'cpu' ) {
942 $ru = wfGetRusage();
943 if ( $ru ) {
944 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
945 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
946 }
947 }
948 return $ret;
949 }
950
951 /**
952 * Resets the parse start timestamps for future calls to getTimeSinceStart()
953 * @since 1.22
954 */
955 public function resetParseStartTime() {
956 $this->mParseStartTime = self::getTimes();
957 }
958
959 /**
960 * Returns the time since resetParseStartTime() was last called
961 *
962 * Clocks available are:
963 * - wall: Wall clock time
964 * - cpu: CPU time (requires getrusage)
965 *
966 * @since 1.22
967 * @param string $clock
968 * @return float|null
969 */
970 public function getTimeSinceStart( $clock ) {
971 if ( !isset( $this->mParseStartTime[$clock] ) ) {
972 return null;
973 }
974
975 $end = self::getTimes( $clock );
976 return $end[$clock] - $this->mParseStartTime[$clock];
977 }
978
979 /**
980 * Sets parser limit report data for a key
981 *
982 * If $value consist of a list of two floats, it will be interpreted as
983 * (actual value, maximum allowed value). The presence of a "-" in $key will cause
984 * the first part of the key to be interpreted as a namespace.
985 *
986 * @since 1.22
987 * @param string $key Data key
988 * @param mixed $value Data value One of (float, string, bool, JSON serializable array)
989 */
990 public function setLimitReportData( $key, $value ) {
991 if ( is_array( $value ) ) {
992 if ( array_keys( $value ) === [ 0, 1 ]
993 && is_numeric( $value[0] )
994 && is_numeric( $value[1] )
995 ) {
996 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
997 } else {
998 $data = $value;
999 }
1000 } else {
1001 $data = $value;
1002 }
1003
1004 if ( strpos( $key, '-' ) ) {
1005 list( $ns, $name ) = explode( '-', $key, 2 );
1006 $this->mLimitReportData[$ns][$name] = $data;
1007 } else {
1008 $this->mLimitReportData[$key] = $data;
1009 }
1010 }
1011
1012 /**
1013 * Check whether the cache TTL was lowered due to dynamic content
1014 *
1015 * When content is determined by more than hard state (e.g. page edits),
1016 * such as template/file transclusions based on the current timestamp or
1017 * extension tags that generate lists based on queries, this return true.
1018 *
1019 * @return bool
1020 * @since 1.25
1021 */
1022 public function hasDynamicContent() {
1023 global $wgParserCacheExpireTime;
1024
1025 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1026 }
1027
1028 /**
1029 * Get or set the prevent-clickjacking flag
1030 *
1031 * @since 1.24
1032 * @param bool|null $flag New flag value, or null to leave it unchanged
1033 * @return bool Old flag value
1034 */
1035 public function preventClickjacking( $flag = null ) {
1036 return wfSetVar( $this->mPreventClickjacking, $flag );
1037 }
1038
1039 /**
1040 * Save space for serialization by removing useless values
1041 * @return array
1042 */
1043 public function __sleep() {
1044 return array_diff(
1045 array_keys( get_object_vars( $this ) ),
1046 [ 'mParseStartTime' ]
1047 );
1048 }
1049 }