3 * Cache of the contents of localisation files.
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
23 use CLDRPluralRuleParser\Evaluator
;
24 use CLDRPluralRuleParser\Error
as CLDRPluralRuleError
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
29 * Class for caching the contents of localisation files, Messages*.php
32 * An instance of this class is available using Language::getLocalisationCache().
34 * The values retrieved from here are merged, containing items from extension
35 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
36 * zh-hans -> en ). Some common errors are corrected, for example namespace
37 * names with spaces instead of underscores, but heavyweight processing, such
38 * as grammatical transformation, is done by the caller.
40 class LocalisationCache
{
43 /** Configuration associative array */
47 * True if recaching should only be done on an explicit call to recache().
48 * Setting this reduces the overhead of cache freshness checking, which
49 * requires doing a stat() for every extension i18n file.
51 private $manualRecache = false;
54 * True to treat all files as expired until they are regenerated by this object.
56 private $forceRecache = false;
59 * The cache data. 3-d array, where the first key is the language code,
60 * the second key is the item key e.g. 'messages', and the third key is
61 * an item specific subkey index. Some items are not arrays and so for those
62 * items, there are no subkeys.
67 * The persistent store object. An instance of LCStore.
74 * @var \Psr\Log\LoggerInterface
79 * A 2-d associative array, code/key, where presence indicates that the item
80 * is loaded. Value arbitrary.
82 * For split items, if set, this indicates that all of the subitems have been
85 private $loadedItems = [];
88 * A 3-d associative array, code/key/subkey, where presence indicates that
89 * the subitem is loaded. Only used for the split items, i.e. messages.
91 private $loadedSubitems = [];
94 * An array where presence of a key indicates that that language has been
95 * initialised. Initialisation includes checking for cache expiry and doing
96 * any necessary updates.
98 private $initialisedLangs = [];
101 * An array mapping non-existent pseudo-languages to fallback languages. This
102 * is filled by initShallowFallback() when data is requested from a language
103 * that lacks a Messages*.php file.
105 private $shallowFallbacks = [];
108 * An array where the keys are codes that have been recached by this instance.
110 private $recachedLangs = [];
115 public static $allKeys = [
116 'fallback', 'namespaceNames', 'bookstoreList',
117 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns',
118 'digitTransformTable', 'separatorTransformTable',
119 'minimumGroupingDigits', 'fallback8bitEncoding',
120 'linkPrefixExtension', 'linkTrail', 'linkPrefixCharset',
121 'namespaceAliases', 'dateFormats', 'datePreferences',
122 'datePreferenceMigrationMap', 'defaultDateFormat',
123 'specialPageAliases', 'imageFiles', 'preloadedMessages',
124 'namespaceGenderAliases', 'digitGroupingPattern', 'pluralRules',
125 'pluralRuleTypes', 'compiledPluralRules',
129 * Keys for items which consist of associative arrays, which may be merged
130 * by a fallback sequence.
132 public static $mergeableMapKeys = [ 'messages', 'namespaceNames',
133 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
137 * Keys for items which are a numbered array.
139 public static $mergeableListKeys = [];
142 * Keys for items which contain an array of arrays of equivalent aliases
143 * for each subitem. The aliases may be merged by a fallback sequence.
145 public static $mergeableAliasListKeys = [ 'specialPageAliases' ];
148 * Keys for items which contain an associative array, and may be merged if
149 * the primary value contains the special array key "inherit". That array
150 * key is removed after the first merge.
152 public static $optionalMergeKeys = [ 'bookstoreList' ];
155 * Keys for items that are formatted like $magicWords
157 public static $magicWordKeys = [ 'magicWords' ];
160 * Keys for items where the subitems are stored in the backend separately.
162 public static $splitKeys = [ 'messages' ];
165 * Keys which are loaded automatically by initLanguage()
167 public static $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
170 * Associative array of cached plural rules. The key is the language code,
171 * the value is an array of plural rules for that language.
173 private $pluralRules = null;
176 * Associative array of cached plural rule types. The key is the language
177 * code, the value is an array of plural rule types for that language. For
178 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
179 * The index for each rule type matches the index for the rule in
180 * $pluralRules, thus allowing correlation between the two. The reason we
181 * don't just use the type names as the keys in $pluralRules is because
182 * Language::convertPlural applies the rules based on numeric order (or
183 * explicit numeric parameter), not based on the name of the rule type. For
184 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
185 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
187 private $pluralRuleTypes = null;
189 private $mergeableKeys = null;
192 * For constructor parameters, see the documentation in DefaultSettings.php
193 * for $wgLocalisationCacheConf.
196 * @throws MWException
198 function __construct( $conf ) {
199 global $wgCacheDirectory;
202 $this->logger
= LoggerFactory
::getInstance( 'localisation' );
204 $directory = !empty( $conf['storeDirectory'] ) ?
$conf['storeDirectory'] : $wgCacheDirectory;
206 $storeArg['directory'] = $directory;
208 if ( !empty( $conf['storeClass'] ) ) {
209 $storeClass = $conf['storeClass'];
211 switch ( $conf['store'] ) {
214 $storeClass = LCStoreCDB
::class;
217 $storeClass = LCStoreDB
::class;
218 $storeArg['server'] = $conf['storeServer'] ??
[];
221 $storeClass = LCStoreStaticArray
::class;
225 $storeClass = LCStoreCDB
::class;
227 $storeClass = LCStoreDB
::class;
228 $storeArg['server'] = $conf['storeServer'] ??
[];
232 throw new MWException(
233 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
237 $this->logger
->debug( static::class . ": using store $storeClass" );
239 $this->store
= new $storeClass( $storeArg );
240 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
241 if ( isset( $conf[$var] ) ) {
242 $this->$var = $conf[$var];
248 * Returns true if the given key is mergeable, that is, if it is an associative
249 * array which can be merged through a fallback sequence.
253 public function isMergeableKey( $key ) {
254 if ( $this->mergeableKeys
=== null ) {
255 $this->mergeableKeys
= array_flip( array_merge(
256 self
::$mergeableMapKeys,
257 self
::$mergeableListKeys,
258 self
::$mergeableAliasListKeys,
259 self
::$optionalMergeKeys,
264 return isset( $this->mergeableKeys
[$key] );
270 * Warning: this may be slow for split items (messages), since it will
271 * need to fetch all of the subitems from the cache individually.
272 * @param string $code
276 public function getItem( $code, $key ) {
277 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
278 $this->loadItem( $code, $key );
281 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
282 return $this->shallowFallbacks
[$code];
285 return $this->data
[$code][$key];
289 * Get a subitem, for instance a single message for a given language.
290 * @param string $code
292 * @param string $subkey
295 public function getSubitem( $code, $key, $subkey ) {
296 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
297 !isset( $this->loadedItems
[$code][$key] )
299 $this->loadSubitem( $code, $key, $subkey );
302 return $this->data
[$code][$key][$subkey] ??
null;
306 * Get the list of subitem keys for a given item.
308 * This is faster than array_keys($lc->getItem(...)) for the items listed in
311 * Will return null if the item is not found, or false if the item is not an
313 * @param string $code
315 * @return bool|null|string|string[]
317 public function getSubitemList( $code, $key ) {
318 if ( in_array( $key, self
::$splitKeys ) ) {
319 return $this->getSubitem( $code, 'list', $key );
321 $item = $this->getItem( $code, $key );
322 if ( is_array( $item ) ) {
323 return array_keys( $item );
331 * Load an item into the cache.
332 * @param string $code
335 protected function loadItem( $code, $key ) {
336 if ( !isset( $this->initialisedLangs
[$code] ) ) {
337 $this->initLanguage( $code );
340 // Check to see if initLanguage() loaded it for us
341 if ( isset( $this->loadedItems
[$code][$key] ) ) {
345 if ( isset( $this->shallowFallbacks
[$code] ) ) {
346 $this->loadItem( $this->shallowFallbacks
[$code], $key );
351 if ( in_array( $key, self
::$splitKeys ) ) {
352 $subkeyList = $this->getSubitem( $code, 'list', $key );
353 foreach ( $subkeyList as $subkey ) {
354 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
357 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
360 $this->data
[$code][$key] = $this->store
->get( $code, $key );
363 $this->loadedItems
[$code][$key] = true;
367 * Load a subitem into the cache
368 * @param string $code
370 * @param string $subkey
372 protected function loadSubitem( $code, $key, $subkey ) {
373 if ( !in_array( $key, self
::$splitKeys ) ) {
374 $this->loadItem( $code, $key );
379 if ( !isset( $this->initialisedLangs
[$code] ) ) {
380 $this->initLanguage( $code );
383 // Check to see if initLanguage() loaded it for us
384 if ( isset( $this->loadedItems
[$code][$key] ) ||
385 isset( $this->loadedSubitems
[$code][$key][$subkey] )
390 if ( isset( $this->shallowFallbacks
[$code] ) ) {
391 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
396 $value = $this->store
->get( $code, "$key:$subkey" );
397 $this->data
[$code][$key][$subkey] = $value;
398 $this->loadedSubitems
[$code][$key][$subkey] = true;
402 * Returns true if the cache identified by $code is missing or expired.
404 * @param string $code
408 public function isExpired( $code ) {
409 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
410 $this->logger
->debug( __METHOD__
. "($code): forced reload" );
415 $deps = $this->store
->get( $code, 'deps' );
416 $keys = $this->store
->get( $code, 'list' );
417 $preload = $this->store
->get( $code, 'preload' );
418 // Different keys may expire separately for some stores
419 if ( $deps === null ||
$keys === null ||
$preload === null ) {
420 $this->logger
->debug( __METHOD__
. "($code): cache missing, need to make one" );
425 foreach ( $deps as $dep ) {
426 // Because we're unserializing stuff from cache, we
427 // could receive objects of classes that don't exist
428 // anymore (e.g. uninstalled extensions)
429 // When this happens, always expire the cache
430 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
431 $this->logger
->debug( __METHOD__
. "($code): cache for $code expired due to " .
442 * Initialise a language in this object. Rebuild the cache if necessary.
443 * @param string $code
444 * @throws MWException
446 protected function initLanguage( $code ) {
447 if ( isset( $this->initialisedLangs
[$code] ) ) {
451 $this->initialisedLangs
[$code] = true;
453 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
454 if ( !Language
::isValidBuiltInCode( $code ) ) {
455 $this->initShallowFallback( $code, 'en' );
460 # Recache the data if necessary
461 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
462 if ( Language
::isSupportedLanguage( $code ) ) {
463 $this->recache( $code );
464 } elseif ( $code === 'en' ) {
465 throw new MWException( 'MessagesEn.php is missing.' );
467 $this->initShallowFallback( $code, 'en' );
474 $preload = $this->getItem( $code, 'preload' );
475 if ( $preload === null ) {
476 if ( $this->manualRecache
) {
477 // No Messages*.php file. Do shallow fallback to en.
478 if ( $code === 'en' ) {
479 throw new MWException( 'No localisation cache found for English. ' .
480 'Please run maintenance/rebuildLocalisationCache.php.' );
482 $this->initShallowFallback( $code, 'en' );
486 throw new MWException( 'Invalid or missing localisation cache.' );
489 $this->data
[$code] = $preload;
490 foreach ( $preload as $key => $item ) {
491 if ( in_array( $key, self
::$splitKeys ) ) {
492 foreach ( $item as $subkey => $subitem ) {
493 $this->loadedSubitems
[$code][$key][$subkey] = true;
496 $this->loadedItems
[$code][$key] = true;
502 * Create a fallback from one language to another, without creating a
503 * complete persistent cache.
504 * @param string $primaryCode
505 * @param string $fallbackCode
507 public function initShallowFallback( $primaryCode, $fallbackCode ) {
508 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
509 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
510 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
511 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
515 * Read a PHP file containing localisation data.
516 * @param string $_fileName
517 * @param string $_fileType
518 * @throws MWException
521 protected function readPHPFile( $_fileName, $_fileType ) {
525 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
526 foreach ( self
::$allKeys as $key ) {
527 // Not all keys are set in language files, so
528 // check they exist first
529 if ( isset( $
$key ) ) {
533 } elseif ( $_fileType == 'aliases' ) {
534 if ( isset( $aliases ) ) {
535 $data['aliases'] = $aliases;
538 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
545 * Read a JSON file containing localisation messages.
546 * @param string $fileName Name of file to read
547 * @throws MWException If there is a syntax error in the JSON file
548 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
550 public function readJSONFile( $fileName ) {
551 if ( !is_readable( $fileName ) ) {
555 $json = file_get_contents( $fileName );
556 if ( $json === false ) {
560 $data = FormatJson
::decode( $json, true );
561 if ( $data === null ) {
562 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
565 // Remove keys starting with '@', they're reserved for metadata and non-message data
566 foreach ( $data as $key => $unused ) {
567 if ( $key === '' ||
$key[0] === '@' ) {
568 unset( $data[$key] );
572 // The JSON format only supports messages, none of the other variables, so wrap the data
573 return [ 'messages' => $data ];
577 * Get the compiled plural rules for a given language from the XML files.
579 * @param string $code
582 public function getCompiledPluralRules( $code ) {
583 $rules = $this->getPluralRules( $code );
584 if ( $rules === null ) {
588 $compiledRules = Evaluator
::compile( $rules );
589 } catch ( CLDRPluralRuleError
$e ) {
590 $this->logger
->debug( $e->getMessage() );
595 return $compiledRules;
599 * Get the plural rules for a given language from the XML files.
602 * @param string $code
605 public function getPluralRules( $code ) {
606 if ( $this->pluralRules
=== null ) {
607 $this->loadPluralFiles();
609 return $this->pluralRules
[$code] ??
null;
613 * Get the plural rule types for a given language from the XML files.
616 * @param string $code
619 public function getPluralRuleTypes( $code ) {
620 if ( $this->pluralRuleTypes
=== null ) {
621 $this->loadPluralFiles();
623 return $this->pluralRuleTypes
[$code] ??
null;
627 * Load the plural XML files.
629 protected function loadPluralFiles() {
631 $cldrPlural = "$IP/languages/data/plurals.xml";
632 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
633 // Load CLDR plural rules
634 $this->loadPluralFile( $cldrPlural );
635 if ( file_exists( $mwPlural ) ) {
636 // Override or extend
637 $this->loadPluralFile( $mwPlural );
642 * Load a plural XML file with the given filename, compile the relevant
643 * rules, and save the compiled rules in a process-local cache.
645 * @param string $fileName
646 * @throws MWException
648 protected function loadPluralFile( $fileName ) {
649 // Use file_get_contents instead of DOMDocument::load (T58439)
650 $xml = file_get_contents( $fileName );
652 throw new MWException( "Unable to read plurals file $fileName" );
654 $doc = new DOMDocument
;
655 $doc->loadXML( $xml );
656 $rulesets = $doc->getElementsByTagName( "pluralRules" );
657 foreach ( $rulesets as $ruleset ) {
658 $codes = $ruleset->getAttribute( 'locales' );
661 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
662 foreach ( $ruleElements as $elt ) {
663 $ruleType = $elt->getAttribute( 'count' );
664 if ( $ruleType === 'other' ) {
665 // Don't record "other" rules, which have an empty condition
668 $rules[] = $elt->nodeValue
;
669 $ruleTypes[] = $ruleType;
671 foreach ( explode( ' ', $codes ) as $code ) {
672 $this->pluralRules
[$code] = $rules;
673 $this->pluralRuleTypes
[$code] = $ruleTypes;
679 * Read the data from the source files for a given language, and register
680 * the relevant dependencies in the $deps array. If the localisation
681 * exists, the data array is returned, otherwise false is returned.
683 * @param string $code
684 * @param array &$deps
687 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
690 // This reads in the PHP i18n file with non-messages l10n data
691 $fileName = Language
::getMessagesFileName( $code );
692 if ( !file_exists( $fileName ) ) {
695 $deps[] = new FileDependency( $fileName );
696 $data = $this->readPHPFile( $fileName, 'core' );
699 # Load CLDR plural rules for JavaScript
700 $data['pluralRules'] = $this->getPluralRules( $code );
702 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
703 # Load plural rule types
704 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
706 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
707 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
713 * Merge two localisation values, a primary and a fallback, overwriting the
714 * primary value in place.
716 * @param mixed &$value
717 * @param mixed $fallbackValue
719 protected function mergeItem( $key, &$value, $fallbackValue ) {
720 if ( !is_null( $value ) ) {
721 if ( !is_null( $fallbackValue ) ) {
722 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
723 $value = $value +
$fallbackValue;
724 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
725 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
726 $value = array_unique( array_merge( $fallbackValue, $value ) );
727 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
728 $value = array_merge_recursive( $value, $fallbackValue );
729 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
730 if ( !empty( $value['inherit'] ) ) {
731 $value = array_merge( $fallbackValue, $value );
734 if ( isset( $value['inherit'] ) ) {
735 unset( $value['inherit'] );
737 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
738 $this->mergeMagicWords( $value, $fallbackValue );
742 $value = $fallbackValue;
747 * @param mixed &$value
748 * @param mixed $fallbackValue
750 protected function mergeMagicWords( &$value, $fallbackValue ) {
751 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
752 if ( !isset( $value[$magicName] ) ) {
753 $value[$magicName] = $fallbackInfo;
755 $oldSynonyms = array_slice( $fallbackInfo, 1 );
756 $newSynonyms = array_slice( $value[$magicName], 1 );
757 $synonyms = array_values( array_unique( array_merge(
758 $newSynonyms, $oldSynonyms ) ) );
759 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
765 * Given an array mapping language code to localisation value, such as is
766 * found in extension *.i18n.php files, iterate through a fallback sequence
767 * to merge the given data with an existing primary value.
769 * Returns true if any data from the extension array was used, false
771 * @param array $codeSequence
773 * @param mixed &$value
774 * @param mixed $fallbackValue
777 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
779 foreach ( $codeSequence as $code ) {
780 if ( isset( $fallbackValue[$code] ) ) {
781 $this->mergeItem( $key, $value, $fallbackValue[$code] );
790 * Gets the combined list of messages dirs from
791 * core and extensions
796 public function getMessagesDirs() {
799 $config = MediaWikiServices
::getInstance()->getMainConfig();
800 $messagesDirs = $config->get( 'MessagesDirs' );
802 'core' => "$IP/languages/i18n",
803 'exif' => "$IP/languages/i18n/exif",
804 'api' => "$IP/includes/api/i18n",
805 'oojs-ui' => "$IP/resources/lib/ooui/i18n",
810 * Load localisation data for a given language for both core and extensions
811 * and save it to the persistent cache store and the process cache
812 * @param string $code
813 * @throws MWException
815 public function recache( $code ) {
816 global $wgExtensionMessagesFiles;
819 throw new MWException( "Invalid language code requested" );
821 $this->recachedLangs
[ $code ] = true;
824 $initialData = array_fill_keys( self
::$allKeys, null );
825 $coreData = $initialData;
828 # Load the primary localisation from the source file
829 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
830 $this->logger
->debug( __METHOD__
. ": got localisation for $code from source" );
832 # Merge primary localisation
833 foreach ( $data as $key => $value ) {
834 $this->mergeItem( $key, $coreData[ $key ], $value );
837 # Fill in the fallback if it's not there already
838 if ( ( is_null( $coreData['fallback'] ) ||
$coreData['fallback'] === false ) && $code === 'en' ) {
839 $coreData['fallback'] = false;
840 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
842 if ( !is_null( $coreData['fallback'] ) ) {
843 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
845 $coreData['fallbackSequence'] = [];
847 $len = count( $coreData['fallbackSequence'] );
849 # Before we add the 'en' fallback for messages, keep a copy of
850 # the original fallback sequence
851 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
853 # Ensure that the sequence ends at 'en' for messages
854 if ( !$len ||
$coreData['fallbackSequence'][$len - 1] !== 'en' ) {
855 $coreData['fallbackSequence'][] = 'en';
859 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
860 $messageDirs = $this->getMessagesDirs();
862 # Load non-JSON localisation data for extensions
863 $extensionData = array_fill_keys( $codeSequence, $initialData );
864 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
865 if ( isset( $messageDirs[$extension] ) ) {
866 # This extension has JSON message data; skip the PHP shim
870 $data = $this->readPHPFile( $fileName, 'extension' );
873 foreach ( $data as $key => $item ) {
874 foreach ( $codeSequence as $csCode ) {
875 if ( isset( $item[$csCode] ) ) {
876 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
883 $deps[] = new FileDependency( $fileName );
887 # Load the localisation data for each fallback, then merge it into the full array
888 $allData = $initialData;
889 foreach ( $codeSequence as $csCode ) {
890 $csData = $initialData;
892 # Load core messages and the extension localisations.
893 foreach ( $messageDirs as $dirs ) {
894 foreach ( (array)$dirs as $dir ) {
895 $fileName = "$dir/$csCode.json";
896 $data = $this->readJSONFile( $fileName );
898 foreach ( $data as $key => $item ) {
899 $this->mergeItem( $key, $csData[$key], $item );
902 $deps[] = new FileDependency( $fileName );
906 # Merge non-JSON extension data
907 if ( isset( $extensionData[$csCode] ) ) {
908 foreach ( $extensionData[$csCode] as $key => $item ) {
909 $this->mergeItem( $key, $csData[$key], $item );
913 if ( $csCode === $code ) {
914 # Merge core data into extension data
915 foreach ( $coreData as $key => $item ) {
916 $this->mergeItem( $key, $csData[$key], $item );
919 # Load the secondary localisation from the source file to
920 # avoid infinite cycles on cyclic fallbacks
921 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
922 # Only merge the keys that make sense to merge
923 foreach ( self
::$allKeys as $key ) {
924 if ( !isset( $fbData[ $key ] ) ) {
928 if ( is_null( $coreData[ $key ] ) ||
$this->isMergeableKey( $key ) ) {
929 $this->mergeItem( $key, $csData[ $key ], $fbData[ $key ] );
934 # Allow extensions an opportunity to adjust the data for this
936 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
938 # Merge the data for this fallback into the final array
939 if ( $csCode === $code ) {
942 foreach ( self
::$allKeys as $key ) {
943 if ( !isset( $csData[$key] ) ) {
947 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
948 $this->mergeItem( $key, $allData[$key], $csData[$key] );
954 # Add cache dependencies for any referenced globals
955 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
956 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
957 // We use the key 'wgMessagesDirs' for historical reasons.
958 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
959 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
961 # Add dependencies to the cache entry
962 $allData['deps'] = $deps;
964 # Replace spaces with underscores in namespace names
965 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
967 # And do the same for special page aliases. $page is an array.
968 foreach ( $allData['specialPageAliases'] as &$page ) {
969 $page = str_replace( ' ', '_', $page );
971 # Decouple the reference to prevent accidental damage
974 # If there were no plural rules, return an empty array
975 if ( $allData['pluralRules'] === null ) {
976 $allData['pluralRules'] = [];
978 if ( $allData['compiledPluralRules'] === null ) {
979 $allData['compiledPluralRules'] = [];
981 # If there were no plural rule types, return an empty array
982 if ( $allData['pluralRuleTypes'] === null ) {
983 $allData['pluralRuleTypes'] = [];
987 $allData['list'] = [];
988 foreach ( self
::$splitKeys as $key ) {
989 $allData['list'][$key] = array_keys( $allData[$key] );
992 $unused = true; // Used to be $purgeBlobs, removed in 1.34
993 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$unused ] );
995 if ( is_null( $allData['namespaceNames'] ) ) {
996 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
997 'Check that your languages/messages/MessagesEn.php file is intact.' );
1000 # Set the preload key
1001 $allData['preload'] = $this->buildPreload( $allData );
1003 # Save to the process cache and register the items loaded
1004 $this->data
[$code] = $allData;
1005 foreach ( $allData as $key => $item ) {
1006 $this->loadedItems
[$code][$key] = true;
1009 # Save to the persistent cache
1010 $this->store
->startWrite( $code );
1011 foreach ( $allData as $key => $value ) {
1012 if ( in_array( $key, self
::$splitKeys ) ) {
1013 foreach ( $value as $subkey => $subvalue ) {
1014 $this->store
->set( "$key:$subkey", $subvalue );
1017 $this->store
->set( $key, $value );
1020 $this->store
->finishWrite();
1022 # Clear out the MessageBlobStore
1023 # HACK: If using a null (i.e. disabled) storage backend, we
1024 # can't write to the MessageBlobStore either
1025 if ( !$this->store
instanceof LCStoreNull
) {
1026 $blobStore = MediaWikiServices
::getInstance()->getResourceLoader()->getMessageBlobStore();
1027 $blobStore->clear();
1032 * Build the preload item from the given pre-cache data.
1034 * The preload item will be loaded automatically, improving performance
1035 * for the commonly-requested items it contains.
1036 * @param array $data
1039 protected function buildPreload( $data ) {
1040 $preload = [ 'messages' => [] ];
1041 foreach ( self
::$preloadedKeys as $key ) {
1042 $preload[$key] = $data[$key];
1045 foreach ( $data['preloadedMessages'] as $subkey ) {
1046 $subitem = $data['messages'][$subkey] ??
null;
1047 $preload['messages'][$subkey] = $subitem;
1054 * Unload the data for a given language from the object cache.
1055 * Reduces memory usage.
1056 * @param string $code
1058 public function unload( $code ) {
1059 unset( $this->data
[$code] );
1060 unset( $this->loadedItems
[$code] );
1061 unset( $this->loadedSubitems
[$code] );
1062 unset( $this->initialisedLangs
[$code] );
1063 unset( $this->shallowFallbacks
[$code] );
1065 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1066 if ( $fbCode === $code ) {
1067 $this->unload( $shallowCode );
1075 public function unloadAll() {
1076 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1077 $this->unload( $lang );
1082 * Disable the storage backend
1084 public function disableBackend() {
1085 $this->store
= new LCStoreNull
;
1086 $this->manualRecache
= false;