3 * Options for the PHP parser
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.
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.
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
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * @brief Set options of the Parser
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.
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()
45 * Flag indicating that newCanonical() accepts an IContextSource or the string 'canonical', for
46 * back-compat checks from extensions.
49 const HAS_NEWCANONICAL_FROM_CONTEXT
= 1;
52 * Default values for all options that are relevant for caching.
53 * @see self::getDefaults()
56 private static $defaults = null;
62 private static $lazyOptions = [
63 'dateformat' => [ __CLASS__
, 'initDateFormat' ],
64 'speculativeRevId' => [ __CLASS__
, 'initSpeculativeRevId' ],
68 * Specify options that are included in the cache key
71 private static $inCacheKey = [
73 'numberheadings' => true,
75 'stubthreshold' => true,
81 * Current values for all options that are relevant for caching.
87 * Timestamp used for {{CURRENTDAY}} etc.
89 * @note Caching based on parse time is handled externally
96 * @todo Track this for caching somehow without fragmenting the cache insanely
101 * Function to be called when an option is accessed.
103 * @note Used for collecting used options, does not affect caching
105 private $onAccessCallback = null;
108 * If the page being parsed is a redirect, this should hold the redirect
111 * @todo Track this for caching somehow
113 private $redirectTarget = null;
116 * Appended to the options hash
118 private $mExtraKey = '';
121 * @name Option accessors
126 * Fetch an option and track that is was accessed
128 * @param string $name Option name
131 public function getOption( $name ) {
132 if ( !array_key_exists( $name, $this->options
) ) {
133 throw new InvalidArgumentException( "Unknown parser option $name" );
136 $this->lazyLoadOption( $name );
137 if ( !empty( self
::$inCacheKey[$name] ) ) {
138 $this->optionUsed( $name );
140 return $this->options
[$name];
144 * @param string $name Lazy load option without tracking usage
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 );
153 * Set an option, generically
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
160 public function setOption( $name, $value ) {
161 if ( !array_key_exists( $name, $this->options
) ) {
162 throw new InvalidArgumentException( "Unknown parser option $name" );
164 $old = $this->options
[$name];
165 $this->options
[$name] = $value;
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
177 protected function setOptionLegacy( $name, $value ) {
178 if ( !array_key_exists( $name, $this->options
) ) {
179 throw new InvalidArgumentException( "Unknown parser option $name" );
181 return wfSetVar( $this->options
[$name], $value );
185 * Whether to extract interlanguage links
187 * When true, interlanguage links will be returned by
188 * ParserOutput::getLanguageLinks() instead of generating link HTML.
192 public function getInterwikiMagic() {
193 return $this->getOption( 'interwikiMagic' );
197 * Specify whether to extract interlanguage links
198 * @param bool|null $x New value (null is no change)
199 * @return bool Old value
201 public function setInterwikiMagic( $x ) {
202 return $this->setOptionLegacy( 'interwikiMagic', $x );
206 * Allow all external images inline?
209 public function getAllowExternalImages() {
210 return $this->getOption( 'allowExternalImages' );
214 * Allow all external images inline?
215 * @param bool|null $x New value (null is no change)
216 * @return bool Old value
218 public function setAllowExternalImages( $x ) {
219 return $this->setOptionLegacy( 'allowExternalImages', $x );
223 * External images to allow
225 * When self::getAllowExternalImages() is false
227 * @return string|string[] URLs to allow
229 public function getAllowExternalImagesFrom() {
230 return $this->getOption( 'allowExternalImagesFrom' );
234 * External images to allow
236 * When self::getAllowExternalImages() is false
238 * @param string|string[]|null $x New value (null is no change)
239 * @return string|string[] Old value
241 public function setAllowExternalImagesFrom( $x ) {
242 return $this->setOptionLegacy( 'allowExternalImagesFrom', $x );
246 * Use the on-wiki external image whitelist?
249 public function getEnableImageWhitelist() {
250 return $this->getOption( 'enableImageWhitelist' );
254 * Use the on-wiki external image whitelist?
255 * @param bool|null $x New value (null is no change)
256 * @return bool Old value
258 public function setEnableImageWhitelist( $x ) {
259 return $this->setOptionLegacy( 'enableImageWhitelist', $x );
263 * Automatically number headings?
266 public function getNumberHeadings() {
267 return $this->getOption( 'numberheadings' );
271 * Automatically number headings?
272 * @param bool|null $x New value (null is no change)
273 * @return bool Old value
275 public function setNumberHeadings( $x ) {
276 return $this->setOptionLegacy( 'numberheadings', $x );
280 * Allow inclusion of special pages?
283 public function getAllowSpecialInclusion() {
284 return $this->getOption( 'allowSpecialInclusion' );
288 * Allow inclusion of special pages?
289 * @param bool|null $x New value (null is no change)
290 * @return bool Old value
292 public function setAllowSpecialInclusion( $x ) {
293 return $this->setOptionLegacy( 'allowSpecialInclusion', $x );
297 * Use tidy to cleanup output HTML?
300 public function getTidy() {
301 return $this->getOption( 'tidy' );
305 * Use tidy to cleanup output HTML?
306 * @param bool|null $x New value (null is no change)
307 * @return bool Old value
309 public function setTidy( $x ) {
310 return $this->setOptionLegacy( 'tidy', $x );
314 * Parsing an interface message?
317 public function getInterfaceMessage() {
318 return $this->getOption( 'interfaceMessage' );
322 * Parsing an interface message?
323 * @param bool|null $x New value (null is no change)
324 * @return bool Old value
326 public function setInterfaceMessage( $x ) {
327 return $this->setOptionLegacy( 'interfaceMessage', $x );
331 * Target language for the parse
332 * @return Language|null
334 public function getTargetLanguage() {
335 return $this->getOption( 'targetLanguage' );
339 * Target language for the parse
340 * @param Language|null $x New value
341 * @return Language|null Old value
343 public function setTargetLanguage( $x ) {
344 return $this->setOption( 'targetLanguage', $x );
348 * Maximum size of template expansions, in bytes
351 public function getMaxIncludeSize() {
352 return $this->getOption( 'maxIncludeSize' );
356 * Maximum size of template expansions, in bytes
357 * @param int|null $x New value (null is no change)
358 * @return int Old value
360 public function setMaxIncludeSize( $x ) {
361 return $this->setOptionLegacy( 'maxIncludeSize', $x );
365 * Maximum number of nodes touched by PPFrame::expand()
368 public function getMaxPPNodeCount() {
369 return $this->getOption( 'maxPPNodeCount' );
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
377 public function setMaxPPNodeCount( $x ) {
378 return $this->setOptionLegacy( 'maxPPNodeCount', $x );
382 * Maximum number of nodes generated by Preprocessor::preprocessToObj()
385 public function getMaxGeneratedPPNodeCount() {
386 return $this->getOption( 'maxGeneratedPPNodeCount' );
390 * Maximum number of nodes generated by Preprocessor::preprocessToObj()
391 * @param int|null $x New value (null is no change)
394 public function setMaxGeneratedPPNodeCount( $x ) {
395 return $this->setOptionLegacy( 'maxGeneratedPPNodeCount', $x );
399 * Maximum recursion depth in PPFrame::expand()
402 public function getMaxPPExpandDepth() {
403 return $this->getOption( 'maxPPExpandDepth' );
407 * Maximum recursion depth for templates within templates
410 public function getMaxTemplateDepth() {
411 return $this->getOption( 'maxTemplateDepth' );
415 * Maximum recursion depth for templates within templates
416 * @param int|null $x New value (null is no change)
417 * @return int Old value
419 public function setMaxTemplateDepth( $x ) {
420 return $this->setOptionLegacy( 'maxTemplateDepth', $x );
424 * Maximum number of calls per parse to expensive parser functions
428 public function getExpensiveParserFunctionLimit() {
429 return $this->getOption( 'expensiveParserFunctionLimit' );
433 * Maximum number of calls per parse to expensive parser functions
435 * @param int|null $x New value (null is no change)
436 * @return int Old value
438 public function setExpensiveParserFunctionLimit( $x ) {
439 return $this->setOptionLegacy( 'expensiveParserFunctionLimit', $x );
443 * Remove HTML comments
444 * @warning Only applies to preprocess operations
447 public function getRemoveComments() {
448 return $this->getOption( 'removeComments' );
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
457 public function setRemoveComments( $x ) {
458 return $this->setOptionLegacy( 'removeComments', $x );
462 * Enable limit report in an HTML comment on output
465 public function getEnableLimitReport() {
466 return $this->getOption( 'enableLimitReport' );
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
474 public function enableLimitReport( $x = true ) {
475 return $this->setOptionLegacy( 'enableLimitReport', $x );
479 * Clean up signature texts?
480 * @see Parser::cleanSig
483 public function getCleanSignatures() {
484 return $this->getOption( 'cleanSignatures' );
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
493 public function setCleanSignatures( $x ) {
494 return $this->setOptionLegacy( 'cleanSignatures', $x );
498 * Target attribute for external links
501 public function getExternalLinkTarget() {
502 return $this->getOption( 'externalLinkTarget' );
506 * Target attribute for external links
507 * @param string|null $x New value (null is no change)
508 * @return string Old value
510 public function setExternalLinkTarget( $x ) {
511 return $this->setOptionLegacy( 'externalLinkTarget', $x );
515 * Whether content conversion should be disabled
518 public function getDisableContentConversion() {
519 return $this->getOption( 'disableContentConversion' );
523 * Whether content conversion should be disabled
524 * @param bool|null $x New value (null is no change)
525 * @return bool Old value
527 public function disableContentConversion( $x = true ) {
528 return $this->setOptionLegacy( 'disableContentConversion', $x );
532 * Whether title conversion should be disabled
535 public function getDisableTitleConversion() {
536 return $this->getOption( 'disableTitleConversion' );
540 * Whether title conversion should be disabled
541 * @param bool|null $x New value (null is no change)
542 * @return bool Old value
544 public function disableTitleConversion( $x = true ) {
545 return $this->setOptionLegacy( 'disableTitleConversion', $x );
549 * Thumb size preferred by the user.
552 public function getThumbSize() {
553 return $this->getOption( 'thumbsize' );
557 * Thumb size preferred by the user.
558 * @param int|null $x New value (null is no change)
559 * @return int Old value
561 public function setThumbSize( $x ) {
562 return $this->setOptionLegacy( 'thumbsize', $x );
566 * Thumb size preferred by the user.
569 public function getStubThreshold() {
570 return $this->getOption( 'stubthreshold' );
574 * Thumb size preferred by the user.
575 * @param int|null $x New value (null is no change)
576 * @return int Old value
578 public function setStubThreshold( $x ) {
579 return $this->setOptionLegacy( 'stubthreshold', $x );
583 * Parsing the page for a "preview" operation?
586 public function getIsPreview() {
587 return $this->getOption( 'isPreview' );
591 * Parsing the page for a "preview" operation?
592 * @param bool|null $x New value (null is no change)
593 * @return bool Old value
595 public function setIsPreview( $x ) {
596 return $this->setOptionLegacy( 'isPreview', $x );
600 * Parsing the page for a "preview" operation on a single section?
603 public function getIsSectionPreview() {
604 return $this->getOption( 'isSectionPreview' );
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
612 public function setIsSectionPreview( $x ) {
613 return $this->setOptionLegacy( 'isSectionPreview', $x );
617 * Parsing the printable version of the page?
620 public function getIsPrintable() {
621 return $this->getOption( 'printable' );
625 * Parsing the printable version of the page?
626 * @param bool|null $x New value (null is no change)
627 * @return bool Old value
629 public function setIsPrintable( $x ) {
630 return $this->setOptionLegacy( 'printable', $x );
634 * Transform wiki markup when saving the page?
637 public function getPreSaveTransform() {
638 return $this->getOption( 'preSaveTransform' );
642 * Transform wiki markup when saving the page?
643 * @param bool|null $x New value (null is no change)
644 * @return bool Old value
646 public function setPreSaveTransform( $x ) {
647 return $this->setOptionLegacy( 'preSaveTransform', $x );
654 public function getDateFormat() {
655 return $this->getOption( 'dateformat' );
659 * Lazy initializer for dateFormat
660 * @param ParserOptions $popt
663 private static function initDateFormat( ParserOptions
$popt ) {
664 return $popt->mUser
->getDatePreference();
669 * @param string|null $x New value (null is no change)
670 * @return string Old value
672 public function setDateFormat( $x ) {
673 return $this->setOptionLegacy( 'dateformat', $x );
677 * Get the user language used by the parser for this page and split the parser cache.
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!
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.
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).
693 public function getUserLangObj() {
694 return $this->getOption( 'userlang' );
698 * Same as getUserLangObj() but returns a string instead.
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!
704 * @see getUserLangObj()
706 * @return string Language code
709 public function getUserLang() {
710 return $this->getUserLangObj()->getCode();
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
718 public function setUserLang( $x ) {
719 if ( is_string( $x ) ) {
720 $x = Language
::factory( $x );
723 return $this->setOptionLegacy( 'userlang', $x );
727 * Are magic ISBN links enabled?
731 public function getMagicISBNLinks() {
732 return $this->getOption( 'magicISBNLinks' );
736 * Are magic PMID links enabled?
740 public function getMagicPMIDLinks() {
741 return $this->getOption( 'magicPMIDLinks' );
745 * Are magic RFC links enabled?
749 public function getMagicRFCLinks() {
750 return $this->getOption( 'magicRFCLinks' );
754 * If the wiki is configured to allow raw html ($wgRawHtml = true)
755 * is it allowed in the specific case of parsing this page.
757 * This is meant to disable unsafe parser tags in cases where
758 * a malicious user may control the input to the parser.
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.
767 public function getAllowUnsafeRawHtml() {
768 return $this->getOption( 'allowUnsafeRawHtml' );
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()
776 * @param bool|null $x Value to set or null to get current value
777 * @return bool Current value for allowUnsafeRawHtml
779 public function setAllowUnsafeRawHtml( $x ) {
780 return $this->setOptionLegacy( 'allowUnsafeRawHtml', $x );
784 * Class to use to wrap output from Parser::parse()
786 * @return string|bool
788 public function getWrapOutputClass() {
789 return $this->getOption( 'wrapclass' );
793 * CSS class to use to wrap output from Parser::parse()
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
799 public function setWrapOutputClass( $className ) {
800 if ( $className === true ) { // DWIM, they probably want the default class name
801 $className = 'mw-parser-output';
803 if ( $className === false ) {
804 wfDeprecated( __METHOD__
. '( false )', '1.31' );
806 return $this->setOption( 'wrapclass', $className );
810 * Callback for current revision fetching; first argument to call_user_func().
814 public function getCurrentRevisionCallback() {
815 return $this->getOption( 'currentRevisionCallback' );
819 * Callback for current revision fetching; first argument to call_user_func().
821 * @param callable|null $x New value (null is no change)
822 * @return callable Old value
824 public function setCurrentRevisionCallback( $x ) {
825 return $this->setOptionLegacy( 'currentRevisionCallback', $x );
829 * Callback for template fetching; first argument to call_user_func().
832 public function getTemplateCallback() {
833 return $this->getOption( 'templateCallback' );
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
841 public function setTemplateCallback( $x ) {
842 return $this->setOptionLegacy( 'templateCallback', $x );
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.
850 * If no callback was defined via setSpeculativeRevIdCallback(), this method will return false.
855 public function getSpeculativeRevId() {
856 return $this->getOption( 'speculativeRevId' );
860 * Callback registered with ParserOptions::$lazyOptions, triggered by getSpeculativeRevId().
862 * @param ParserOptions $popt
865 private static function initSpeculativeRevId( ParserOptions
$popt ) {
866 $cb = $popt->getOption( 'speculativeRevIdCallback' );
867 $id = $cb ?
$cb() : null;
869 // returning null would result in this being re-called every access
874 * Callback to generate a guess for {{REVISIONID}}
876 * @deprecated since 1.32, use getSpeculativeRevId() instead!
877 * @return callable|null
879 public function getSpeculativeRevIdCallback() {
880 return $this->getOption( 'speculativeRevIdCallback' );
884 * Callback to generate a guess for {{REVISIONID}}
886 * @param callable|null $x New value (null is no change)
887 * @return callable|null Old value
889 public function setSpeculativeRevIdCallback( $x ) {
890 $this->setOption( 'speculativeRevId', null ); // reset
891 return $this->setOptionLegacy( 'speculativeRevIdCallback', $x );
897 * Timestamp used for {{CURRENTDAY}} etc.
898 * @return string TS_MW timestamp
900 public function getTimestamp() {
901 if ( !isset( $this->mTimestamp
) ) {
902 $this->mTimestamp
= wfTimestampNow();
904 return $this->mTimestamp
;
908 * Timestamp used for {{CURRENTDAY}} etc.
909 * @param string|null $x New value (null is no change)
910 * @return string Old value
912 public function setTimestamp( $x ) {
913 return wfSetVar( $this->mTimestamp
, $x );
917 * Set the redirect target.
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
924 * @param Title|null $title
926 function setRedirectTarget( $title ) {
927 $this->redirectTarget
= $title;
931 * Get the previously-set redirect target.
936 function getRedirectTarget() {
937 return $this->redirectTarget
;
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.
946 public function addExtraKey( $key ) {
947 $this->mExtraKey
.= '!' . $key;
954 public function getUser() {
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
964 public function __construct( $user = null, $lang = null ) {
965 if ( $user === null ) {
967 if ( $wgUser === null ) {
973 if ( $lang === null ) {
975 if ( !StubObject
::isRealObject( $wgLang ) ) {
980 $this->initialiseFromUser( $user, $lang );
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.
988 * @return ParserOptions
990 public static function newFromAnon() {
991 return new ParserOptions( new User
,
992 MediaWikiServices
::getInstance()->getContentLanguage() );
996 * Get a ParserOptions object from a given user.
997 * Language will be taken from $wgLang.
999 * @warning For interaction with the parser cache, use
1000 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
1002 * @return ParserOptions
1004 public static function newFromUser( $user ) {
1005 return new ParserOptions( $user );
1009 * Get a ParserOptions object from a given user and language
1011 * @warning For interaction with the parser cache, use
1012 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
1014 * @param Language $lang
1015 * @return ParserOptions
1017 public static function newFromUserAndLang( User
$user, Language
$lang ) {
1018 return new ParserOptions( $user, $lang );
1022 * Get a ParserOptions object from a IContextSource object
1024 * @warning For interaction with the parser cache, use
1025 * WikiPage::makeParserOptions() or ParserOptions::newCanonical() instead.
1026 * @param IContextSource $context
1027 * @return ParserOptions
1029 public static function newFromContext( IContextSource
$context ) {
1030 return new ParserOptions( $context->getUser(), $context->getLanguage() );
1034 * Creates a "canonical" ParserOptions object
1036 * For historical reasons, certain options have default values that are
1037 * different from the canonical values used for caching.
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
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 );
1058 throw new InvalidArgumentException(
1059 '$context must be an IContextSource, the string "canonical", a User, or null'
1063 foreach ( self
::getCanonicalOverrides() as $k => $v ) {
1064 $ret->setOption( $k, $v );
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.
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;
1086 if ( self
::$defaults === null ) {
1087 // *UPDATE* ParserOptions::matches() if any of this changes as needed
1089 'dateformat' => null,
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,
1107 Hooks
::run( 'ParserOptionsRegister', [
1110 &self
::$lazyOptions,
1113 ksort( self
::$inCacheKey );
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(),
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.
1152 private static function getCanonicalOverrides() {
1153 global $wgEnableParserLimitReporting;
1156 'enableLimitReport' => $wgEnableParserLimitReporting,
1164 * @param Language $lang
1166 private function initialiseFromUser( $user, $lang ) {
1167 $this->options
= self
::getDefaults();
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;
1177 * Check if these options match that of another options set
1179 * This ignores report limit settings that only affect HTML comments
1181 * @param ParserOptions $other
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
1191 foreach ( $options as $option ) {
1192 // Resolve any lazy options
1193 $this->lazyLoadOption( $option );
1194 $other->lazyLoadOption( $option );
1196 $o1 = $this->optionToString( $this->options
[$option] );
1197 $o2 = $this->optionToString( $other->options
[$option] );
1198 if ( $o1 !== $o2 ) {
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
1212 foreach ( $fields as $field ) {
1213 if ( !is_object( $this->$field ) && $this->$field !== $other->$field ) {
1222 * @param ParserOptions $other
1223 * @return bool Whether the cache key relevant options match those of $other
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 );
1232 $o1 = $this->optionToString( $this->options
[$option] );
1233 $o2 = $this->optionToString( $other->options
[$option] );
1234 if ( $o1 !== $o2 ) {
1243 * Registers a callback for tracking which ParserOptions which are used.
1244 * This is a private API with the parser.
1245 * @param callable $callback
1247 public function registerWatcher( $callback ) {
1248 $this->onAccessCallback
= $callback;
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().
1257 * @param string $optionName Name of the option
1259 public function optionUsed( $optionName ) {
1260 if ( $this->onAccessCallback
) {
1261 call_user_func( $this->onAccessCallback
, $optionName );
1266 * Return all option keys that vary the options hash
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();
1276 return array_keys( array_filter( self
::$inCacheKey ) );
1280 * Convert an option to a string value
1281 * @param mixed $value
1284 private function optionToString( $value ) {
1285 if ( $value === true ) {
1287 } elseif ( $value === false ) {
1289 } elseif ( $value === null ) {
1291 } elseif ( $value instanceof Language
) {
1292 return $value->getCode();
1293 } elseif ( is_array( $value ) ) {
1294 return '[' . implode( ',', array_map( [ $this, 'optionToString' ], $value ) ) . ']';
1296 return (string)$value;
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.
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
1312 public function optionsHash( $forOptions, $title = null ) {
1313 global $wgRenderHashAppend;
1315 $inCacheKey = self
::allCacheVaryingOptions();
1317 // Resolve any lazy options
1318 $lazyOpts = array_intersect( $forOptions, $inCacheKey, array_keys( self
::$lazyOptions ) );
1319 foreach ( $lazyOpts as $k ) {
1320 $this->lazyLoadOption( $k );
1323 $options = $this->options
;
1324 $defaults = self
::getCanonicalOverrides() + self
::getDefaults();
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.
1332 foreach ( array_intersect( $inCacheKey, $forOptions ) as $option ) {
1333 $v = $this->optionToString( $options[$option] );
1334 $d = $this->optionToString( $defaults[$option] );
1336 $values[] = "$option=$v";
1340 $confstr = $values ?
implode( '!', $values ) : 'canonical';
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();
1348 MediaWikiServices
::getInstance()->getContentLanguage()->getExtraHashOptions();
1351 $confstr .= $wgRenderHashAppend;
1353 if ( $this->mExtraKey
!= '' ) {
1354 $confstr .= $this->mExtraKey
;
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 ] );
1361 // Make it a valid memcached key fragment
1362 $confstr = str_replace( ' ', '_', $confstr );
1368 * Test whether these options are safe to cache
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] );
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.
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
1396 public function setupFakeRevision( $title, $content, $user ) {
1397 $oldCallback = $this->setCurrentRevisionCallback(
1399 $titleToCheck, $parser = false ) use ( $title, $content, $user, &$oldCallback
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(),
1408 'content' => $content
1411 return call_user_func( $oldCallback, $titleToCheck, $parser );
1417 $wgHooks['TitleExists'][] =
1418 function ( $titleToCheck, &$exists ) use ( $title ) {
1419 if ( $titleToCheck->equals( $title ) ) {
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 ) {
1429 unset( $wgHooks['TitleExists'][$key] );
1430 $linkCache->clearLink( $title );
1436 * For really cool vim folding this needs to be at the end:
1437 * vim: foldmarker=@{,@} foldmethod=marker