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;
206 $storeConf['server'] = $conf['storeServer'] ??
[];
209 $storeClass = LCStoreStaticArray
::class;
212 if ( !empty( $conf['storeDirectory'] ) ) {
213 $storeClass = LCStoreCDB
::class;
214 } elseif ( $wgCacheDirectory ) {
215 $storeConf['directory'] = $wgCacheDirectory;
216 $storeClass = LCStoreCDB
::class;
218 $storeClass = LCStoreDB
::class;
219 $storeConf['server'] = $conf['storeServer'] ??
[];
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 return $this->data
[$code][$key][$subkey] ??
null;
301 * Get the list of subitem keys for a given item.
303 * This is faster than array_keys($lc->getItem(...)) for the items listed in
306 * Will return null if the item is not found, or false if the item is not an
308 * @param string $code
310 * @return bool|null|string|string[]
312 public function getSubitemList( $code, $key ) {
313 if ( in_array( $key, self
::$splitKeys ) ) {
314 return $this->getSubitem( $code, 'list', $key );
316 $item = $this->getItem( $code, $key );
317 if ( is_array( $item ) ) {
318 return array_keys( $item );
326 * Load an item into the cache.
327 * @param string $code
330 protected function loadItem( $code, $key ) {
331 if ( !isset( $this->initialisedLangs
[$code] ) ) {
332 $this->initLanguage( $code );
335 // Check to see if initLanguage() loaded it for us
336 if ( isset( $this->loadedItems
[$code][$key] ) ) {
340 if ( isset( $this->shallowFallbacks
[$code] ) ) {
341 $this->loadItem( $this->shallowFallbacks
[$code], $key );
346 if ( in_array( $key, self
::$splitKeys ) ) {
347 $subkeyList = $this->getSubitem( $code, 'list', $key );
348 foreach ( $subkeyList as $subkey ) {
349 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
352 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
355 $this->data
[$code][$key] = $this->store
->get( $code, $key );
358 $this->loadedItems
[$code][$key] = true;
362 * Load a subitem into the cache
363 * @param string $code
365 * @param string $subkey
367 protected function loadSubitem( $code, $key, $subkey ) {
368 if ( !in_array( $key, self
::$splitKeys ) ) {
369 $this->loadItem( $code, $key );
374 if ( !isset( $this->initialisedLangs
[$code] ) ) {
375 $this->initLanguage( $code );
378 // Check to see if initLanguage() loaded it for us
379 if ( isset( $this->loadedItems
[$code][$key] ) ||
380 isset( $this->loadedSubitems
[$code][$key][$subkey] )
385 if ( isset( $this->shallowFallbacks
[$code] ) ) {
386 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
391 $value = $this->store
->get( $code, "$key:$subkey" );
392 $this->data
[$code][$key][$subkey] = $value;
393 $this->loadedSubitems
[$code][$key][$subkey] = true;
397 * Returns true if the cache identified by $code is missing or expired.
399 * @param string $code
403 public function isExpired( $code ) {
404 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
405 wfDebug( __METHOD__
. "($code): forced reload\n" );
410 $deps = $this->store
->get( $code, 'deps' );
411 $keys = $this->store
->get( $code, 'list' );
412 $preload = $this->store
->get( $code, 'preload' );
413 // Different keys may expire separately for some stores
414 if ( $deps === null ||
$keys === null ||
$preload === null ) {
415 wfDebug( __METHOD__
. "($code): cache missing, need to make one\n" );
420 foreach ( $deps as $dep ) {
421 // Because we're unserializing stuff from cache, we
422 // could receive objects of classes that don't exist
423 // anymore (e.g. uninstalled extensions)
424 // When this happens, always expire the cache
425 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
426 wfDebug( __METHOD__
. "($code): cache for $code expired due to " .
427 get_class( $dep ) . "\n" );
437 * Initialise a language in this object. Rebuild the cache if necessary.
438 * @param string $code
439 * @throws MWException
441 protected function initLanguage( $code ) {
442 if ( isset( $this->initialisedLangs
[$code] ) ) {
446 $this->initialisedLangs
[$code] = true;
448 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
449 if ( !Language
::isValidBuiltInCode( $code ) ) {
450 $this->initShallowFallback( $code, 'en' );
455 # Recache the data if necessary
456 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
457 if ( Language
::isSupportedLanguage( $code ) ) {
458 $this->recache( $code );
459 } elseif ( $code === 'en' ) {
460 throw new MWException( 'MessagesEn.php is missing.' );
462 $this->initShallowFallback( $code, 'en' );
469 $preload = $this->getItem( $code, 'preload' );
470 if ( $preload === null ) {
471 if ( $this->manualRecache
) {
472 // No Messages*.php file. Do shallow fallback to en.
473 if ( $code === 'en' ) {
474 throw new MWException( 'No localisation cache found for English. ' .
475 'Please run maintenance/rebuildLocalisationCache.php.' );
477 $this->initShallowFallback( $code, 'en' );
481 throw new MWException( 'Invalid or missing localisation cache.' );
484 $this->data
[$code] = $preload;
485 foreach ( $preload as $key => $item ) {
486 if ( in_array( $key, self
::$splitKeys ) ) {
487 foreach ( $item as $subkey => $subitem ) {
488 $this->loadedSubitems
[$code][$key][$subkey] = true;
491 $this->loadedItems
[$code][$key] = true;
497 * Create a fallback from one language to another, without creating a
498 * complete persistent cache.
499 * @param string $primaryCode
500 * @param string $fallbackCode
502 public function initShallowFallback( $primaryCode, $fallbackCode ) {
503 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
504 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
505 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
506 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
510 * Read a PHP file containing localisation data.
511 * @param string $_fileName
512 * @param string $_fileType
513 * @throws MWException
516 protected function readPHPFile( $_fileName, $_fileType ) {
517 // Disable APC caching
518 Wikimedia\
suppressWarnings();
519 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
520 Wikimedia\restoreWarnings
();
524 Wikimedia\
suppressWarnings();
525 ini_set( 'apc.cache_by_default', $_apcEnabled );
526 Wikimedia\restoreWarnings
();
529 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
530 foreach ( self
::$allKeys as $key ) {
531 // Not all keys are set in language files, so
532 // check they exist first
533 if ( isset( $
$key ) ) {
537 } elseif ( $_fileType == 'aliases' ) {
538 if ( isset( $aliases ) ) {
539 /** @suppress PhanUndeclaredVariable */
540 $data['aliases'] = $aliases;
543 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
550 * Read a JSON file containing localisation messages.
551 * @param string $fileName Name of file to read
552 * @throws MWException If there is a syntax error in the JSON file
553 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
555 public function readJSONFile( $fileName ) {
556 if ( !is_readable( $fileName ) ) {
560 $json = file_get_contents( $fileName );
561 if ( $json === false ) {
565 $data = FormatJson
::decode( $json, true );
566 if ( $data === null ) {
567 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
570 // Remove keys starting with '@', they're reserved for metadata and non-message data
571 foreach ( $data as $key => $unused ) {
572 if ( $key === '' ||
$key[0] === '@' ) {
573 unset( $data[$key] );
577 // The JSON format only supports messages, none of the other variables, so wrap the data
578 return [ 'messages' => $data ];
582 * Get the compiled plural rules for a given language from the XML files.
584 * @param string $code
587 public function getCompiledPluralRules( $code ) {
588 $rules = $this->getPluralRules( $code );
589 if ( $rules === null ) {
593 $compiledRules = Evaluator
::compile( $rules );
594 } catch ( CLDRPluralRuleError
$e ) {
595 wfDebugLog( 'l10n', $e->getMessage() );
600 return $compiledRules;
604 * Get the plural rules for a given language from the XML files.
607 * @param string $code
610 public function getPluralRules( $code ) {
611 if ( $this->pluralRules
=== null ) {
612 $this->loadPluralFiles();
614 return $this->pluralRules
[$code] ??
null;
618 * Get the plural rule types for a given language from the XML files.
621 * @param string $code
624 public function getPluralRuleTypes( $code ) {
625 if ( $this->pluralRuleTypes
=== null ) {
626 $this->loadPluralFiles();
628 return $this->pluralRuleTypes
[$code] ??
null;
632 * Load the plural XML files.
634 protected function loadPluralFiles() {
636 $cldrPlural = "$IP/languages/data/plurals.xml";
637 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
638 // Load CLDR plural rules
639 $this->loadPluralFile( $cldrPlural );
640 if ( file_exists( $mwPlural ) ) {
641 // Override or extend
642 $this->loadPluralFile( $mwPlural );
647 * Load a plural XML file with the given filename, compile the relevant
648 * rules, and save the compiled rules in a process-local cache.
650 * @param string $fileName
651 * @throws MWException
653 protected function loadPluralFile( $fileName ) {
654 // Use file_get_contents instead of DOMDocument::load (T58439)
655 $xml = file_get_contents( $fileName );
657 throw new MWException( "Unable to read plurals file $fileName" );
659 $doc = new DOMDocument
;
660 $doc->loadXML( $xml );
661 $rulesets = $doc->getElementsByTagName( "pluralRules" );
662 foreach ( $rulesets as $ruleset ) {
663 $codes = $ruleset->getAttribute( 'locales' );
666 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
667 foreach ( $ruleElements as $elt ) {
668 $ruleType = $elt->getAttribute( 'count' );
669 if ( $ruleType === 'other' ) {
670 // Don't record "other" rules, which have an empty condition
673 $rules[] = $elt->nodeValue
;
674 $ruleTypes[] = $ruleType;
676 foreach ( explode( ' ', $codes ) as $code ) {
677 $this->pluralRules
[$code] = $rules;
678 $this->pluralRuleTypes
[$code] = $ruleTypes;
684 * Read the data from the source files for a given language, and register
685 * the relevant dependencies in the $deps array. If the localisation
686 * exists, the data array is returned, otherwise false is returned.
688 * @param string $code
689 * @param array &$deps
692 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
695 // This reads in the PHP i18n file with non-messages l10n data
696 $fileName = Language
::getMessagesFileName( $code );
697 if ( !file_exists( $fileName ) ) {
700 $deps[] = new FileDependency( $fileName );
701 $data = $this->readPHPFile( $fileName, 'core' );
704 # Load CLDR plural rules for JavaScript
705 $data['pluralRules'] = $this->getPluralRules( $code );
707 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
708 # Load plural rule types
709 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
711 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
712 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
718 * Merge two localisation values, a primary and a fallback, overwriting the
719 * primary value in place.
721 * @param mixed &$value
722 * @param mixed $fallbackValue
724 protected function mergeItem( $key, &$value, $fallbackValue ) {
725 if ( !is_null( $value ) ) {
726 if ( !is_null( $fallbackValue ) ) {
727 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
728 $value = $value +
$fallbackValue;
729 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
730 $value = array_unique( array_merge( $fallbackValue, $value ) );
731 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
732 $value = array_merge_recursive( $value, $fallbackValue );
733 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
734 if ( !empty( $value['inherit'] ) ) {
735 $value = array_merge( $fallbackValue, $value );
738 if ( isset( $value['inherit'] ) ) {
739 unset( $value['inherit'] );
741 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
742 $this->mergeMagicWords( $value, $fallbackValue );
746 $value = $fallbackValue;
751 * @param mixed &$value
752 * @param mixed $fallbackValue
754 protected function mergeMagicWords( &$value, $fallbackValue ) {
755 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
756 if ( !isset( $value[$magicName] ) ) {
757 $value[$magicName] = $fallbackInfo;
759 $oldSynonyms = array_slice( $fallbackInfo, 1 );
760 $newSynonyms = array_slice( $value[$magicName], 1 );
761 $synonyms = array_values( array_unique( array_merge(
762 $newSynonyms, $oldSynonyms ) ) );
763 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
769 * Given an array mapping language code to localisation value, such as is
770 * found in extension *.i18n.php files, iterate through a fallback sequence
771 * to merge the given data with an existing primary value.
773 * Returns true if any data from the extension array was used, false
775 * @param array $codeSequence
777 * @param mixed &$value
778 * @param mixed $fallbackValue
781 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
783 foreach ( $codeSequence as $code ) {
784 if ( isset( $fallbackValue[$code] ) ) {
785 $this->mergeItem( $key, $value, $fallbackValue[$code] );
794 * Gets the combined list of messages dirs from
795 * core and extensions
800 public function getMessagesDirs() {
803 $config = MediaWikiServices
::getInstance()->getMainConfig();
804 $messagesDirs = $config->get( 'MessagesDirs' );
806 'core' => "$IP/languages/i18n",
807 'exif' => "$IP/languages/i18n/exif",
808 'api' => "$IP/includes/api/i18n",
809 'oojs-ui' => "$IP/resources/lib/ooui/i18n",
814 * Load localisation data for a given language for both core and extensions
815 * and save it to the persistent cache store and the process cache
816 * @param string $code
817 * @throws MWException
819 public function recache( $code ) {
820 global $wgExtensionMessagesFiles;
823 throw new MWException( "Invalid language code requested" );
825 $this->recachedLangs
[$code] = true;
828 $initialData = array_fill_keys( self
::$allKeys, null );
829 $coreData = $initialData;
832 # Load the primary localisation from the source file
833 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
834 if ( $data === false ) {
835 wfDebug( __METHOD__
. ": no localisation file for $code, using fallback to en\n" );
836 $coreData['fallback'] = 'en';
838 wfDebug( __METHOD__
. ": got localisation for $code from source\n" );
840 # Merge primary localisation
841 foreach ( $data as $key => $value ) {
842 $this->mergeItem( $key, $coreData[$key], $value );
846 # Fill in the fallback if it's not there already
847 if ( ( is_null( $coreData['fallback'] ) ||
$coreData['fallback'] === false ) && $code === 'en' ) {
848 $coreData['fallback'] = false;
849 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
851 if ( !is_null( $coreData['fallback'] ) ) {
852 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
854 $coreData['fallbackSequence'] = [];
856 $len = count( $coreData['fallbackSequence'] );
858 # Before we add the 'en' fallback for messages, keep a copy of
859 # the original fallback sequence
860 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
862 # Ensure that the sequence ends at 'en' for messages
863 if ( !$len ||
$coreData['fallbackSequence'][$len - 1] !== 'en' ) {
864 $coreData['fallbackSequence'][] = 'en';
868 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
869 $messageDirs = $this->getMessagesDirs();
871 # Load non-JSON localisation data for extensions
872 $extensionData = array_fill_keys( $codeSequence, $initialData );
873 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
874 if ( isset( $messageDirs[$extension] ) ) {
875 # This extension has JSON message data; skip the PHP shim
879 $data = $this->readPHPFile( $fileName, 'extension' );
882 foreach ( $data as $key => $item ) {
883 foreach ( $codeSequence as $csCode ) {
884 if ( isset( $item[$csCode] ) ) {
885 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
892 $deps[] = new FileDependency( $fileName );
896 # Load the localisation data for each fallback, then merge it into the full array
897 $allData = $initialData;
898 foreach ( $codeSequence as $csCode ) {
899 $csData = $initialData;
901 # Load core messages and the extension localisations.
902 foreach ( $messageDirs as $dirs ) {
903 foreach ( (array)$dirs as $dir ) {
904 $fileName = "$dir/$csCode.json";
905 $data = $this->readJSONFile( $fileName );
907 foreach ( $data as $key => $item ) {
908 $this->mergeItem( $key, $csData[$key], $item );
911 $deps[] = new FileDependency( $fileName );
915 # Merge non-JSON extension data
916 if ( isset( $extensionData[$csCode] ) ) {
917 foreach ( $extensionData[$csCode] as $key => $item ) {
918 $this->mergeItem( $key, $csData[$key], $item );
922 if ( $csCode === $code ) {
923 # Merge core data into extension data
924 foreach ( $coreData as $key => $item ) {
925 $this->mergeItem( $key, $csData[$key], $item );
928 # Load the secondary localisation from the source file to
929 # avoid infinite cycles on cyclic fallbacks
930 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
931 if ( $fbData !== false ) {
932 # Only merge the keys that make sense to merge
933 foreach ( self
::$allKeys as $key ) {
934 if ( !isset( $fbData[$key] ) ) {
938 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
939 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
945 # Allow extensions an opportunity to adjust the data for this
947 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
949 # Merge the data for this fallback into the final array
950 if ( $csCode === $code ) {
953 foreach ( self
::$allKeys as $key ) {
954 if ( !isset( $csData[$key] ) ) {
958 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
959 $this->mergeItem( $key, $allData[$key], $csData[$key] );
965 # Add cache dependencies for any referenced globals
966 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
967 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
968 // We use the key 'wgMessagesDirs' for historical reasons.
969 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
970 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
972 # Add dependencies to the cache entry
973 $allData['deps'] = $deps;
975 # Replace spaces with underscores in namespace names
976 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
978 # And do the same for special page aliases. $page is an array.
979 foreach ( $allData['specialPageAliases'] as &$page ) {
980 $page = str_replace( ' ', '_', $page );
982 # Decouple the reference to prevent accidental damage
985 # If there were no plural rules, return an empty array
986 if ( $allData['pluralRules'] === null ) {
987 $allData['pluralRules'] = [];
989 if ( $allData['compiledPluralRules'] === null ) {
990 $allData['compiledPluralRules'] = [];
992 # If there were no plural rule types, return an empty array
993 if ( $allData['pluralRuleTypes'] === null ) {
994 $allData['pluralRuleTypes'] = [];
998 $allData['list'] = [];
999 foreach ( self
::$splitKeys as $key ) {
1000 $allData['list'][$key] = array_keys( $allData[$key] );
1004 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$purgeBlobs ] );
1006 if ( is_null( $allData['namespaceNames'] ) ) {
1007 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
1008 'Check that your languages/messages/MessagesEn.php file is intact.' );
1011 # Set the preload key
1012 $allData['preload'] = $this->buildPreload( $allData );
1014 # Save to the process cache and register the items loaded
1015 $this->data
[$code] = $allData;
1016 foreach ( $allData as $key => $item ) {
1017 $this->loadedItems
[$code][$key] = true;
1020 # Save to the persistent cache
1021 $this->store
->startWrite( $code );
1022 foreach ( $allData as $key => $value ) {
1023 if ( in_array( $key, self
::$splitKeys ) ) {
1024 foreach ( $value as $subkey => $subvalue ) {
1025 $this->store
->set( "$key:$subkey", $subvalue );
1028 $this->store
->set( $key, $value );
1031 $this->store
->finishWrite();
1033 # Clear out the MessageBlobStore
1034 # HACK: If using a null (i.e. disabled) storage backend, we
1035 # can't write to the MessageBlobStore either
1036 if ( $purgeBlobs && !$this->store
instanceof LCStoreNull
) {
1037 $blobStore = new MessageBlobStore();
1038 $blobStore->clear();
1043 * Build the preload item from the given pre-cache data.
1045 * The preload item will be loaded automatically, improving performance
1046 * for the commonly-requested items it contains.
1047 * @param array $data
1050 protected function buildPreload( $data ) {
1051 $preload = [ 'messages' => [] ];
1052 foreach ( self
::$preloadedKeys as $key ) {
1053 $preload[$key] = $data[$key];
1056 foreach ( $data['preloadedMessages'] as $subkey ) {
1057 $subitem = $data['messages'][$subkey] ??
null;
1058 $preload['messages'][$subkey] = $subitem;
1065 * Unload the data for a given language from the object cache.
1066 * Reduces memory usage.
1067 * @param string $code
1069 public function unload( $code ) {
1070 unset( $this->data
[$code] );
1071 unset( $this->loadedItems
[$code] );
1072 unset( $this->loadedSubitems
[$code] );
1073 unset( $this->initialisedLangs
[$code] );
1074 unset( $this->shallowFallbacks
[$code] );
1076 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1077 if ( $fbCode === $code ) {
1078 $this->unload( $shallowCode );
1086 public function unloadAll() {
1087 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1088 $this->unload( $lang );
1093 * Disable the storage backend
1095 public function disableBackend() {
1096 $this->store
= new LCStoreNull
;
1097 $this->manualRecache
= false;