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