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