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