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