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