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