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\MediaWikiServices
;
28 * Class for caching the contents of localisation files, Messages*.php
31 * An instance of this class is available using Language::getLocalisationCache().
33 * The values retrieved from here are merged, containing items from extension
34 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
35 * zh-hans -> en ). Some common errors are corrected, for example namespace
36 * names with spaces instead of underscores, but heavyweight processing, such
37 * as grammatical transformation, is done by the caller.
39 class LocalisationCache
{
42 /** Configuration associative array */
46 * True if recaching should only be done on an explicit call to recache().
47 * Setting this reduces the overhead of cache freshness checking, which
48 * requires doing a stat() for every extension i18n file.
50 private $manualRecache = false;
53 * True to treat all files as expired until they are regenerated by this object.
55 private $forceRecache = false;
58 * The cache data. 3-d array, where the first key is the language code,
59 * the second key is the item key e.g. 'messages', and the third key is
60 * an item specific subkey index. Some items are not arrays and so for those
61 * items, there are no subkeys.
66 * The persistent store object. An instance of LCStore.
73 * A 2-d associative array, code/key, where presence indicates that the item
74 * is loaded. Value arbitrary.
76 * For split items, if set, this indicates that all of the subitems have been
79 private $loadedItems = [];
82 * A 3-d associative array, code/key/subkey, where presence indicates that
83 * the subitem is loaded. Only used for the split items, i.e. messages.
85 private $loadedSubitems = [];
88 * An array where presence of a key indicates that that language has been
89 * initialised. Initialisation includes checking for cache expiry and doing
90 * any necessary updates.
92 private $initialisedLangs = [];
95 * An array mapping non-existent pseudo-languages to fallback languages. This
96 * is filled by initShallowFallback() when data is requested from a language
97 * that lacks a Messages*.php file.
99 private $shallowFallbacks = [];
102 * An array where the keys are codes that have been recached by this instance.
104 private $recachedLangs = [];
109 static public $allKeys = [
110 'fallback', 'namespaceNames', 'bookstoreList',
111 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
112 'separatorTransformTable', 'minimumGroupingDigits',
113 'fallback8bitEncoding', 'linkPrefixExtension',
114 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
115 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
116 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
117 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
118 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
122 * Keys for items which consist of associative arrays, which may be merged
123 * by a fallback sequence.
125 static public $mergeableMapKeys = [ 'messages', 'namespaceNames',
126 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
130 * Keys for items which are a numbered array.
132 static public $mergeableListKeys = [ 'extraUserToggles' ];
135 * Keys for items which contain an array of arrays of equivalent aliases
136 * for each subitem. The aliases may be merged by a fallback sequence.
138 static public $mergeableAliasListKeys = [ 'specialPageAliases' ];
141 * Keys for items which contain an associative array, and may be merged if
142 * the primary value contains the special array key "inherit". That array
143 * key is removed after the first merge.
145 static public $optionalMergeKeys = [ 'bookstoreList' ];
148 * Keys for items that are formatted like $magicWords
150 static public $magicWordKeys = [ 'magicWords' ];
153 * Keys for items where the subitems are stored in the backend separately.
155 static public $splitKeys = [ 'messages' ];
158 * Keys which are loaded automatically by initLanguage()
160 static public $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
163 * Associative array of cached plural rules. The key is the language code,
164 * the value is an array of plural rules for that language.
166 private $pluralRules = null;
169 * Associative array of cached plural rule types. The key is the language
170 * code, the value is an array of plural rule types for that language. For
171 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
172 * The index for each rule type matches the index for the rule in
173 * $pluralRules, thus allowing correlation between the two. The reason we
174 * don't just use the type names as the keys in $pluralRules is because
175 * Language::convertPlural applies the rules based on numeric order (or
176 * explicit numeric parameter), not based on the name of the rule type. For
177 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
178 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
180 private $pluralRuleTypes = null;
182 private $mergeableKeys = null;
185 * For constructor parameters, see the documentation in DefaultSettings.php
186 * for $wgLocalisationCacheConf.
189 * @throws MWException
191 function __construct( $conf ) {
192 global $wgCacheDirectory;
196 if ( !empty( $conf['storeClass'] ) ) {
197 $storeClass = $conf['storeClass'];
199 switch ( $conf['store'] ) {
202 $storeClass = LCStoreCDB
::class;
205 $storeClass = LCStoreDB
::class;
208 $storeClass = LCStoreStaticArray
::class;
211 if ( !empty( $conf['storeDirectory'] ) ) {
212 $storeClass = LCStoreCDB
::class;
213 } elseif ( $wgCacheDirectory ) {
214 $storeConf['directory'] = $wgCacheDirectory;
215 $storeClass = LCStoreCDB
::class;
217 $storeClass = LCStoreDB
::class;
221 throw new MWException(
222 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
227 wfDebugLog( 'caches', static::class . ": using store $storeClass" );
228 if ( !empty( $conf['storeDirectory'] ) ) {
229 $storeConf['directory'] = $conf['storeDirectory'];
232 $this->store
= new $storeClass( $storeConf );
233 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
234 if ( isset( $conf[$var] ) ) {
235 $this->$var = $conf[$var];
241 * Returns true if the given key is mergeable, that is, if it is an associative
242 * array which can be merged through a fallback sequence.
246 public function isMergeableKey( $key ) {
247 if ( $this->mergeableKeys
=== null ) {
248 $this->mergeableKeys
= array_flip( array_merge(
249 self
::$mergeableMapKeys,
250 self
::$mergeableListKeys,
251 self
::$mergeableAliasListKeys,
252 self
::$optionalMergeKeys,
257 return isset( $this->mergeableKeys
[$key] );
263 * Warning: this may be slow for split items (messages), since it will
264 * need to fetch all of the subitems from the cache individually.
265 * @param string $code
269 public function getItem( $code, $key ) {
270 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
271 $this->loadItem( $code, $key );
274 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
275 return $this->shallowFallbacks
[$code];
278 return $this->data
[$code][$key];
282 * Get a subitem, for instance a single message for a given language.
283 * @param string $code
285 * @param string $subkey
288 public function getSubitem( $code, $key, $subkey ) {
289 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
290 !isset( $this->loadedItems
[$code][$key] )
292 $this->loadSubitem( $code, $key, $subkey );
295 return $this->data
[$code][$key][$subkey] ??
null;
299 * Get the list of subitem keys for a given item.
301 * This is faster than array_keys($lc->getItem(...)) for the items listed in
304 * Will return null if the item is not found, or false if the item is not an
306 * @param string $code
308 * @return bool|null|string|string[]
310 public function getSubitemList( $code, $key ) {
311 if ( in_array( $key, self
::$splitKeys ) ) {
312 return $this->getSubitem( $code, 'list', $key );
314 $item = $this->getItem( $code, $key );
315 if ( is_array( $item ) ) {
316 return array_keys( $item );
324 * Load an item into the cache.
325 * @param string $code
328 protected function loadItem( $code, $key ) {
329 if ( !isset( $this->initialisedLangs
[$code] ) ) {
330 $this->initLanguage( $code );
333 // Check to see if initLanguage() loaded it for us
334 if ( isset( $this->loadedItems
[$code][$key] ) ) {
338 if ( isset( $this->shallowFallbacks
[$code] ) ) {
339 $this->loadItem( $this->shallowFallbacks
[$code], $key );
344 if ( in_array( $key, self
::$splitKeys ) ) {
345 $subkeyList = $this->getSubitem( $code, 'list', $key );
346 foreach ( $subkeyList as $subkey ) {
347 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
350 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
353 $this->data
[$code][$key] = $this->store
->get( $code, $key );
356 $this->loadedItems
[$code][$key] = true;
360 * Load a subitem into the cache
361 * @param string $code
363 * @param string $subkey
365 protected function loadSubitem( $code, $key, $subkey ) {
366 if ( !in_array( $key, self
::$splitKeys ) ) {
367 $this->loadItem( $code, $key );
372 if ( !isset( $this->initialisedLangs
[$code] ) ) {
373 $this->initLanguage( $code );
376 // Check to see if initLanguage() loaded it for us
377 if ( isset( $this->loadedItems
[$code][$key] ) ||
378 isset( $this->loadedSubitems
[$code][$key][$subkey] )
383 if ( isset( $this->shallowFallbacks
[$code] ) ) {
384 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
389 $value = $this->store
->get( $code, "$key:$subkey" );
390 $this->data
[$code][$key][$subkey] = $value;
391 $this->loadedSubitems
[$code][$key][$subkey] = true;
395 * Returns true if the cache identified by $code is missing or expired.
397 * @param string $code
401 public function isExpired( $code ) {
402 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
403 wfDebug( __METHOD__
. "($code): forced reload\n" );
408 $deps = $this->store
->get( $code, 'deps' );
409 $keys = $this->store
->get( $code, 'list' );
410 $preload = $this->store
->get( $code, 'preload' );
411 // Different keys may expire separately for some stores
412 if ( $deps === null ||
$keys === null ||
$preload === null ) {
413 wfDebug( __METHOD__
. "($code): cache missing, need to make one\n" );
418 foreach ( $deps as $dep ) {
419 // Because we're unserializing stuff from cache, we
420 // could receive objects of classes that don't exist
421 // anymore (e.g. uninstalled extensions)
422 // When this happens, always expire the cache
423 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
424 wfDebug( __METHOD__
. "($code): cache for $code expired due to " .
425 get_class( $dep ) . "\n" );
435 * Initialise a language in this object. Rebuild the cache if necessary.
436 * @param string $code
437 * @throws MWException
439 protected function initLanguage( $code ) {
440 if ( isset( $this->initialisedLangs
[$code] ) ) {
444 $this->initialisedLangs
[$code] = true;
446 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
447 if ( !Language
::isValidBuiltInCode( $code ) ) {
448 $this->initShallowFallback( $code, 'en' );
453 # Recache the data if necessary
454 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
455 if ( Language
::isSupportedLanguage( $code ) ) {
456 $this->recache( $code );
457 } elseif ( $code === 'en' ) {
458 throw new MWException( 'MessagesEn.php is missing.' );
460 $this->initShallowFallback( $code, 'en' );
467 $preload = $this->getItem( $code, 'preload' );
468 if ( $preload === null ) {
469 if ( $this->manualRecache
) {
470 // No Messages*.php file. Do shallow fallback to en.
471 if ( $code === 'en' ) {
472 throw new MWException( 'No localisation cache found for English. ' .
473 'Please run maintenance/rebuildLocalisationCache.php.' );
475 $this->initShallowFallback( $code, 'en' );
479 throw new MWException( 'Invalid or missing localisation cache.' );
482 $this->data
[$code] = $preload;
483 foreach ( $preload as $key => $item ) {
484 if ( in_array( $key, self
::$splitKeys ) ) {
485 foreach ( $item as $subkey => $subitem ) {
486 $this->loadedSubitems
[$code][$key][$subkey] = true;
489 $this->loadedItems
[$code][$key] = true;
495 * Create a fallback from one language to another, without creating a
496 * complete persistent cache.
497 * @param string $primaryCode
498 * @param string $fallbackCode
500 public function initShallowFallback( $primaryCode, $fallbackCode ) {
501 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
502 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
503 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
504 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
508 * Read a PHP file containing localisation data.
509 * @param string $_fileName
510 * @param string $_fileType
511 * @throws MWException
514 protected function readPHPFile( $_fileName, $_fileType ) {
515 // Disable APC caching
516 Wikimedia\
suppressWarnings();
517 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
518 Wikimedia\restoreWarnings
();
522 Wikimedia\
suppressWarnings();
523 ini_set( 'apc.cache_by_default', $_apcEnabled );
524 Wikimedia\restoreWarnings
();
526 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
527 $data = compact( self
::$allKeys );
528 } elseif ( $_fileType == 'aliases' ) {
529 $data = compact( 'aliases' );
531 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
538 * Read a JSON file containing localisation messages.
539 * @param string $fileName Name of file to read
540 * @throws MWException If there is a syntax error in the JSON file
541 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
543 public function readJSONFile( $fileName ) {
544 if ( !is_readable( $fileName ) ) {
548 $json = file_get_contents( $fileName );
549 if ( $json === false ) {
553 $data = FormatJson
::decode( $json, true );
554 if ( $data === null ) {
555 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
558 // Remove keys starting with '@', they're reserved for metadata and non-message data
559 foreach ( $data as $key => $unused ) {
560 if ( $key === '' ||
$key[0] === '@' ) {
561 unset( $data[$key] );
565 // The JSON format only supports messages, none of the other variables, so wrap the data
566 return [ 'messages' => $data ];
570 * Get the compiled plural rules for a given language from the XML files.
572 * @param string $code
575 public function getCompiledPluralRules( $code ) {
576 $rules = $this->getPluralRules( $code );
577 if ( $rules === null ) {
581 $compiledRules = Evaluator
::compile( $rules );
582 } catch ( CLDRPluralRuleError
$e ) {
583 wfDebugLog( 'l10n', $e->getMessage() );
588 return $compiledRules;
592 * Get the plural rules for a given language from the XML files.
595 * @param string $code
598 public function getPluralRules( $code ) {
599 if ( $this->pluralRules
=== null ) {
600 $this->loadPluralFiles();
602 return $this->pluralRules
[$code] ??
null;
606 * Get the plural rule types for a given language from the XML files.
609 * @param string $code
612 public function getPluralRuleTypes( $code ) {
613 if ( $this->pluralRuleTypes
=== null ) {
614 $this->loadPluralFiles();
616 return $this->pluralRuleTypes
[$code] ??
null;
620 * Load the plural XML files.
622 protected function loadPluralFiles() {
624 $cldrPlural = "$IP/languages/data/plurals.xml";
625 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
626 // Load CLDR plural rules
627 $this->loadPluralFile( $cldrPlural );
628 if ( file_exists( $mwPlural ) ) {
629 // Override or extend
630 $this->loadPluralFile( $mwPlural );
635 * Load a plural XML file with the given filename, compile the relevant
636 * rules, and save the compiled rules in a process-local cache.
638 * @param string $fileName
639 * @throws MWException
641 protected function loadPluralFile( $fileName ) {
642 // Use file_get_contents instead of DOMDocument::load (T58439)
643 $xml = file_get_contents( $fileName );
645 throw new MWException( "Unable to read plurals file $fileName" );
647 $doc = new DOMDocument
;
648 $doc->loadXML( $xml );
649 $rulesets = $doc->getElementsByTagName( "pluralRules" );
650 foreach ( $rulesets as $ruleset ) {
651 $codes = $ruleset->getAttribute( 'locales' );
654 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
655 foreach ( $ruleElements as $elt ) {
656 $ruleType = $elt->getAttribute( 'count' );
657 if ( $ruleType === 'other' ) {
658 // Don't record "other" rules, which have an empty condition
661 $rules[] = $elt->nodeValue
;
662 $ruleTypes[] = $ruleType;
664 foreach ( explode( ' ', $codes ) as $code ) {
665 $this->pluralRules
[$code] = $rules;
666 $this->pluralRuleTypes
[$code] = $ruleTypes;
672 * Read the data from the source files for a given language, and register
673 * the relevant dependencies in the $deps array. If the localisation
674 * exists, the data array is returned, otherwise false is returned.
676 * @param string $code
677 * @param array &$deps
680 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
683 // This reads in the PHP i18n file with non-messages l10n data
684 $fileName = Language
::getMessagesFileName( $code );
685 if ( !file_exists( $fileName ) ) {
688 $deps[] = new FileDependency( $fileName );
689 $data = $this->readPHPFile( $fileName, 'core' );
692 # Load CLDR plural rules for JavaScript
693 $data['pluralRules'] = $this->getPluralRules( $code );
695 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
696 # Load plural rule types
697 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
699 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
700 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
706 * Merge two localisation values, a primary and a fallback, overwriting the
707 * primary value in place.
709 * @param mixed &$value
710 * @param mixed $fallbackValue
712 protected function mergeItem( $key, &$value, $fallbackValue ) {
713 if ( !is_null( $value ) ) {
714 if ( !is_null( $fallbackValue ) ) {
715 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
716 $value = $value +
$fallbackValue;
717 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
718 $value = array_unique( array_merge( $fallbackValue, $value ) );
719 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
720 $value = array_merge_recursive( $value, $fallbackValue );
721 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
722 if ( !empty( $value['inherit'] ) ) {
723 $value = array_merge( $fallbackValue, $value );
726 if ( isset( $value['inherit'] ) ) {
727 unset( $value['inherit'] );
729 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
730 $this->mergeMagicWords( $value, $fallbackValue );
734 $value = $fallbackValue;
739 * @param mixed &$value
740 * @param mixed $fallbackValue
742 protected function mergeMagicWords( &$value, $fallbackValue ) {
743 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
744 if ( !isset( $value[$magicName] ) ) {
745 $value[$magicName] = $fallbackInfo;
747 $oldSynonyms = array_slice( $fallbackInfo, 1 );
748 $newSynonyms = array_slice( $value[$magicName], 1 );
749 $synonyms = array_values( array_unique( array_merge(
750 $newSynonyms, $oldSynonyms ) ) );
751 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
757 * Given an array mapping language code to localisation value, such as is
758 * found in extension *.i18n.php files, iterate through a fallback sequence
759 * to merge the given data with an existing primary value.
761 * Returns true if any data from the extension array was used, false
763 * @param array $codeSequence
765 * @param mixed &$value
766 * @param mixed $fallbackValue
769 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
771 foreach ( $codeSequence as $code ) {
772 if ( isset( $fallbackValue[$code] ) ) {
773 $this->mergeItem( $key, $value, $fallbackValue[$code] );
782 * Gets the combined list of messages dirs from
783 * core and extensions
788 public function getMessagesDirs() {
791 $config = MediaWikiServices
::getInstance()->getMainConfig();
792 $messagesDirs = $config->get( 'MessagesDirs' );
794 'core' => "$IP/languages/i18n",
795 'api' => "$IP/includes/api/i18n",
796 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
801 * Load localisation data for a given language for both core and extensions
802 * and save it to the persistent cache store and the process cache
803 * @param string $code
804 * @throws MWException
806 public function recache( $code ) {
807 global $wgExtensionMessagesFiles;
810 throw new MWException( "Invalid language code requested" );
812 $this->recachedLangs
[$code] = true;
815 $initialData = array_fill_keys( self
::$allKeys, null );
816 $coreData = $initialData;
819 # Load the primary localisation from the source file
820 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
821 if ( $data === false ) {
822 wfDebug( __METHOD__
. ": no localisation file for $code, using fallback to en\n" );
823 $coreData['fallback'] = 'en';
825 wfDebug( __METHOD__
. ": got localisation for $code from source\n" );
827 # Merge primary localisation
828 foreach ( $data as $key => $value ) {
829 $this->mergeItem( $key, $coreData[$key], $value );
833 # Fill in the fallback if it's not there already
834 if ( is_null( $coreData['fallback'] ) ) {
835 $coreData['fallback'] = $code === 'en' ?
false : 'en';
837 if ( $coreData['fallback'] === false ) {
838 $coreData['fallbackSequence'] = [];
840 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
841 $len = count( $coreData['fallbackSequence'] );
843 # Ensure that the sequence ends at en
844 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
845 $coreData['fallbackSequence'][] = 'en';
849 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
850 $messageDirs = $this->getMessagesDirs();
852 # Load non-JSON localisation data for extensions
853 $extensionData = array_fill_keys( $codeSequence, $initialData );
854 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
855 if ( isset( $messageDirs[$extension] ) ) {
856 # This extension has JSON message data; skip the PHP shim
860 $data = $this->readPHPFile( $fileName, 'extension' );
863 foreach ( $data as $key => $item ) {
864 foreach ( $codeSequence as $csCode ) {
865 if ( isset( $item[$csCode] ) ) {
866 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
873 $deps[] = new FileDependency( $fileName );
877 # Load the localisation data for each fallback, then merge it into the full array
878 $allData = $initialData;
879 foreach ( $codeSequence as $csCode ) {
880 $csData = $initialData;
882 # Load core messages and the extension localisations.
883 foreach ( $messageDirs as $dirs ) {
884 foreach ( (array)$dirs as $dir ) {
885 $fileName = "$dir/$csCode.json";
886 $data = $this->readJSONFile( $fileName );
888 foreach ( $data as $key => $item ) {
889 $this->mergeItem( $key, $csData[$key], $item );
892 $deps[] = new FileDependency( $fileName );
896 # Merge non-JSON extension data
897 if ( isset( $extensionData[$csCode] ) ) {
898 foreach ( $extensionData[$csCode] as $key => $item ) {
899 $this->mergeItem( $key, $csData[$key], $item );
903 if ( $csCode === $code ) {
904 # Merge core data into extension data
905 foreach ( $coreData as $key => $item ) {
906 $this->mergeItem( $key, $csData[$key], $item );
909 # Load the secondary localisation from the source file to
910 # avoid infinite cycles on cyclic fallbacks
911 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
912 if ( $fbData !== false ) {
913 # Only merge the keys that make sense to merge
914 foreach ( self
::$allKeys as $key ) {
915 if ( !isset( $fbData[$key] ) ) {
919 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
920 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
926 # Allow extensions an opportunity to adjust the data for this
928 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
930 # Merge the data for this fallback into the final array
931 if ( $csCode === $code ) {
934 foreach ( self
::$allKeys as $key ) {
935 if ( !isset( $csData[$key] ) ) {
939 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
940 $this->mergeItem( $key, $allData[$key], $csData[$key] );
946 # Add cache dependencies for any referenced globals
947 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
948 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
949 // We use the key 'wgMessagesDirs' for historical reasons.
950 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
951 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
953 # Add dependencies to the cache entry
954 $allData['deps'] = $deps;
956 # Replace spaces with underscores in namespace names
957 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
959 # And do the same for special page aliases. $page is an array.
960 foreach ( $allData['specialPageAliases'] as &$page ) {
961 $page = str_replace( ' ', '_', $page );
963 # Decouple the reference to prevent accidental damage
966 # If there were no plural rules, return an empty array
967 if ( $allData['pluralRules'] === null ) {
968 $allData['pluralRules'] = [];
970 if ( $allData['compiledPluralRules'] === null ) {
971 $allData['compiledPluralRules'] = [];
973 # If there were no plural rule types, return an empty array
974 if ( $allData['pluralRuleTypes'] === null ) {
975 $allData['pluralRuleTypes'] = [];
979 $allData['list'] = [];
980 foreach ( self
::$splitKeys as $key ) {
981 $allData['list'][$key] = array_keys( $allData[$key] );
985 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$purgeBlobs ] );
987 if ( is_null( $allData['namespaceNames'] ) ) {
988 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
989 'Check that your languages/messages/MessagesEn.php file is intact.' );
992 # Set the preload key
993 $allData['preload'] = $this->buildPreload( $allData );
995 # Save to the process cache and register the items loaded
996 $this->data
[$code] = $allData;
997 foreach ( $allData as $key => $item ) {
998 $this->loadedItems
[$code][$key] = true;
1001 # Save to the persistent cache
1002 $this->store
->startWrite( $code );
1003 foreach ( $allData as $key => $value ) {
1004 if ( in_array( $key, self
::$splitKeys ) ) {
1005 foreach ( $value as $subkey => $subvalue ) {
1006 $this->store
->set( "$key:$subkey", $subvalue );
1009 $this->store
->set( $key, $value );
1012 $this->store
->finishWrite();
1014 # Clear out the MessageBlobStore
1015 # HACK: If using a null (i.e. disabled) storage backend, we
1016 # can't write to the MessageBlobStore either
1017 if ( $purgeBlobs && !$this->store
instanceof LCStoreNull
) {
1018 $blobStore = new MessageBlobStore();
1019 $blobStore->clear();
1024 * Build the preload item from the given pre-cache data.
1026 * The preload item will be loaded automatically, improving performance
1027 * for the commonly-requested items it contains.
1028 * @param array $data
1031 protected function buildPreload( $data ) {
1032 $preload = [ 'messages' => [] ];
1033 foreach ( self
::$preloadedKeys as $key ) {
1034 $preload[$key] = $data[$key];
1037 foreach ( $data['preloadedMessages'] as $subkey ) {
1038 $subitem = $data['messages'][$subkey] ??
null;
1039 $preload['messages'][$subkey] = $subitem;
1046 * Unload the data for a given language from the object cache.
1047 * Reduces memory usage.
1048 * @param string $code
1050 public function unload( $code ) {
1051 unset( $this->data
[$code] );
1052 unset( $this->loadedItems
[$code] );
1053 unset( $this->loadedSubitems
[$code] );
1054 unset( $this->initialisedLangs
[$code] );
1055 unset( $this->shallowFallbacks
[$code] );
1057 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1058 if ( $fbCode === $code ) {
1059 $this->unload( $shallowCode );
1067 public function unloadAll() {
1068 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1069 $this->unload( $lang );
1074 * Disable the storage backend
1076 public function disableBackend() {
1077 $this->store
= new LCStoreNull
;
1078 $this->manualRecache
= false;