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