Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[lhc/web/wiklou.git] / includes / parser / ParserOptions.php
1 <?php
2 /**
3 * Options for the PHP parser
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\ScopedCallback;
26
27 /**
28 * @brief Set options of the Parser
29 *
30 * How to add an option in core:
31 * 1. Add it to one of the arrays in ParserOptions::setDefaults()
32 * 2. If necessary, add an entry to ParserOptions::$inCacheKey
33 * 3. Add a getter and setter in the section for that.
34 *
35 * How to add an option in an extension:
36 * 1. Use the 'ParserOptionsRegister' hook to register it.
37 * 2. Where necessary, use $popt->getOption() and $popt->setOption()
38 * to access it.
39 *
40 * @ingroup Parser
41 */
42 class ParserOptions {
43
44 /**
45 * Flag indicating that newCanonical() accepts an IContextSource or the string 'canonical', for
46 * back-compat checks from extensions.
47 * @since 1.32
48 */
49 const HAS_NEWCANONICAL_FROM_CONTEXT = 1;
50
51 /**
52 * Default values for all options that are relevant for caching.
53 * @see self::getDefaults()
54 * @var array|null
55 */
56 private static $defaults = null;
57
58 /**
59 * Lazy-loaded options
60 * @var callable[]
61 */
62 private static $lazyOptions = [
63 'dateformat' => [ __CLASS__, 'initDateFormat' ],
64 'speculativeRevId' => [ __CLASS__, 'initSpeculativeRevId' ],
65 ];
66
67 /**
68 * Specify options that are included in the cache key
69 * @var array
70 */
71 private static $inCacheKey = [
72 'dateformat' => true,
73 'numberheadings' => true,
74 'thumbsize' => true,
75 'stubthreshold' => true,
76 'printable' => true,
77 'userlang' => true,
78 ];
79
80 /**
81 * Current values for all options that are relevant for caching.
82 * @var array
83 */
84 private $options;
85
86 /**
87 * Timestamp used for {{CURRENTDAY}} etc.
88 * @var string|null
89 * @note Caching based on parse time is handled externally
90 */
91 private $mTimestamp;
92
93 /**
94 * Stored user object
95 * @var User
96 * @todo Track this for caching somehow without fragmenting the cache insanely
97 */
98 private $mUser;
99
100 /**
101 * Function to be called when an option is accessed.
102 * @var callable|null
103 * @note Used for collecting used options, does not affect caching
104 */
105 private $onAccessCallback = null;
106
107 /**
108 * If the page being parsed is a redirect, this should hold the redirect
109 * target.
110 * @var Title|null
111 * @todo Track this for caching somehow
112 */
113 private $redirectTarget = null;
114
115 /**
116 * Appended to the options hash
117 */
118 private $mExtraKey = '';
119
120 /**
121 * @name Option accessors
122 * @{
123 */
124
125 /**
126 * Fetch an option and track that is was accessed
127 * @since 1.30
128 * @param string $name Option name
129 * @return mixed
130 */
131 public function getOption( $name ) {
132 if ( !array_key_exists( $name, $this->options ) ) {
133 throw new InvalidArgumentException( "Unknown parser option $name" );
134 }
135
136 $this->lazyLoadOption( $name );
137 if ( !empty( self::$inCacheKey[$name] ) ) {
138 $this->optionUsed( $name );
139 }
140 return $this->options[$name];
141 }
142
143 /**
144 * @param string $name Lazy load option without tracking usage
145 */
146 private function lazyLoadOption( $name ) {
147 if ( isset( self::$lazyOptions[$name] ) && $this->options[$name] === null ) {
148 $this->options[$name] = call_user_func( self::$lazyOptions[$name], $this, $name );
149 }
150 }
151
152 /**
153 * Set an option, generically
154 * @since 1.30
155 * @param string $name Option name
156 * @param mixed $value New value. Passing null will set null, unlike many
157 * of the existing accessors which ignore null for historical reasons.
158 * @return mixed Old value
159 */
160 public function setOption( $name, $value ) {
161 if ( !array_key_exists( $name, $this->options ) ) {
162 throw new InvalidArgumentException( "Unknown parser option $name" );
163 }
164 $old = $this->options[$name];
165 $this->options[$name] = $value;
166 return $old;
167 }
168
169 /**
170 * Legacy implementation
171 * @since 1.30 For implementing legacy setters only. Don't use this in new code.
172 * @deprecated since 1.30
173 * @param string $name Option name
174 * @param mixed $value New value. Passing null does not set the value.
175 * @return mixed Old value
176 */
177 protected function setOptionLegacy( $name, $value ) {
178 if ( !array_key_exists( $name, $this->options ) ) {
179 throw new InvalidArgumentException( "Unknown parser option $name" );
180 }
181 return wfSetVar( $this->options[$name], $value );
182 }
183
184 /**
185 * Whether to extract interlanguage links
186 *
187 * When true, interlanguage links will be returned by
188 * ParserOutput::getLanguageLinks() instead of generating link HTML.
189 *
190 * @return bool
191 */
192 public function getInterwikiMagic() {
193 return $this->getOption( 'interwikiMagic' );
194 }
195
196 /**
197 * Specify whether to extract interlanguage links
198 * @param bool|null $x New value (null is no change)
199 * @return bool Old value
200 */
201 public function setInterwikiMagic( $x ) {
202 return $this->setOptionLegacy( 'interwikiMagic', $x );
203 }
204
205 /**
206 * Allow all external images inline?
207 * @return bool
208 */
209 public function getAllowExternalImages() {
210 return $this->getOption( 'allowExternalImages' );
211 }
212
213 /**
214 * Allow all external images inline?
215 * @param bool|null $x New value (null is no change)
216 * @return bool Old value
217 */
218 public function setAllowExternalImages( $x ) {
219 return $this->setOptionLegacy( 'allowExternalImages', $x );
220 }
221
222 /**
223 * External images to allow
224 *
225 * When self::getAllowExternalImages() is false
226 *
227 * @return string|string[] URLs to allow
228 */
229 public function getAllowExternalImagesFrom() {
230 return $this->getOption( 'allowExternalImagesFrom' );
231 }
232
233 /**
234 * External images to allow
235 *
236 * When self::getAllowExternalImages() is false
237 *
238 * @param string|string[]|null $x New value (null is no change)
239 * @return string|string[] Old value
240 */
241 public function setAllowExternalImagesFrom( $x ) {
242 return $this->setOptionLegacy( 'allowExternalImagesFrom', $x );
243 }
244
245 /**
246 * Use the on-wiki external image whitelist?
247 * @return bool
248 */
249 public function getEnableImageWhitelist() {
250 return $this->getOption( 'enableImageWhitelist' );
251 }
252
253 /**
254 * Use the on-wiki external image whitelist?
255 * @param bool|null $x New value (null is no change)
256 * @return bool Old value
257 */
258 public function setEnableImageWhitelist( $x ) {
259 return $this->setOptionLegacy( 'enableImageWhitelist', $x );
260 }
261
262 /**
263 * Automatically number headings?
264 * @return bool
265 */
266 public function getNumberHeadings() {
267 return $this->getOption( 'numberheadings' );
268 }
269
270 /**
271 * Automatically number headings?
272 * @param bool|null $x New value (null is no change)
273 * @return bool Old value
274 */
275 public function setNumberHeadings( $x ) {
276 return $this->setOptionLegacy( 'numberheadings', $x );
277 }
278
279 /**
280 * Allow inclusion of special pages?
281 * @return bool
282 */
283 public function getAllowSpecialInclusion() {
284 return $this->getOption( 'allowSpecialInclusion' );
285 }
286
287 /**
288 * Allow inclusion of special pages?
289 * @param bool|null $x New value (null is no change)
290 * @return bool Old value
291 */
292 public function setAllowSpecialInclusion( $x ) {
293 return $this->setOptionLegacy( 'allowSpecialInclusion', $x );
294 }
295
296 /**
297 * Use tidy to cleanup output HTML?
298 * @return bool
299 */
300 public function getTidy() {
301 return $this->getOption( 'tidy' );
302 }
303
304 /**
305 * Use tidy to cleanup output HTML?
306 * @param bool|null $x New value (null is no change)
307 * @return bool Old value
308 */
309 public function setTidy( $x ) {
310 return $this->setOptionLegacy( 'tidy', $x );
311 }
312
313 /**
314 * Parsing an interface message?
315 * @return bool
316 */
317 public function getInterfaceMessage() {
318 return $this->getOption( 'interfaceMessage' );
319 }
320
321 /**
322 * Parsing an interface message?
323 * @param bool|null $x New value (null is no change)
324 * @return bool Old value
325 */
326 public function setInterfaceMessage( $x ) {
327 return $this->setOptionLegacy( 'interfaceMessage', $x );
328 }
329
330 /**
331 * Target language for the parse
332 * @return Language|null
333 */
334 public function getTargetLanguage() {
335 return $this->getOption( 'targetLanguage' );
336 }
337
338 /**
339 * Target language for the parse
340 * @param Language|null $x New value
341 * @return Language|null Old value
342 */
343 public function setTargetLanguage( $x ) {
344 return $this->setOption( 'targetLanguage', $x );
345 }
346
347 /**
348 * Maximum size of template expansions, in bytes
349 * @return int
350 */
351 public function getMaxIncludeSize() {
352 return $this->getOption( 'maxIncludeSize' );
353 }
354
355 /**
356 * Maximum size of template expansions, in bytes
357 * @param int|null $x New value (null is no change)
358 * @return int Old value
359 */
360 public function setMaxIncludeSize( $x ) {
361 return $this->setOptionLegacy( 'maxIncludeSize', $x );
362 }
363
364 /**
365 * Maximum number of nodes touched by PPFrame::expand()
366 * @return int
367 */
368 public function getMaxPPNodeCount() {
369 return $this->getOption( 'maxPPNodeCount' );
370 }
371
372 /**
373 * Maximum number of nodes touched by PPFrame::expand()
374 * @param int|null $x New value (null is no change)
375 * @return int Old value
376 */
377 public function setMaxPPNodeCount( $x ) {
378 return $this->setOptionLegacy( 'maxPPNodeCount', $x );
379 }
380
381 /**
382 * Maximum number of nodes generated by Preprocessor::preprocessToObj()
383 * @return int
384 */
385 public function getMaxGeneratedPPNodeCount() {
386 return $this->getOption( 'maxGeneratedPPNodeCount' );
387 }
388
389 /**
390 * Maximum number of nodes generated by Preprocessor::preprocessToObj()
391 * @param int|null $x New value (null is no change)
392 * @return int
393 */
394 public function setMaxGeneratedPPNodeCount( $x ) {
395 return $this->setOptionLegacy( 'maxGeneratedPPNodeCount', $x );
396 }
397
398 /**
399 * Maximum recursion depth in PPFrame::expand()
400 * @return int
401 */
402 public function getMaxPPExpandDepth() {
403 return $this->getOption( 'maxPPExpandDepth' );
404 }
405
406 /**
407 * Maximum recursion depth for templates within templates
408 * @return int
409 */
410 public function getMaxTemplateDepth() {
411 return $this->getOption( 'maxTemplateDepth' );
412 }
413
414 /**
415 * Maximum recursion depth for templates within templates
416 * @param int|null $x New value (null is no change)
417 * @return int Old value
418 */
419 public function setMaxTemplateDepth( $x ) {
420 return $this->setOptionLegacy( 'maxTemplateDepth', $x );
421 }
422
423 /**
424 * Maximum number of calls per parse to expensive parser functions
425 * @since 1.20
426 * @return int
427 */
428 public function getExpensiveParserFunctionLimit() {
429 return $this->getOption( 'expensiveParserFunctionLimit' );
430 }
431
432 /**
433 * Maximum number of calls per parse to expensive parser functions
434 * @since 1.20
435 * @param int|null $x New value (null is no change)
436 * @return int Old value
437 */
438 public function setExpensiveParserFunctionLimit( $x ) {
439 return $this->setOptionLegacy( 'expensiveParserFunctionLimit', $x );
440 }
441
442 /**
443 * Remove HTML comments
444 * @warning Only applies to preprocess operations
445 * @return bool
446 */
447 public function getRemoveComments() {
448 return $this->getOption( 'removeComments' );
449 }
450
451 /**
452 * Remove HTML comments
453 * @warning Only applies to preprocess operations
454 * @param bool|null $x New value (null is no change)
455 * @return bool Old value
456 */
457 public function setRemoveComments( $x ) {
458 return $this->setOptionLegacy( 'removeComments', $x );
459 }
460
461 /**
462 * Enable limit report in an HTML comment on output
463 * @return bool
464 */
465 public function getEnableLimitReport() {
466 return $this->getOption( 'enableLimitReport' );
467 }
468
469 /**
470 * Enable limit report in an HTML comment on output
471 * @param bool|null $x New value (null is no change)
472 * @return bool Old value
473 */
474 public function enableLimitReport( $x = true ) {
475 return $this->setOptionLegacy( 'enableLimitReport', $x );
476 }
477
478 /**
479 * Clean up signature texts?
480 * @see Parser::cleanSig
481 * @return bool
482 */
483 public function getCleanSignatures() {
484 return $this->getOption( 'cleanSignatures' );
485 }
486
487 /**
488 * Clean up signature texts?
489 * @see Parser::cleanSig
490 * @param bool|null $x New value (null is no change)
491 * @return bool Old value
492 */
493 public function setCleanSignatures( $x ) {
494 return $this->setOptionLegacy( 'cleanSignatures', $x );
495 }
496
497 /**
498 * Target attribute for external links
499 * @return string
500 */
501 public function getExternalLinkTarget() {
502 return $this->getOption( 'externalLinkTarget' );
503 }
504
505 /**
506 * Target attribute for external links
507 * @param string|null $x New value (null is no change)
508 * @return string Old value
509 */
510 public function setExternalLinkTarget( $x ) {
511 return $this->setOptionLegacy( 'externalLinkTarget', $x );
512 }
513
514 /**
515 * Whether content conversion should be disabled
516 * @return bool
517 */
518 public function getDisableContentConversion() {
519 return $this->getOption( 'disableContentConversion' );
520 }
521
522 /**
523 * Whether content conversion should be disabled
524 * @param bool|null $x New value (null is no change)
525 * @return bool Old value
526 */
527 public function disableContentConversion( $x = true ) {
528 return $this->setOptionLegacy( 'disableContentConversion', $x );
529 }
530
531 /**
532 * Whether title conversion should be disabled
533 * @return bool
534 */
535 public function getDisableTitleConversion() {
536 return $this->getOption( 'disableTitleConversion' );
537 }
538
539 /**
540 * Whether title conversion should be disabled
541 * @param bool|null $x New value (null is no change)
542 * @return bool Old value
543 */
544 public function disableTitleConversion( $x = true ) {
545 return $this->setOptionLegacy( 'disableTitleConversion', $x );
546 }
547
548 /**
549 * Thumb size preferred by the user.
550 * @return int
551 */
552 public function getThumbSize() {
553 return $this->getOption( 'thumbsize' );
554 }
555
556 /**
557 * Thumb size preferred by the user.
558 * @param int|null $x New value (null is no change)
559 * @return int Old value
560 */
561 public function setThumbSize( $x ) {
562 return $this->setOptionLegacy( 'thumbsize', $x );
563 }
564
565 /**
566 * Thumb size preferred by the user.
567 * @return int
568 */
569 public function getStubThreshold() {
570 return $this->getOption( 'stubthreshold' );
571 }
572
573 /**
574 * Thumb size preferred by the user.
575 * @param int|null $x New value (null is no change)
576 * @return int Old value
577 */
578 public function setStubThreshold( $x ) {
579 return $this->setOptionLegacy( 'stubthreshold', $x );
580 }
581
582 /**
583 * Parsing the page for a "preview" operation?
584 * @return bool
585 */
586 public function getIsPreview() {
587 return $this->getOption( 'isPreview' );
588 }
589
590 /**
591 * Parsing the page for a "preview" operation?
592 * @param bool|null $x New value (null is no change)
593 * @return bool Old value
594 */
595 public function setIsPreview( $x ) {
596 return $this->setOptionLegacy( 'isPreview', $x );
597 }
598
599 /**
600 * Parsing the page for a "preview" operation on a single section?
601 * @return bool
602 */
603 public function getIsSectionPreview() {
604 return $this->getOption( 'isSectionPreview' );
605 }
606
607 /**
608 * Parsing the page for a "preview" operation on a single section?
609 * @param bool|null $x New value (null is no change)
610 * @return bool Old value
611 */
612 public function setIsSectionPreview( $x ) {
613 return $this->setOptionLegacy( 'isSectionPreview', $x );
614 }
615
616 /**
617 * Parsing the printable version of the page?
618 * @return bool
619 */
620 public function getIsPrintable() {
621 return $this->getOption( 'printable' );
622 }
623
624 /**
625 * Parsing the printable version of the page?
626 * @param bool|null $x New value (null is no change)
627 * @return bool Old value
628 */
629 public function setIsPrintable( $x ) {
630 return $this->setOptionLegacy( 'printable', $x );
631 }
632
633 /**
634 * Transform wiki markup when saving the page?
635 * @return bool
636 */
637 public function getPreSaveTransform() {
638 return $this->getOption( 'preSaveTransform' );
639 }
640
641 /**
642 * Transform wiki markup when saving the page?
643 * @param bool|null $x New value (null is no change)
644 * @return bool Old value
645 */
646 public function setPreSaveTransform( $x ) {
647 return $this->setOptionLegacy( 'preSaveTransform', $x );
648 }
649
650 /**
651 * Date format index
652 * @return string
653 */
654 public function getDateFormat() {
655 return $this->getOption( 'dateformat' );
656 }
657
658 /**
659 * Lazy initializer for dateFormat
660 * @param ParserOptions $popt
661 * @return string
662 */
663 private static function initDateFormat( ParserOptions $popt ) {
664 return $popt->mUser->getDatePreference();
665 }
666
667 /**
668 * Date format index
669 * @param string|null $x New value (null is no change)
670 * @return string Old value
671 */
672 public function setDateFormat( $x ) {
673 return $this->setOptionLegacy( 'dateformat', $x );
674 }
675
676 /**
677 * Get the user language used by the parser for this page and split the parser cache.
678 *
679 * @warning Calling this causes the parser cache to be fragmented by user language!
680 * To avoid cache fragmentation, output should not depend on the user language.
681 * Use Parser::getFunctionLang() or Parser::getTargetLanguage() instead!
682 *
683 * @note This function will trigger a cache fragmentation by recording the
684 * 'userlang' option, see optionUsed(). This is done to avoid cache pollution
685 * when the page is rendered based on the language of the user.
686 *
687 * @note When saving, this will return the default language instead of the user's.
688 * {{int: }} uses this which used to produce inconsistent link tables (T16404).
689 *
690 * @return Language
691 * @since 1.19
692 */
693 public function getUserLangObj() {
694 return $this->getOption( 'userlang' );
695 }
696
697 /**
698 * Same as getUserLangObj() but returns a string instead.
699 *
700 * @warning Calling this causes the parser cache to be fragmented by user language!
701 * To avoid cache fragmentation, output should not depend on the user language.
702 * Use Parser::getFunctionLang() or Parser::getTargetLanguage() instead!
703 *
704 * @see getUserLangObj()
705 *
706 * @return string Language code
707 * @since 1.17
708 */
709 public function getUserLang() {
710 return $this->getUserLangObj()->getCode();
711 }
712
713 /**
714 * Set the user language used by the parser for this page and split the parser cache.
715 * @param string|Language $x New value
716 * @return Language Old value
717 */
718 public function setUserLang( $x ) {
719 if ( is_string( $x ) ) {
720 $x = Language::factory( $x );
721 }
722
723 return $this->setOptionLegacy( 'userlang', $x );
724 }
725
726 /**
727 * Are magic ISBN links enabled?
728 * @since 1.28
729 * @return bool
730 */
731 public function getMagicISBNLinks() {
732 return $this->getOption( 'magicISBNLinks' );
733 }
734
735 /**
736 * Are magic PMID links enabled?
737 * @since 1.28
738 * @return bool
739 */
740 public function getMagicPMIDLinks() {
741 return $this->getOption( 'magicPMIDLinks' );
742 }
743
744 /**
745 * Are magic RFC links enabled?
746 * @since 1.28
747 * @return bool
748 */
749 public function getMagicRFCLinks() {
750 return $this->getOption( 'magicRFCLinks' );
751 }
752
753 /**
754 * If the wiki is configured to allow raw html ($wgRawHtml = true)
755 * is it allowed in the specific case of parsing this page.
756 *
757 * This is meant to disable unsafe parser tags in cases where
758 * a malicious user may control the input to the parser.
759 *
760 * @note This is expected to be true for normal pages even if the
761 * wiki has $wgRawHtml disabled in general. The setting only
762 * signifies that raw html would be unsafe in the current context
763 * provided that raw html is allowed at all.
764 * @since 1.29
765 * @return bool
766 */
767 public function getAllowUnsafeRawHtml() {
768 return $this->getOption( 'allowUnsafeRawHtml' );
769 }
770
771 /**
772 * If the wiki is configured to allow raw html ($wgRawHtml = true)
773 * is it allowed in the specific case of parsing this page.
774 * @see self::getAllowUnsafeRawHtml()
775 * @since 1.29
776 * @param bool|null $x Value to set or null to get current value
777 * @return bool Current value for allowUnsafeRawHtml
778 */
779 public function setAllowUnsafeRawHtml( $x ) {
780 return $this->setOptionLegacy( 'allowUnsafeRawHtml', $x );
781 }
782
783 /**
784 * Class to use to wrap output from Parser::parse()
785 * @since 1.30
786 * @return string|bool
787 */
788 public function getWrapOutputClass() {
789 return $this->getOption( 'wrapclass' );
790 }
791
792 /**
793 * CSS class to use to wrap output from Parser::parse()
794 * @since 1.30
795 * @param string $className Class name to use for wrapping.
796 * Passing false to indicate "no wrapping" was deprecated in MediaWiki 1.31.
797 * @return string|bool Current value
798 */
799 public function setWrapOutputClass( $className ) {
800 if ( $className === true ) { // DWIM, they probably want the default class name
801 $className = 'mw-parser-output';
802 }
803 if ( $className === false ) {
804 wfDeprecated( __METHOD__ . '( false )', '1.31' );
805 }
806 return $this->setOption( 'wrapclass', $className );
807 }
808
809 /**
810 * Callback for current revision fetching; first argument to call_user_func().
811 * @since 1.24
812 * @return callable
813 */
814 public function getCurrentRevisionCallback() {
815 return $this->getOption( 'currentRevisionCallback' );
816 }
817
818 /**
819 * Callback for current revision fetching; first argument to call_user_func().
820 * @since 1.24
821 * @param callable|null $x New value (null is no change)
822 * @return callable Old value
823 */
824 public function setCurrentRevisionCallback( $x ) {
825 return $this->setOptionLegacy( 'currentRevisionCallback', $x );
826 }
827
828 /**
829 * Callback for template fetching; first argument to call_user_func().
830 * @return callable
831 */
832 public function getTemplateCallback() {
833 return $this->getOption( 'templateCallback' );
834 }
835
836 /**
837 * Callback for template fetching; first argument to call_user_func().
838 * @param callable|null $x New value (null is no change)
839 * @return callable Old value
840 */
841 public function setTemplateCallback( $x ) {
842 return $this->setOptionLegacy( 'templateCallback', $x );
843 }
844
845 /**
846 * A guess for {{REVISIONID}}, calculated using the callback provided via
847 * setSpeculativeRevIdCallback(). For consistency, the value will be calculated upon the
848 * first call of this method, and re-used for subsequent calls.
849 *
850 * If no callback was defined via setSpeculativeRevIdCallback(), this method will return false.
851 *
852 * @since 1.32
853 * @return int|false
854 */
855 public function getSpeculativeRevId() {
856 return $this->getOption( 'speculativeRevId' );
857 }
858
859 /**
860 * Callback registered with ParserOptions::$lazyOptions, triggered by getSpeculativeRevId().
861 *
862 * @param ParserOptions $popt
863 * @return bool|false
864 */
865 private static function initSpeculativeRevId( ParserOptions $popt ) {
866 $cb = $popt->getOption( 'speculativeRevIdCallback' );
867 $id = $cb ? $cb() : null;
868
869 // returning null would result in this being re-called every access
870 return $id ?? false;
871 }
872
873 /**
874 * Callback to generate a guess for {{REVISIONID}}
875 * @since 1.28
876 * @deprecated since 1.32, use getSpeculativeRevId() instead!
877 * @return callable|null
878 */
879 public function getSpeculativeRevIdCallback() {
880 return $this->getOption( 'speculativeRevIdCallback' );
881 }
882
883 /**
884 * Callback to generate a guess for {{REVISIONID}}
885 * @since 1.28
886 * @param callable|null $x New value (null is no change)
887 * @return callable|null Old value
888 */
889 public function setSpeculativeRevIdCallback( $x ) {
890 $this->setOption( 'speculativeRevId', null ); // reset
891 return $this->setOptionLegacy( 'speculativeRevIdCallback', $x );
892 }
893
894 /**@}*/
895
896 /**
897 * Timestamp used for {{CURRENTDAY}} etc.
898 * @return string TS_MW timestamp
899 */
900 public function getTimestamp() {
901 if ( !isset( $this->mTimestamp ) ) {
902 $this->mTimestamp = wfTimestampNow();
903 }
904 return $this->mTimestamp;
905 }
906
907 /**
908 * Timestamp used for {{CURRENTDAY}} etc.
909 * @param string|null $x New value (null is no change)
910 * @return string Old value
911 */
912 public function setTimestamp( $x ) {
913 return wfSetVar( $this->mTimestamp, $x );
914 }
915
916 /**
917 * Set the redirect target.
918 *
919 * Note that setting or changing this does not *make* the page a redirect
920 * or change its target, it merely records the information for reference
921 * during the parse.
922 *
923 * @since 1.24
924 * @param Title|null $title
925 */
926 function setRedirectTarget( $title ) {
927 $this->redirectTarget = $title;
928 }
929
930 /**
931 * Get the previously-set redirect target.
932 *
933 * @since 1.24
934 * @return Title|null
935 */
936 function getRedirectTarget() {
937 return $this->redirectTarget;
938 }
939
940 /**
941 * Extra key that should be present in the parser cache key.
942 * @warning Consider registering your additional options with the
943 * ParserOptionsRegister hook instead of using this method.
944 * @param string $key
945 */
946 public function addExtraKey( $key ) {
947 $this->mExtraKey .= '!' . $key;
948 }
949
950 /**
951 * Current user
952 * @return User
953 */
954 public function getUser() {
955 return $this->mUser;
956 }
957
958 /**
959 * @warning For interaction with the parser cache, use
960 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
961 * @param User|null $user
962 * @param Language|null $lang
963 */
964 public function __construct( $user = null, $lang = null ) {
965 if ( $user === null ) {
966 global $wgUser;
967 if ( $wgUser === null ) {
968 $user = new User;
969 } else {
970 $user = $wgUser;
971 }
972 }
973 if ( $lang === null ) {
974 global $wgLang;
975 if ( !StubObject::isRealObject( $wgLang ) ) {
976 $wgLang->_unstub();
977 }
978 $lang = $wgLang;
979 }
980 $this->initialiseFromUser( $user, $lang );
981 }
982
983 /**
984 * Get a ParserOptions object for an anonymous user
985 * @warning For interaction with the parser cache, use
986 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
987 * @since 1.27
988 * @return ParserOptions
989 */
990 public static function newFromAnon() {
991 return new ParserOptions( new User,
992 MediaWikiServices::getInstance()->getContentLanguage() );
993 }
994
995 /**
996 * Get a ParserOptions object from a given user.
997 * Language will be taken from $wgLang.
998 *
999 * @warning For interaction with the parser cache, use
1000 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
1001 * @param User $user
1002 * @return ParserOptions
1003 */
1004 public static function newFromUser( $user ) {
1005 return new ParserOptions( $user );
1006 }
1007
1008 /**
1009 * Get a ParserOptions object from a given user and language
1010 *
1011 * @warning For interaction with the parser cache, use
1012 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
1013 * @param User $user
1014 * @param Language $lang
1015 * @return ParserOptions
1016 */
1017 public static function newFromUserAndLang( User $user, Language $lang ) {
1018 return new ParserOptions( $user, $lang );
1019 }
1020
1021 /**
1022 * Get a ParserOptions object from a IContextSource object
1023 *
1024 * @warning For interaction with the parser cache, use
1025 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
1026 * @param IContextSource $context
1027 * @return ParserOptions
1028 */
1029 public static function newFromContext( IContextSource $context ) {
1030 return new ParserOptions( $context->getUser(), $context->getLanguage() );
1031 }
1032
1033 /**
1034 * Creates a "canonical" ParserOptions object
1035 *
1036 * For historical reasons, certain options have default values that are
1037 * different from the canonical values used for caching.
1038 *
1039 * @since 1.30
1040 * @since 1.32 Added string and IContextSource as options for the first parameter
1041 * @param IContextSource|string|User|null $context
1042 * - If an IContextSource, the options are initialized based on the source's User and Language.
1043 * - If the string 'canonical', the options are initialized with an anonymous user and
1044 * the content language.
1045 * - If a User or null, the options are initialized for that User (or $wgUser if null).
1046 * 'userlang' is taken from the $userLang parameter, defaulting to $wgLang if that is null.
1047 * @param Language|StubObject|null $userLang (see above)
1048 * @return ParserOptions
1049 */
1050 public static function newCanonical( $context = null, $userLang = null ) {
1051 if ( $context instanceof IContextSource ) {
1052 $ret = self::newFromContext( $context );
1053 } elseif ( $context === 'canonical' ) {
1054 $ret = self::newFromAnon();
1055 } elseif ( $context instanceof User || $context === null ) {
1056 $ret = new self( $context, $userLang );
1057 } else {
1058 throw new InvalidArgumentException(
1059 '$context must be an IContextSource, the string "canonical", a User, or null'
1060 );
1061 }
1062
1063 foreach ( self::getCanonicalOverrides() as $k => $v ) {
1064 $ret->setOption( $k, $v );
1065 }
1066 return $ret;
1067 }
1068
1069 /**
1070 * Get default option values
1071 * @warning If you change the default for an existing option (unless it's
1072 * being overridden by self::getCanonicalOverrides()), all existing parser
1073 * cache entries will be invalid. To avoid bugs, you'll need to handle
1074 * that somehow (e.g. with the RejectParserCacheValue hook) because
1075 * MediaWiki won't do it for you.
1076 * @return array
1077 */
1078 private static function getDefaults() {
1079 global $wgInterwikiMagic, $wgAllowExternalImages,
1080 $wgAllowExternalImagesFrom, $wgEnableImageWhitelist, $wgAllowSpecialInclusion,
1081 $wgMaxArticleSize, $wgMaxPPNodeCount, $wgMaxTemplateDepth, $wgMaxPPExpandDepth,
1082 $wgCleanSignatures, $wgExternalLinkTarget, $wgExpensiveParserFunctionLimit,
1083 $wgMaxGeneratedPPNodeCount, $wgDisableLangConversion, $wgDisableTitleConversion,
1084 $wgEnableMagicLinks;
1085
1086 if ( self::$defaults === null ) {
1087 // *UPDATE* ParserOptions::matches() if any of this changes as needed
1088 self::$defaults = [
1089 'dateformat' => null,
1090 'tidy' => true,
1091 'interfaceMessage' => false,
1092 'targetLanguage' => null,
1093 'removeComments' => true,
1094 'enableLimitReport' => false,
1095 'preSaveTransform' => true,
1096 'isPreview' => false,
1097 'isSectionPreview' => false,
1098 'printable' => false,
1099 'allowUnsafeRawHtml' => true,
1100 'wrapclass' => 'mw-parser-output',
1101 'currentRevisionCallback' => [ Parser::class, 'statelessFetchRevision' ],
1102 'templateCallback' => [ Parser::class, 'statelessFetchTemplate' ],
1103 'speculativeRevIdCallback' => null,
1104 'speculativeRevId' => null,
1105 ];
1106
1107 Hooks::run( 'ParserOptionsRegister', [
1108 &self::$defaults,
1109 &self::$inCacheKey,
1110 &self::$lazyOptions,
1111 ] );
1112
1113 ksort( self::$inCacheKey );
1114 }
1115
1116 // Unit tests depend on being able to modify the globals at will
1117 return self::$defaults + [
1118 'interwikiMagic' => $wgInterwikiMagic,
1119 'allowExternalImages' => $wgAllowExternalImages,
1120 'allowExternalImagesFrom' => $wgAllowExternalImagesFrom,
1121 'enableImageWhitelist' => $wgEnableImageWhitelist,
1122 'allowSpecialInclusion' => $wgAllowSpecialInclusion,
1123 'maxIncludeSize' => $wgMaxArticleSize * 1024,
1124 'maxPPNodeCount' => $wgMaxPPNodeCount,
1125 'maxGeneratedPPNodeCount' => $wgMaxGeneratedPPNodeCount,
1126 'maxPPExpandDepth' => $wgMaxPPExpandDepth,
1127 'maxTemplateDepth' => $wgMaxTemplateDepth,
1128 'expensiveParserFunctionLimit' => $wgExpensiveParserFunctionLimit,
1129 'externalLinkTarget' => $wgExternalLinkTarget,
1130 'cleanSignatures' => $wgCleanSignatures,
1131 'disableContentConversion' => $wgDisableLangConversion,
1132 'disableTitleConversion' => $wgDisableLangConversion || $wgDisableTitleConversion,
1133 'magicISBNLinks' => $wgEnableMagicLinks['ISBN'],
1134 'magicPMIDLinks' => $wgEnableMagicLinks['PMID'],
1135 'magicRFCLinks' => $wgEnableMagicLinks['RFC'],
1136 'numberheadings' => User::getDefaultOption( 'numberheadings' ),
1137 'thumbsize' => User::getDefaultOption( 'thumbsize' ),
1138 'stubthreshold' => 0,
1139 'userlang' => MediaWikiServices::getInstance()->getContentLanguage(),
1140 ];
1141 }
1142
1143 /**
1144 * Get "canonical" non-default option values
1145 * @see self::newCanonical
1146 * @warning If you change the override for an existing option, all existing
1147 * parser cache entries will be invalid. To avoid bugs, you'll need to
1148 * handle that somehow (e.g. with the RejectParserCacheValue hook) because
1149 * MediaWiki won't do it for you.
1150 * @return array
1151 */
1152 private static function getCanonicalOverrides() {
1153 global $wgEnableParserLimitReporting;
1154
1155 return [
1156 'enableLimitReport' => $wgEnableParserLimitReporting,
1157 ];
1158 }
1159
1160 /**
1161 * Get user options
1162 *
1163 * @param User $user
1164 * @param Language $lang
1165 */
1166 private function initialiseFromUser( $user, $lang ) {
1167 $this->options = self::getDefaults();
1168
1169 $this->mUser = $user;
1170 $this->options['numberheadings'] = $user->getOption( 'numberheadings' );
1171 $this->options['thumbsize'] = $user->getOption( 'thumbsize' );
1172 $this->options['stubthreshold'] = $user->getStubThreshold();
1173 $this->options['userlang'] = $lang;
1174 }
1175
1176 /**
1177 * Check if these options match that of another options set
1178 *
1179 * This ignores report limit settings that only affect HTML comments
1180 *
1181 * @param ParserOptions $other
1182 * @return bool
1183 * @since 1.25
1184 */
1185 public function matches( ParserOptions $other ) {
1186 // Compare most options
1187 $options = array_keys( $this->options );
1188 $options = array_diff( $options, [
1189 'enableLimitReport', // only affects HTML comments
1190 ] );
1191 foreach ( $options as $option ) {
1192 // Resolve any lazy options
1193 $this->lazyLoadOption( $option );
1194 $other->lazyLoadOption( $option );
1195
1196 $o1 = $this->optionToString( $this->options[$option] );
1197 $o2 = $this->optionToString( $other->options[$option] );
1198 if ( $o1 !== $o2 ) {
1199 return false;
1200 }
1201 }
1202
1203 // Compare most other fields
1204 $fields = array_keys( get_class_vars( __CLASS__ ) );
1205 $fields = array_diff( $fields, [
1206 'defaults', // static
1207 'lazyOptions', // static
1208 'inCacheKey', // static
1209 'options', // Already checked above
1210 'onAccessCallback', // only used for ParserOutput option tracking
1211 ] );
1212 foreach ( $fields as $field ) {
1213 if ( !is_object( $this->$field ) && $this->$field !== $other->$field ) {
1214 return false;
1215 }
1216 }
1217
1218 return true;
1219 }
1220
1221 /**
1222 * @param ParserOptions $other
1223 * @return bool Whether the cache key relevant options match those of $other
1224 * @since 1.33
1225 */
1226 public function matchesForCacheKey( ParserOptions $other ) {
1227 foreach ( self::allCacheVaryingOptions() as $option ) {
1228 // Populate any lazy options
1229 $this->lazyLoadOption( $option );
1230 $other->lazyLoadOption( $option );
1231
1232 $o1 = $this->optionToString( $this->options[$option] );
1233 $o2 = $this->optionToString( $other->options[$option] );
1234 if ( $o1 !== $o2 ) {
1235 return false;
1236 }
1237 }
1238
1239 return true;
1240 }
1241
1242 /**
1243 * Registers a callback for tracking which ParserOptions which are used.
1244 * This is a private API with the parser.
1245 * @param callable $callback
1246 */
1247 public function registerWatcher( $callback ) {
1248 $this->onAccessCallback = $callback;
1249 }
1250
1251 /**
1252 * Called when an option is accessed.
1253 * Calls the watcher that was set using registerWatcher().
1254 * Typically, the watcher callback is ParserOutput::registerOption().
1255 * The information registered that way will be used by ParserCache::save().
1256 *
1257 * @param string $optionName Name of the option
1258 */
1259 public function optionUsed( $optionName ) {
1260 if ( $this->onAccessCallback ) {
1261 call_user_func( $this->onAccessCallback, $optionName );
1262 }
1263 }
1264
1265 /**
1266 * Return all option keys that vary the options hash
1267 * @since 1.30
1268 * @return string[]
1269 */
1270 public static function allCacheVaryingOptions() {
1271 // Trigger a call to the 'ParserOptionsRegister' hook if it hasn't
1272 // already been called.
1273 if ( self::$defaults === null ) {
1274 self::getDefaults();
1275 }
1276 return array_keys( array_filter( self::$inCacheKey ) );
1277 }
1278
1279 /**
1280 * Convert an option to a string value
1281 * @param mixed $value
1282 * @return string
1283 */
1284 private function optionToString( $value ) {
1285 if ( $value === true ) {
1286 return '1';
1287 } elseif ( $value === false ) {
1288 return '0';
1289 } elseif ( $value === null ) {
1290 return '';
1291 } elseif ( $value instanceof Language ) {
1292 return $value->getCode();
1293 } elseif ( is_array( $value ) ) {
1294 return '[' . implode( ',', array_map( [ $this, 'optionToString' ], $value ) ) . ']';
1295 } else {
1296 return (string)$value;
1297 }
1298 }
1299
1300 /**
1301 * Generate a hash string with the values set on these ParserOptions
1302 * for the keys given in the array.
1303 * This will be used as part of the hash key for the parser cache,
1304 * so users sharing the options with vary for the same page share
1305 * the same cached data safely.
1306 *
1307 * @since 1.17
1308 * @param string[] $forOptions
1309 * @param Title|null $title Used to get the content language of the page (since r97636)
1310 * @return string Page rendering hash
1311 */
1312 public function optionsHash( $forOptions, $title = null ) {
1313 global $wgRenderHashAppend;
1314
1315 $inCacheKey = self::allCacheVaryingOptions();
1316
1317 // Resolve any lazy options
1318 $lazyOpts = array_intersect( $forOptions, $inCacheKey, array_keys( self::$lazyOptions ) );
1319 foreach ( $lazyOpts as $k ) {
1320 $this->lazyLoadOption( $k );
1321 }
1322
1323 $options = $this->options;
1324 $defaults = self::getCanonicalOverrides() + self::getDefaults();
1325
1326 // We only include used options with non-canonical values in the key
1327 // so adding a new option doesn't invalidate the entire parser cache.
1328 // The drawback to this is that changing the default value of an option
1329 // requires manual invalidation of existing cache entries, as mentioned
1330 // in the docs on the relevant methods and hooks.
1331 $values = [];
1332 foreach ( array_intersect( $inCacheKey, $forOptions ) as $option ) {
1333 $v = $this->optionToString( $options[$option] );
1334 $d = $this->optionToString( $defaults[$option] );
1335 if ( $v !== $d ) {
1336 $values[] = "$option=$v";
1337 }
1338 }
1339
1340 $confstr = $values ? implode( '!', $values ) : 'canonical';
1341
1342 // add in language specific options, if any
1343 // @todo FIXME: This is just a way of retrieving the url/user preferred variant
1344 if ( !is_null( $title ) ) {
1345 $confstr .= $title->getPageLanguage()->getExtraHashOptions();
1346 } else {
1347 $confstr .=
1348 MediaWikiServices::getInstance()->getContentLanguage()->getExtraHashOptions();
1349 }
1350
1351 $confstr .= $wgRenderHashAppend;
1352
1353 if ( $this->mExtraKey != '' ) {
1354 $confstr .= $this->mExtraKey;
1355 }
1356
1357 // Give a chance for extensions to modify the hash, if they have
1358 // extra options or other effects on the parser cache.
1359 Hooks::run( 'PageRenderingHash', [ &$confstr, $this->getUser(), &$forOptions ] );
1360
1361 // Make it a valid memcached key fragment
1362 $confstr = str_replace( ' ', '_', $confstr );
1363
1364 return $confstr;
1365 }
1366
1367 /**
1368 * Test whether these options are safe to cache
1369 * @since 1.30
1370 * @return bool
1371 */
1372 public function isSafeToCache() {
1373 $defaults = self::getCanonicalOverrides() + self::getDefaults();
1374 foreach ( $this->options as $option => $value ) {
1375 if ( empty( self::$inCacheKey[$option] ) ) {
1376 $v = $this->optionToString( $value );
1377 $d = $this->optionToString( $defaults[$option] );
1378 if ( $v !== $d ) {
1379 return false;
1380 }
1381 }
1382 }
1383 return true;
1384 }
1385
1386 /**
1387 * Sets a hook to force that a page exists, and sets a current revision callback to return
1388 * a revision with custom content when the current revision of the page is requested.
1389 *
1390 * @since 1.25
1391 * @param Title $title
1392 * @param Content $content
1393 * @param User $user The user that the fake revision is attributed to
1394 * @return ScopedCallback to unset the hook
1395 */
1396 public function setupFakeRevision( $title, $content, $user ) {
1397 $oldCallback = $this->setCurrentRevisionCallback(
1398 function (
1399 $titleToCheck, $parser = false ) use ( $title, $content, $user, &$oldCallback
1400 ) {
1401 if ( $titleToCheck->equals( $title ) ) {
1402 return new Revision( [
1403 'page' => $title->getArticleID(),
1404 'user_text' => $user->getName(),
1405 'user' => $user->getId(),
1406 'parent_id' => $title->getLatestRevID(),
1407 'title' => $title,
1408 'content' => $content
1409 ] );
1410 } else {
1411 return call_user_func( $oldCallback, $titleToCheck, $parser );
1412 }
1413 }
1414 );
1415
1416 global $wgHooks;
1417 $wgHooks['TitleExists'][] =
1418 function ( $titleToCheck, &$exists ) use ( $title ) {
1419 if ( $titleToCheck->equals( $title ) ) {
1420 $exists = true;
1421 }
1422 };
1423 end( $wgHooks['TitleExists'] );
1424 $key = key( $wgHooks['TitleExists'] );
1425 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1426 $linkCache->clearBadLink( $title->getPrefixedDBkey() );
1427 return new ScopedCallback( function () use ( $title, $key, $linkCache ) {
1428 global $wgHooks;
1429 unset( $wgHooks['TitleExists'][$key] );
1430 $linkCache->clearLink( $title );
1431 } );
1432 }
1433 }
1434
1435 /**
1436 * For really cool vim folding this needs to be at the end:
1437 * vim: foldmarker=@{,@} foldmethod=marker
1438 */