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