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