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 Cdb\Reader
as CdbReader
;
24 use Cdb\Writer
as CdbWriter
;
25 use CLDRPluralRuleParser\Evaluator
;
26 use CLDRPluralRuleParser\Error
as CLDRPluralRuleError
;
27 use MediaWiki\MediaWikiServices
;
30 * Class for caching the contents of localisation files, Messages*.php
33 * An instance of this class is available using Language::getLocalisationCache().
35 * The values retrieved from here are merged, containing items from extension
36 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
37 * zh-hans -> en ). Some common errors are corrected, for example namespace
38 * names with spaces instead of underscores, but heavyweight processing, such
39 * as grammatical transformation, is done by the caller.
41 class LocalisationCache
{
44 /** Configuration associative array */
48 * True if recaching should only be done on an explicit call to recache().
49 * Setting this reduces the overhead of cache freshness checking, which
50 * requires doing a stat() for every extension i18n file.
52 private $manualRecache = false;
55 * True to treat all files as expired until they are regenerated by this object.
57 private $forceRecache = false;
60 * The cache data. 3-d array, where the first key is the language code,
61 * the second key is the item key e.g. 'messages', and the third key is
62 * an item specific subkey index. Some items are not arrays and so for those
63 * items, there are no subkeys.
68 * The persistent store object. An instance of LCStore.
75 * A 2-d associative array, code/key, where presence indicates that the item
76 * is loaded. Value arbitrary.
78 * For split items, if set, this indicates that all of the subitems have been
81 private $loadedItems = [];
84 * A 3-d associative array, code/key/subkey, where presence indicates that
85 * the subitem is loaded. Only used for the split items, i.e. messages.
87 private $loadedSubitems = [];
90 * An array where presence of a key indicates that that language has been
91 * initialised. Initialisation includes checking for cache expiry and doing
92 * any necessary updates.
94 private $initialisedLangs = [];
97 * An array mapping non-existent pseudo-languages to fallback languages. This
98 * is filled by initShallowFallback() when data is requested from a language
99 * that lacks a Messages*.php file.
101 private $shallowFallbacks = [];
104 * An array where the keys are codes that have been recached by this instance.
106 private $recachedLangs = [];
111 static public $allKeys = [
112 'fallback', 'namespaceNames', 'bookstoreList',
113 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
114 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
115 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
116 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
117 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
118 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
119 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
123 * Keys for items which consist of associative arrays, which may be merged
124 * by a fallback sequence.
126 static public $mergeableMapKeys = [ 'messages', 'namespaceNames',
127 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
131 * Keys for items which are a numbered array.
133 static public $mergeableListKeys = [ 'extraUserToggles' ];
136 * Keys for items which contain an array of arrays of equivalent aliases
137 * for each subitem. The aliases may be merged by a fallback sequence.
139 static public $mergeableAliasListKeys = [ 'specialPageAliases' ];
142 * Keys for items which contain an associative array, and may be merged if
143 * the primary value contains the special array key "inherit". That array
144 * key is removed after the first merge.
146 static public $optionalMergeKeys = [ 'bookstoreList' ];
149 * Keys for items that are formatted like $magicWords
151 static public $magicWordKeys = [ 'magicWords' ];
154 * Keys for items where the subitems are stored in the backend separately.
156 static public $splitKeys = [ 'messages' ];
159 * Keys which are loaded automatically by initLanguage()
161 static public $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
164 * Associative array of cached plural rules. The key is the language code,
165 * the value is an array of plural rules for that language.
167 private $pluralRules = null;
170 * Associative array of cached plural rule types. The key is the language
171 * code, the value is an array of plural rule types for that language. For
172 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
173 * The index for each rule type matches the index for the rule in
174 * $pluralRules, thus allowing correlation between the two. The reason we
175 * don't just use the type names as the keys in $pluralRules is because
176 * Language::convertPlural applies the rules based on numeric order (or
177 * explicit numeric parameter), not based on the name of the rule type. For
178 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
179 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
181 private $pluralRuleTypes = null;
183 private $mergeableKeys = null;
187 * For constructor parameters, see the documentation in DefaultSettings.php
188 * for $wgLocalisationCacheConf.
191 * @throws MWException
193 function __construct( $conf ) {
194 global $wgCacheDirectory;
198 if ( !empty( $conf['storeClass'] ) ) {
199 $storeClass = $conf['storeClass'];
201 switch ( $conf['store'] ) {
204 $storeClass = 'LCStoreCDB';
207 $storeClass = 'LCStoreDB';
210 $storeClass = 'LCStoreStaticArray';
213 if ( !empty( $conf['storeDirectory'] ) ) {
214 $storeClass = 'LCStoreCDB';
215 } elseif ( $wgCacheDirectory ) {
216 $storeConf['directory'] = $wgCacheDirectory;
217 $storeClass = 'LCStoreCDB';
219 $storeClass = 'LCStoreDB';
223 throw new MWException(
224 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
229 wfDebugLog( 'caches', static::class . ": using store $storeClass" );
230 if ( !empty( $conf['storeDirectory'] ) ) {
231 $storeConf['directory'] = $conf['storeDirectory'];
234 $this->store
= new $storeClass( $storeConf );
235 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
236 if ( isset( $conf[$var] ) ) {
237 $this->$var = $conf[$var];
243 * Returns true if the given key is mergeable, that is, if it is an associative
244 * array which can be merged through a fallback sequence.
248 public function isMergeableKey( $key ) {
249 if ( $this->mergeableKeys
=== null ) {
250 $this->mergeableKeys
= array_flip( array_merge(
251 self
::$mergeableMapKeys,
252 self
::$mergeableListKeys,
253 self
::$mergeableAliasListKeys,
254 self
::$optionalMergeKeys,
259 return isset( $this->mergeableKeys
[$key] );
265 * Warning: this may be slow for split items (messages), since it will
266 * need to fetch all of the subitems from the cache individually.
267 * @param string $code
271 public function getItem( $code, $key ) {
272 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
273 $this->loadItem( $code, $key );
276 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
277 return $this->shallowFallbacks
[$code];
280 return $this->data
[$code][$key];
284 * Get a subitem, for instance a single message for a given language.
285 * @param string $code
287 * @param string $subkey
290 public function getSubitem( $code, $key, $subkey ) {
291 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
292 !isset( $this->loadedItems
[$code][$key] )
294 $this->loadSubitem( $code, $key, $subkey );
297 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
298 return $this->data
[$code][$key][$subkey];
305 * Get the list of subitem keys for a given item.
307 * This is faster than array_keys($lc->getItem(...)) for the items listed in
310 * Will return null if the item is not found, or false if the item is not an
312 * @param string $code
314 * @return bool|null|string|string[]
316 public function getSubitemList( $code, $key ) {
317 if ( in_array( $key, self
::$splitKeys ) ) {
318 return $this->getSubitem( $code, 'list', $key );
320 $item = $this->getItem( $code, $key );
321 if ( is_array( $item ) ) {
322 return array_keys( $item );
330 * Load an item into the cache.
331 * @param string $code
334 protected function loadItem( $code, $key ) {
335 if ( !isset( $this->initialisedLangs
[$code] ) ) {
336 $this->initLanguage( $code );
339 // Check to see if initLanguage() loaded it for us
340 if ( isset( $this->loadedItems
[$code][$key] ) ) {
344 if ( isset( $this->shallowFallbacks
[$code] ) ) {
345 $this->loadItem( $this->shallowFallbacks
[$code], $key );
350 if ( in_array( $key, self
::$splitKeys ) ) {
351 $subkeyList = $this->getSubitem( $code, 'list', $key );
352 foreach ( $subkeyList as $subkey ) {
353 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
356 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
359 $this->data
[$code][$key] = $this->store
->get( $code, $key );
362 $this->loadedItems
[$code][$key] = true;
366 * Load a subitem into the cache
367 * @param string $code
369 * @param string $subkey
371 protected function loadSubitem( $code, $key, $subkey ) {
372 if ( !in_array( $key, self
::$splitKeys ) ) {
373 $this->loadItem( $code, $key );
378 if ( !isset( $this->initialisedLangs
[$code] ) ) {
379 $this->initLanguage( $code );
382 // Check to see if initLanguage() loaded it for us
383 if ( isset( $this->loadedItems
[$code][$key] ) ||
384 isset( $this->loadedSubitems
[$code][$key][$subkey] )
389 if ( isset( $this->shallowFallbacks
[$code] ) ) {
390 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
395 $value = $this->store
->get( $code, "$key:$subkey" );
396 $this->data
[$code][$key][$subkey] = $value;
397 $this->loadedSubitems
[$code][$key][$subkey] = true;
401 * Returns true if the cache identified by $code is missing or expired.
403 * @param string $code
407 public function isExpired( $code ) {
408 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
409 wfDebug( __METHOD__
. "($code): forced reload\n" );
414 $deps = $this->store
->get( $code, 'deps' );
415 $keys = $this->store
->get( $code, 'list' );
416 $preload = $this->store
->get( $code, 'preload' );
417 // Different keys may expire separately for some stores
418 if ( $deps === null ||
$keys === null ||
$preload === null ) {
419 wfDebug( __METHOD__
. "($code): cache missing, need to make one\n" );
424 foreach ( $deps as $dep ) {
425 // Because we're unserializing stuff from cache, we
426 // could receive objects of classes that don't exist
427 // anymore (e.g. uninstalled extensions)
428 // When this happens, always expire the cache
429 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
430 wfDebug( __METHOD__
. "($code): cache for $code expired due to " .
431 get_class( $dep ) . "\n" );
441 * Initialise a language in this object. Rebuild the cache if necessary.
442 * @param string $code
443 * @throws MWException
445 protected function initLanguage( $code ) {
446 if ( isset( $this->initialisedLangs
[$code] ) ) {
450 $this->initialisedLangs
[$code] = true;
452 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
453 if ( !Language
::isValidBuiltInCode( $code ) ) {
454 $this->initShallowFallback( $code, 'en' );
459 # Recache the data if necessary
460 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
461 if ( Language
::isSupportedLanguage( $code ) ) {
462 $this->recache( $code );
463 } elseif ( $code === 'en' ) {
464 throw new MWException( 'MessagesEn.php is missing.' );
466 $this->initShallowFallback( $code, 'en' );
473 $preload = $this->getItem( $code, 'preload' );
474 if ( $preload === null ) {
475 if ( $this->manualRecache
) {
476 // No Messages*.php file. Do shallow fallback to en.
477 if ( $code === 'en' ) {
478 throw new MWException( 'No localisation cache found for English. ' .
479 'Please run maintenance/rebuildLocalisationCache.php.' );
481 $this->initShallowFallback( $code, 'en' );
485 throw new MWException( 'Invalid or missing localisation cache.' );
488 $this->data
[$code] = $preload;
489 foreach ( $preload as $key => $item ) {
490 if ( in_array( $key, self
::$splitKeys ) ) {
491 foreach ( $item as $subkey => $subitem ) {
492 $this->loadedSubitems
[$code][$key][$subkey] = true;
495 $this->loadedItems
[$code][$key] = true;
501 * Create a fallback from one language to another, without creating a
502 * complete persistent cache.
503 * @param string $primaryCode
504 * @param string $fallbackCode
506 public function initShallowFallback( $primaryCode, $fallbackCode ) {
507 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
508 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
509 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
510 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
514 * Read a PHP file containing localisation data.
515 * @param string $_fileName
516 * @param string $_fileType
517 * @throws MWException
520 protected function readPHPFile( $_fileName, $_fileType ) {
521 // Disable APC caching
522 MediaWiki\
suppressWarnings();
523 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
524 MediaWiki\restoreWarnings
();
528 MediaWiki\
suppressWarnings();
529 ini_set( 'apc.cache_by_default', $_apcEnabled );
530 MediaWiki\restoreWarnings
();
532 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
533 $data = compact( self
::$allKeys );
534 } elseif ( $_fileType == 'aliases' ) {
535 $data = compact( 'aliases' );
537 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
544 * Read a JSON file containing localisation messages.
545 * @param string $fileName Name of file to read
546 * @throws MWException If there is a syntax error in the JSON file
547 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
549 public function readJSONFile( $fileName ) {
550 if ( !is_readable( $fileName ) ) {
554 $json = file_get_contents( $fileName );
555 if ( $json === false ) {
559 $data = FormatJson
::decode( $json, true );
560 if ( $data === null ) {
561 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
564 // Remove keys starting with '@', they're reserved for metadata and non-message data
565 foreach ( $data as $key => $unused ) {
566 if ( $key === '' ||
$key[0] === '@' ) {
567 unset( $data[$key] );
571 // The JSON format only supports messages, none of the other variables, so wrap the data
572 return [ 'messages' => $data ];
576 * Get the compiled plural rules for a given language from the XML files.
578 * @param string $code
581 public function getCompiledPluralRules( $code ) {
582 $rules = $this->getPluralRules( $code );
583 if ( $rules === null ) {
587 $compiledRules = Evaluator
::compile( $rules );
588 } catch ( CLDRPluralRuleError
$e ) {
589 wfDebugLog( 'l10n', $e->getMessage() );
594 return $compiledRules;
598 * Get the plural rules for a given language from the XML files.
601 * @param string $code
604 public function getPluralRules( $code ) {
605 if ( $this->pluralRules
=== null ) {
606 $this->loadPluralFiles();
608 if ( !isset( $this->pluralRules
[$code] ) ) {
611 return $this->pluralRules
[$code];
616 * Get the plural rule types for a given language from the XML files.
619 * @param string $code
622 public function getPluralRuleTypes( $code ) {
623 if ( $this->pluralRuleTypes
=== null ) {
624 $this->loadPluralFiles();
626 if ( !isset( $this->pluralRuleTypes
[$code] ) ) {
629 return $this->pluralRuleTypes
[$code];
634 * Load the plural XML files.
636 protected function loadPluralFiles() {
638 $cldrPlural = "$IP/languages/data/plurals.xml";
639 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
640 // Load CLDR plural rules
641 $this->loadPluralFile( $cldrPlural );
642 if ( file_exists( $mwPlural ) ) {
643 // Override or extend
644 $this->loadPluralFile( $mwPlural );
649 * Load a plural XML file with the given filename, compile the relevant
650 * rules, and save the compiled rules in a process-local cache.
652 * @param string $fileName
653 * @throws MWException
655 protected function loadPluralFile( $fileName ) {
656 // Use file_get_contents instead of DOMDocument::load (T58439)
657 $xml = file_get_contents( $fileName );
659 throw new MWException( "Unable to read plurals file $fileName" );
661 $doc = new DOMDocument
;
662 $doc->loadXML( $xml );
663 $rulesets = $doc->getElementsByTagName( "pluralRules" );
664 foreach ( $rulesets as $ruleset ) {
665 $codes = $ruleset->getAttribute( 'locales' );
668 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
669 foreach ( $ruleElements as $elt ) {
670 $ruleType = $elt->getAttribute( 'count' );
671 if ( $ruleType === 'other' ) {
672 // Don't record "other" rules, which have an empty condition
675 $rules[] = $elt->nodeValue
;
676 $ruleTypes[] = $ruleType;
678 foreach ( explode( ' ', $codes ) as $code ) {
679 $this->pluralRules
[$code] = $rules;
680 $this->pluralRuleTypes
[$code] = $ruleTypes;
686 * Read the data from the source files for a given language, and register
687 * the relevant dependencies in the $deps array. If the localisation
688 * exists, the data array is returned, otherwise false is returned.
690 * @param string $code
694 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
697 // This reads in the PHP i18n file with non-messages l10n data
698 $fileName = Language
::getMessagesFileName( $code );
699 if ( !file_exists( $fileName ) ) {
702 $deps[] = new FileDependency( $fileName );
703 $data = $this->readPHPFile( $fileName, 'core' );
706 # Load CLDR plural rules for JavaScript
707 $data['pluralRules'] = $this->getPluralRules( $code );
709 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
710 # Load plural rule types
711 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
713 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
714 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
720 * Merge two localisation values, a primary and a fallback, overwriting the
721 * primary value in place.
723 * @param mixed $value
724 * @param mixed $fallbackValue
726 protected function mergeItem( $key, &$value, $fallbackValue ) {
727 if ( !is_null( $value ) ) {
728 if ( !is_null( $fallbackValue ) ) {
729 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
730 $value = $value +
$fallbackValue;
731 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
732 $value = array_unique( array_merge( $fallbackValue, $value ) );
733 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
734 $value = array_merge_recursive( $value, $fallbackValue );
735 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
736 if ( !empty( $value['inherit'] ) ) {
737 $value = array_merge( $fallbackValue, $value );
740 if ( isset( $value['inherit'] ) ) {
741 unset( $value['inherit'] );
743 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
744 $this->mergeMagicWords( $value, $fallbackValue );
748 $value = $fallbackValue;
753 * @param mixed $value
754 * @param mixed $fallbackValue
756 protected function mergeMagicWords( &$value, $fallbackValue ) {
757 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
758 if ( !isset( $value[$magicName] ) ) {
759 $value[$magicName] = $fallbackInfo;
761 $oldSynonyms = array_slice( $fallbackInfo, 1 );
762 $newSynonyms = array_slice( $value[$magicName], 1 );
763 $synonyms = array_values( array_unique( array_merge(
764 $newSynonyms, $oldSynonyms ) ) );
765 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
771 * Given an array mapping language code to localisation value, such as is
772 * found in extension *.i18n.php files, iterate through a fallback sequence
773 * to merge the given data with an existing primary value.
775 * Returns true if any data from the extension array was used, false
777 * @param array $codeSequence
779 * @param mixed $value
780 * @param mixed $fallbackValue
783 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
785 foreach ( $codeSequence as $code ) {
786 if ( isset( $fallbackValue[$code] ) ) {
787 $this->mergeItem( $key, $value, $fallbackValue[$code] );
796 * Gets the combined list of messages dirs from
797 * core and extensions
802 public function getMessagesDirs() {
805 $config = MediaWikiServices
::getInstance()->getMainConfig();
806 $messagesDirs = $config->get( 'MessagesDirs' );
808 'core' => "$IP/languages/i18n",
809 'api' => "$IP/includes/api/i18n",
810 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
815 * Load localisation data for a given language for both core and extensions
816 * and save it to the persistent cache store and the process cache
817 * @param string $code
818 * @throws MWException
820 public function recache( $code ) {
821 global $wgExtensionMessagesFiles;
824 throw new MWException( "Invalid language code requested" );
826 $this->recachedLangs
[$code] = true;
829 $initialData = array_fill_keys( self
::$allKeys, null );
830 $coreData = $initialData;
833 # Load the primary localisation from the source file
834 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
835 if ( $data === false ) {
836 wfDebug( __METHOD__
. ": no localisation file for $code, using fallback to en\n" );
837 $coreData['fallback'] = 'en';
839 wfDebug( __METHOD__
. ": got localisation for $code from source\n" );
841 # Merge primary localisation
842 foreach ( $data as $key => $value ) {
843 $this->mergeItem( $key, $coreData[$key], $value );
847 # Fill in the fallback if it's not there already
848 if ( is_null( $coreData['fallback'] ) ) {
849 $coreData['fallback'] = $code === 'en' ?
false : 'en';
851 if ( $coreData['fallback'] === false ) {
852 $coreData['fallbackSequence'] = [];
854 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
855 $len = count( $coreData['fallbackSequence'] );
857 # Ensure that the sequence ends at en
858 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
859 $coreData['fallbackSequence'][] = 'en';
863 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
864 $messageDirs = $this->getMessagesDirs();
866 # Load non-JSON localisation data for extensions
867 $extensionData = array_fill_keys( $codeSequence, $initialData );
868 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
869 if ( isset( $messageDirs[$extension] ) ) {
870 # This extension has JSON message data; skip the PHP shim
874 $data = $this->readPHPFile( $fileName, 'extension' );
877 foreach ( $data as $key => $item ) {
878 foreach ( $codeSequence as $csCode ) {
879 if ( isset( $item[$csCode] ) ) {
880 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
887 $deps[] = new FileDependency( $fileName );
891 # Load the localisation data for each fallback, then merge it into the full array
892 $allData = $initialData;
893 foreach ( $codeSequence as $csCode ) {
894 $csData = $initialData;
896 # Load core messages and the extension localisations.
897 foreach ( $messageDirs as $dirs ) {
898 foreach ( (array)$dirs as $dir ) {
899 $fileName = "$dir/$csCode.json";
900 $data = $this->readJSONFile( $fileName );
902 foreach ( $data as $key => $item ) {
903 $this->mergeItem( $key, $csData[$key], $item );
906 $deps[] = new FileDependency( $fileName );
910 # Merge non-JSON extension data
911 if ( isset( $extensionData[$csCode] ) ) {
912 foreach ( $extensionData[$csCode] as $key => $item ) {
913 $this->mergeItem( $key, $csData[$key], $item );
917 if ( $csCode === $code ) {
918 # Merge core data into extension data
919 foreach ( $coreData as $key => $item ) {
920 $this->mergeItem( $key, $csData[$key], $item );
923 # Load the secondary localisation from the source file to
924 # avoid infinite cycles on cyclic fallbacks
925 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
926 if ( $fbData !== false ) {
927 # Only merge the keys that make sense to merge
928 foreach ( self
::$allKeys as $key ) {
929 if ( !isset( $fbData[$key] ) ) {
933 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
934 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
940 # Allow extensions an opportunity to adjust the data for this
942 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
944 # Merge the data for this fallback into the final array
945 if ( $csCode === $code ) {
948 foreach ( self
::$allKeys as $key ) {
949 if ( !isset( $csData[$key] ) ) {
953 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
954 $this->mergeItem( $key, $allData[$key], $csData[$key] );
960 # Add cache dependencies for any referenced globals
961 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
962 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
963 // We use the key 'wgMessagesDirs' for historical reasons.
964 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
965 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
967 # Add dependencies to the cache entry
968 $allData['deps'] = $deps;
970 # Replace spaces with underscores in namespace names
971 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
973 # And do the same for special page aliases. $page is an array.
974 foreach ( $allData['specialPageAliases'] as &$page ) {
975 $page = str_replace( ' ', '_', $page );
977 # Decouple the reference to prevent accidental damage
980 # If there were no plural rules, return an empty array
981 if ( $allData['pluralRules'] === null ) {
982 $allData['pluralRules'] = [];
984 if ( $allData['compiledPluralRules'] === null ) {
985 $allData['compiledPluralRules'] = [];
987 # If there were no plural rule types, return an empty array
988 if ( $allData['pluralRuleTypes'] === null ) {
989 $allData['pluralRuleTypes'] = [];
993 $allData['list'] = [];
994 foreach ( self
::$splitKeys as $key ) {
995 $allData['list'][$key] = array_keys( $allData[$key] );
999 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$purgeBlobs ] );
1001 if ( is_null( $allData['namespaceNames'] ) ) {
1002 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
1003 'Check that your languages/messages/MessagesEn.php file is intact.' );
1006 # Set the preload key
1007 $allData['preload'] = $this->buildPreload( $allData );
1009 # Save to the process cache and register the items loaded
1010 $this->data
[$code] = $allData;
1011 foreach ( $allData as $key => $item ) {
1012 $this->loadedItems
[$code][$key] = true;
1015 # Save to the persistent cache
1016 $this->store
->startWrite( $code );
1017 foreach ( $allData as $key => $value ) {
1018 if ( in_array( $key, self
::$splitKeys ) ) {
1019 foreach ( $value as $subkey => $subvalue ) {
1020 $this->store
->set( "$key:$subkey", $subvalue );
1023 $this->store
->set( $key, $value );
1026 $this->store
->finishWrite();
1028 # Clear out the MessageBlobStore
1029 # HACK: If using a null (i.e. disabled) storage backend, we
1030 # can't write to the MessageBlobStore either
1031 if ( $purgeBlobs && !$this->store
instanceof LCStoreNull
) {
1032 $blobStore = new MessageBlobStore();
1033 $blobStore->clear();
1038 * Build the preload item from the given pre-cache data.
1040 * The preload item will be loaded automatically, improving performance
1041 * for the commonly-requested items it contains.
1042 * @param array $data
1045 protected function buildPreload( $data ) {
1046 $preload = [ 'messages' => [] ];
1047 foreach ( self
::$preloadedKeys as $key ) {
1048 $preload[$key] = $data[$key];
1051 foreach ( $data['preloadedMessages'] as $subkey ) {
1052 if ( isset( $data['messages'][$subkey] ) ) {
1053 $subitem = $data['messages'][$subkey];
1057 $preload['messages'][$subkey] = $subitem;
1064 * Unload the data for a given language from the object cache.
1065 * Reduces memory usage.
1066 * @param string $code
1068 public function unload( $code ) {
1069 unset( $this->data
[$code] );
1070 unset( $this->loadedItems
[$code] );
1071 unset( $this->loadedSubitems
[$code] );
1072 unset( $this->initialisedLangs
[$code] );
1073 unset( $this->shallowFallbacks
[$code] );
1075 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1076 if ( $fbCode === $code ) {
1077 $this->unload( $shallowCode );
1085 public function unloadAll() {
1086 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1087 $this->unload( $lang );
1092 * Disable the storage backend
1094 public function disableBackend() {
1095 $this->store
= new LCStoreNull
;
1096 $this->manualRecache
= false;