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\Config\ServiceOptions
;
26 use MediaWiki\Languages\LanguageNameUtils
;
27 use Psr\Log\LoggerInterface
;
30 * Class for caching the contents of localisation files, Messages*.php
33 * An instance of this class is available using MediaWikiServices.
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 /** @var ServiceOptions */
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 * The cache data. 3-d array, where the first key is the language code,
56 * the second key is the item key e.g. 'messages', and the third key is
57 * an item specific subkey index. Some items are not arrays and so for those
58 * items, there are no subkeys.
63 * The persistent store object. An instance of LCStore.
70 * @var LoggerInterface
74 /** @var callable[] See comment for parameter in constructor */
75 private $clearStoreCallbacks;
77 /** @var LanguageNameUtils */
78 private $langNameUtils;
81 * A 2-d associative array, code/key, where presence indicates that the item
82 * is loaded. Value arbitrary.
84 * For split items, if set, this indicates that all of the subitems have been
87 private $loadedItems = [];
90 * A 3-d associative array, code/key/subkey, where presence indicates that
91 * the subitem is loaded. Only used for the split items, i.e. messages.
93 private $loadedSubitems = [];
96 * An array where presence of a key indicates that that language has been
97 * initialised. Initialisation includes checking for cache expiry and doing
98 * any necessary updates.
100 private $initialisedLangs = [];
103 * An array mapping non-existent pseudo-languages to fallback languages. This
104 * is filled by initShallowFallback() when data is requested from a language
105 * that lacks a Messages*.php file.
107 private $shallowFallbacks = [];
110 * An array where the keys are codes that have been recached by this instance.
112 private $recachedLangs = [];
117 public static $allKeys = [
118 'fallback', 'namespaceNames', 'bookstoreList',
119 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns',
120 'digitTransformTable', 'separatorTransformTable',
121 'minimumGroupingDigits', 'fallback8bitEncoding',
122 'linkPrefixExtension', 'linkTrail', 'linkPrefixCharset',
123 'namespaceAliases', 'dateFormats', 'datePreferences',
124 'datePreferenceMigrationMap', 'defaultDateFormat',
125 'specialPageAliases', 'imageFiles', 'preloadedMessages',
126 'namespaceGenderAliases', 'digitGroupingPattern', 'pluralRules',
127 'pluralRuleTypes', 'compiledPluralRules',
131 * Keys for items which consist of associative arrays, which may be merged
132 * by a fallback sequence.
134 public static $mergeableMapKeys = [ 'messages', 'namespaceNames',
135 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
139 * Keys for items which are a numbered array.
141 public static $mergeableListKeys = [];
144 * Keys for items which contain an array of arrays of equivalent aliases
145 * for each subitem. The aliases may be merged by a fallback sequence.
147 public static $mergeableAliasListKeys = [ 'specialPageAliases' ];
150 * Keys for items which contain an associative array, and may be merged if
151 * the primary value contains the special array key "inherit". That array
152 * key is removed after the first merge.
154 public static $optionalMergeKeys = [ 'bookstoreList' ];
157 * Keys for items that are formatted like $magicWords
159 public static $magicWordKeys = [ 'magicWords' ];
162 * Keys for items where the subitems are stored in the backend separately.
164 public static $splitKeys = [ 'messages' ];
167 * Keys which are loaded automatically by initLanguage()
169 public static $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
172 * Associative array of cached plural rules. The key is the language code,
173 * the value is an array of plural rules for that language.
175 private $pluralRules = null;
178 * Associative array of cached plural rule types. The key is the language
179 * code, the value is an array of plural rule types for that language. For
180 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
181 * The index for each rule type matches the index for the rule in
182 * $pluralRules, thus allowing correlation between the two. The reason we
183 * don't just use the type names as the keys in $pluralRules is because
184 * Language::convertPlural applies the rules based on numeric order (or
185 * explicit numeric parameter), not based on the name of the rule type. For
186 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
187 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
189 private $pluralRuleTypes = null;
191 private $mergeableKeys = null;
194 * @todo Make this a const when HHVM support is dropped (T192166)
199 public static $constructorOptions = [
200 // True to treat all files as expired until they are regenerated by this object.
203 'ExtensionMessagesFiles',
208 * For constructor parameters, see the documentation in DefaultSettings.php
209 * for $wgLocalisationCacheConf.
211 * Do not construct this directly. Use MediaWikiServices.
213 * @param ServiceOptions $options
214 * @param LCStore $store What backend to use for storage
215 * @param LoggerInterface $logger
216 * @param callable[] $clearStoreCallbacks To be called whenever the cache is cleared. Can be
217 * used to clear other caches that depend on this one, such as ResourceLoader's
219 * @param LanguageNameUtils $langNameUtils
220 * @throws MWException
222 function __construct(
223 ServiceOptions
$options,
225 LoggerInterface
$logger,
226 array $clearStoreCallbacks,
227 LanguageNameUtils
$langNameUtils
229 $options->assertRequiredOptions( self
::$constructorOptions );
231 $this->options
= $options;
232 $this->store
= $store;
233 $this->logger
= $logger;
234 $this->clearStoreCallbacks
= $clearStoreCallbacks;
235 $this->langNameUtils
= $langNameUtils;
237 // Keep this separate from $this->options so it can be mutable
238 $this->manualRecache
= $options->get( 'manualRecache' );
242 * Returns true if the given key is mergeable, that is, if it is an associative
243 * array which can be merged through a fallback sequence.
247 public function isMergeableKey( $key ) {
248 if ( $this->mergeableKeys
=== null ) {
249 $this->mergeableKeys
= array_flip( array_merge(
250 self
::$mergeableMapKeys,
251 self
::$mergeableListKeys,
252 self
::$mergeableAliasListKeys,
253 self
::$optionalMergeKeys,
258 return isset( $this->mergeableKeys
[$key] );
264 * Warning: this may be slow for split items (messages), since it will
265 * need to fetch all of the subitems from the cache individually.
266 * @param string $code
270 public function getItem( $code, $key ) {
271 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
272 $this->loadItem( $code, $key );
275 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
276 return $this->shallowFallbacks
[$code];
279 return $this->data
[$code][$key];
283 * Get a subitem, for instance a single message for a given language.
284 * @param string $code
286 * @param string $subkey
289 public function getSubitem( $code, $key, $subkey ) {
290 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
291 !isset( $this->loadedItems
[$code][$key] )
293 $this->loadSubitem( $code, $key, $subkey );
296 return $this->data
[$code][$key][$subkey] ??
null;
300 * Get the list of subitem keys for a given item.
302 * This is faster than array_keys($lc->getItem(...)) for the items listed in
305 * Will return null if the item is not found, or false if the item is not an
307 * @param string $code
309 * @return bool|null|string|string[]
311 public function getSubitemList( $code, $key ) {
312 if ( in_array( $key, self
::$splitKeys ) ) {
313 return $this->getSubitem( $code, 'list', $key );
315 $item = $this->getItem( $code, $key );
316 if ( is_array( $item ) ) {
317 return array_keys( $item );
325 * Load an item into the cache.
326 * @param string $code
329 protected function loadItem( $code, $key ) {
330 if ( !isset( $this->initialisedLangs
[$code] ) ) {
331 $this->initLanguage( $code );
334 // Check to see if initLanguage() loaded it for us
335 if ( isset( $this->loadedItems
[$code][$key] ) ) {
339 if ( isset( $this->shallowFallbacks
[$code] ) ) {
340 $this->loadItem( $this->shallowFallbacks
[$code], $key );
345 if ( in_array( $key, self
::$splitKeys ) ) {
346 $subkeyList = $this->getSubitem( $code, 'list', $key );
347 foreach ( $subkeyList as $subkey ) {
348 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
351 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
354 $this->data
[$code][$key] = $this->store
->get( $code, $key );
357 $this->loadedItems
[$code][$key] = true;
361 * Load a subitem into the cache
362 * @param string $code
364 * @param string $subkey
366 protected function loadSubitem( $code, $key, $subkey ) {
367 if ( !in_array( $key, self
::$splitKeys ) ) {
368 $this->loadItem( $code, $key );
373 if ( !isset( $this->initialisedLangs
[$code] ) ) {
374 $this->initLanguage( $code );
377 // Check to see if initLanguage() loaded it for us
378 if ( isset( $this->loadedItems
[$code][$key] ) ||
379 isset( $this->loadedSubitems
[$code][$key][$subkey] )
384 if ( isset( $this->shallowFallbacks
[$code] ) ) {
385 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
390 $value = $this->store
->get( $code, "$key:$subkey" );
391 $this->data
[$code][$key][$subkey] = $value;
392 $this->loadedSubitems
[$code][$key][$subkey] = true;
396 * Returns true if the cache identified by $code is missing or expired.
398 * @param string $code
402 public function isExpired( $code ) {
403 if ( $this->options
->get( 'forceRecache' ) && !isset( $this->recachedLangs
[$code] ) ) {
404 $this->logger
->debug( __METHOD__
. "($code): forced reload" );
409 $deps = $this->store
->get( $code, 'deps' );
410 $keys = $this->store
->get( $code, 'list' );
411 $preload = $this->store
->get( $code, 'preload' );
412 // Different keys may expire separately for some stores
413 if ( $deps === null ||
$keys === null ||
$preload === null ) {
414 $this->logger
->debug( __METHOD__
. "($code): cache missing, need to make one" );
419 foreach ( $deps as $dep ) {
420 // Because we're unserializing stuff from cache, we
421 // could receive objects of classes that don't exist
422 // anymore (e.g. uninstalled extensions)
423 // When this happens, always expire the cache
424 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
425 $this->logger
->debug( __METHOD__
. "($code): cache for $code expired due to " .
436 * Initialise a language in this object. Rebuild the cache if necessary.
437 * @param string $code
438 * @throws MWException
440 protected function initLanguage( $code ) {
441 if ( isset( $this->initialisedLangs
[$code] ) ) {
445 $this->initialisedLangs
[$code] = true;
447 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
448 if ( !$this->langNameUtils
->isValidBuiltInCode( $code ) ) {
449 $this->initShallowFallback( $code, 'en' );
454 # Recache the data if necessary
455 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
456 if ( $this->langNameUtils
->isSupportedLanguage( $code ) ) {
457 $this->recache( $code );
458 } elseif ( $code === 'en' ) {
459 throw new MWException( 'MessagesEn.php is missing.' );
461 $this->initShallowFallback( $code, 'en' );
468 $preload = $this->getItem( $code, 'preload' );
469 if ( $preload === null ) {
470 if ( $this->manualRecache
) {
471 // No Messages*.php file. Do shallow fallback to en.
472 if ( $code === 'en' ) {
473 throw new MWException( 'No localisation cache found for English. ' .
474 'Please run maintenance/rebuildLocalisationCache.php.' );
476 $this->initShallowFallback( $code, 'en' );
480 throw new MWException( 'Invalid or missing localisation cache.' );
483 $this->data
[$code] = $preload;
484 foreach ( $preload as $key => $item ) {
485 if ( in_array( $key, self
::$splitKeys ) ) {
486 foreach ( $item as $subkey => $subitem ) {
487 $this->loadedSubitems
[$code][$key][$subkey] = true;
490 $this->loadedItems
[$code][$key] = true;
496 * Create a fallback from one language to another, without creating a
497 * complete persistent cache.
498 * @param string $primaryCode
499 * @param string $fallbackCode
501 public function initShallowFallback( $primaryCode, $fallbackCode ) {
502 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
503 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
504 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
505 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
509 * Read a PHP file containing localisation data.
510 * @param string $_fileName
511 * @param string $_fileType
512 * @throws MWException
515 protected function readPHPFile( $_fileName, $_fileType ) {
516 // Disable APC caching
517 Wikimedia\
suppressWarnings();
518 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
519 Wikimedia\restoreWarnings
();
523 Wikimedia\
suppressWarnings();
524 ini_set( 'apc.cache_by_default', $_apcEnabled );
525 Wikimedia\restoreWarnings
();
528 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
529 foreach ( self
::$allKeys as $key ) {
530 // Not all keys are set in language files, so
531 // check they exist first
532 if ( isset( $
$key ) ) {
536 } elseif ( $_fileType == 'aliases' ) {
537 if ( isset( $aliases ) ) {
538 $data['aliases'] = $aliases;
541 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
548 * Read a JSON file containing localisation messages.
549 * @param string $fileName Name of file to read
550 * @throws MWException If there is a syntax error in the JSON file
551 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
553 public function readJSONFile( $fileName ) {
554 if ( !is_readable( $fileName ) ) {
558 $json = file_get_contents( $fileName );
559 if ( $json === false ) {
563 $data = FormatJson
::decode( $json, true );
564 if ( $data === null ) {
565 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
568 // Remove keys starting with '@', they're reserved for metadata and non-message data
569 foreach ( $data as $key => $unused ) {
570 if ( $key === '' ||
$key[0] === '@' ) {
571 unset( $data[$key] );
575 // The JSON format only supports messages, none of the other variables, so wrap the data
576 return [ 'messages' => $data ];
580 * Get the compiled plural rules for a given language from the XML files.
582 * @param string $code
585 public function getCompiledPluralRules( $code ) {
586 $rules = $this->getPluralRules( $code );
587 if ( $rules === null ) {
591 $compiledRules = Evaluator
::compile( $rules );
592 } catch ( CLDRPluralRuleError
$e ) {
593 $this->logger
->debug( $e->getMessage() );
598 return $compiledRules;
602 * Get the plural rules for a given language from the XML files.
605 * @param string $code
608 public function getPluralRules( $code ) {
609 if ( $this->pluralRules
=== null ) {
610 $this->loadPluralFiles();
612 return $this->pluralRules
[$code] ??
null;
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 return $this->pluralRuleTypes
[$code] ??
null;
630 * Load the plural XML files.
632 protected function loadPluralFiles() {
634 $cldrPlural = "$IP/languages/data/plurals.xml";
635 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
636 // Load CLDR plural rules
637 $this->loadPluralFile( $cldrPlural );
638 if ( file_exists( $mwPlural ) ) {
639 // Override or extend
640 $this->loadPluralFile( $mwPlural );
645 * Load a plural XML file with the given filename, compile the relevant
646 * rules, and save the compiled rules in a process-local cache.
648 * @param string $fileName
649 * @throws MWException
651 protected function loadPluralFile( $fileName ) {
652 // Use file_get_contents instead of DOMDocument::load (T58439)
653 $xml = file_get_contents( $fileName );
655 throw new MWException( "Unable to read plurals file $fileName" );
657 $doc = new DOMDocument
;
658 $doc->loadXML( $xml );
659 $rulesets = $doc->getElementsByTagName( "pluralRules" );
660 foreach ( $rulesets as $ruleset ) {
661 $codes = $ruleset->getAttribute( 'locales' );
664 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
665 foreach ( $ruleElements as $elt ) {
666 $ruleType = $elt->getAttribute( 'count' );
667 if ( $ruleType === 'other' ) {
668 // Don't record "other" rules, which have an empty condition
671 $rules[] = $elt->nodeValue
;
672 $ruleTypes[] = $ruleType;
674 foreach ( explode( ' ', $codes ) as $code ) {
675 $this->pluralRules
[$code] = $rules;
676 $this->pluralRuleTypes
[$code] = $ruleTypes;
682 * Read the data from the source files for a given language, and register
683 * the relevant dependencies in the $deps array. If the localisation
684 * exists, the data array is returned, otherwise false is returned.
686 * @param string $code
687 * @param array &$deps
690 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
693 // This reads in the PHP i18n file with non-messages l10n data
694 $fileName = $this->langNameUtils
->getMessagesFileName( $code );
695 if ( !file_exists( $fileName ) ) {
698 $deps[] = new FileDependency( $fileName );
699 $data = $this->readPHPFile( $fileName, 'core' );
702 # Load CLDR plural rules for JavaScript
703 $data['pluralRules'] = $this->getPluralRules( $code );
705 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
706 # Load plural rule types
707 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
709 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
710 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
716 * Merge two localisation values, a primary and a fallback, overwriting the
717 * primary value in place.
719 * @param mixed &$value
720 * @param mixed $fallbackValue
722 protected function mergeItem( $key, &$value, $fallbackValue ) {
723 if ( !is_null( $value ) ) {
724 if ( !is_null( $fallbackValue ) ) {
725 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
726 $value = $value +
$fallbackValue;
727 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
728 $value = array_unique( array_merge( $fallbackValue, $value ) );
729 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
730 $value = array_merge_recursive( $value, $fallbackValue );
731 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
732 if ( !empty( $value['inherit'] ) ) {
733 $value = array_merge( $fallbackValue, $value );
736 if ( isset( $value['inherit'] ) ) {
737 unset( $value['inherit'] );
739 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
740 $this->mergeMagicWords( $value, $fallbackValue );
744 $value = $fallbackValue;
749 * @param mixed &$value
750 * @param mixed $fallbackValue
752 protected function mergeMagicWords( &$value, $fallbackValue ) {
753 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
754 if ( !isset( $value[$magicName] ) ) {
755 $value[$magicName] = $fallbackInfo;
757 $oldSynonyms = array_slice( $fallbackInfo, 1 );
758 $newSynonyms = array_slice( $value[$magicName], 1 );
759 $synonyms = array_values( array_unique( array_merge(
760 $newSynonyms, $oldSynonyms ) ) );
761 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
767 * Given an array mapping language code to localisation value, such as is
768 * found in extension *.i18n.php files, iterate through a fallback sequence
769 * to merge the given data with an existing primary value.
771 * Returns true if any data from the extension array was used, false
773 * @param array $codeSequence
775 * @param mixed &$value
776 * @param mixed $fallbackValue
779 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
781 foreach ( $codeSequence as $code ) {
782 if ( isset( $fallbackValue[$code] ) ) {
783 $this->mergeItem( $key, $value, $fallbackValue[$code] );
792 * Gets the combined list of messages dirs from
793 * core and extensions
798 public function getMessagesDirs() {
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",
806 ] +
$this->options
->get( 'MessagesDirs' );
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 ) {
817 throw new MWException( "Invalid language code requested" );
819 $this->recachedLangs
[$code] = true;
822 $initialData = array_fill_keys( self
::$allKeys, null );
823 $coreData = $initialData;
826 # Load the primary localisation from the source file
827 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
828 if ( $data === false ) {
829 $this->logger
->debug( __METHOD__
. ": no localisation file for $code, using fallback to en" );
830 $coreData['fallback'] = 'en';
832 $this->logger
->debug( __METHOD__
. ": got localisation for $code from source" );
834 # Merge primary localisation
835 foreach ( $data as $key => $value ) {
836 $this->mergeItem( $key, $coreData[$key], $value );
840 # Fill in the fallback if it's not there already
841 if ( ( is_null( $coreData['fallback'] ) ||
$coreData['fallback'] === false ) && $code === 'en' ) {
842 $coreData['fallback'] = false;
843 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
845 if ( !is_null( $coreData['fallback'] ) ) {
846 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
848 $coreData['fallbackSequence'] = [];
850 $len = count( $coreData['fallbackSequence'] );
852 # Before we add the 'en' fallback for messages, keep a copy of
853 # the original fallback sequence
854 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
856 # Ensure that the sequence ends at 'en' for messages
857 if ( !$len ||
$coreData['fallbackSequence'][$len - 1] !== 'en' ) {
858 $coreData['fallbackSequence'][] = 'en';
862 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
863 $messageDirs = $this->getMessagesDirs();
865 # Load non-JSON localisation data for extensions
866 $extensionData = array_fill_keys( $codeSequence, $initialData );
867 foreach ( $this->options
->get( 'ExtensionMessagesFiles' ) as $extension => $fileName ) {
868 if ( isset( $messageDirs[$extension] ) ) {
869 # This extension has JSON message data; skip the PHP shim
873 $data = $this->readPHPFile( $fileName, 'extension' );
876 foreach ( $data as $key => $item ) {
877 foreach ( $codeSequence as $csCode ) {
878 if ( isset( $item[$csCode] ) ) {
879 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
886 $deps[] = new FileDependency( $fileName );
890 # Load the localisation data for each fallback, then merge it into the full array
891 $allData = $initialData;
892 foreach ( $codeSequence as $csCode ) {
893 $csData = $initialData;
895 # Load core messages and the extension localisations.
896 foreach ( $messageDirs as $dirs ) {
897 foreach ( (array)$dirs as $dir ) {
898 $fileName = "$dir/$csCode.json";
899 $data = $this->readJSONFile( $fileName );
901 foreach ( $data as $key => $item ) {
902 $this->mergeItem( $key, $csData[$key], $item );
905 $deps[] = new FileDependency( $fileName );
909 # Merge non-JSON extension data
910 if ( isset( $extensionData[$csCode] ) ) {
911 foreach ( $extensionData[$csCode] as $key => $item ) {
912 $this->mergeItem( $key, $csData[$key], $item );
916 if ( $csCode === $code ) {
917 # Merge core data into extension data
918 foreach ( $coreData as $key => $item ) {
919 $this->mergeItem( $key, $csData[$key], $item );
922 # Load the secondary localisation from the source file to
923 # avoid infinite cycles on cyclic fallbacks
924 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
925 if ( $fbData !== false ) {
926 # Only merge the keys that make sense to merge
927 foreach ( self
::$allKeys as $key ) {
928 if ( !isset( $fbData[$key] ) ) {
932 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
933 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
939 # Allow extensions an opportunity to adjust the data for this
941 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
943 # Merge the data for this fallback into the final array
944 if ( $csCode === $code ) {
947 foreach ( self
::$allKeys as $key ) {
948 if ( !isset( $csData[$key] ) ) {
952 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
953 $this->mergeItem( $key, $allData[$key], $csData[$key] );
959 # Add cache dependencies for any referenced globals
960 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
961 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
962 // We use the key 'wgMessagesDirs' for historical reasons.
963 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
964 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
966 # Add dependencies to the cache entry
967 $allData['deps'] = $deps;
969 # Replace spaces with underscores in namespace names
970 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
972 # And do the same for special page aliases. $page is an array.
973 foreach ( $allData['specialPageAliases'] as &$page ) {
974 $page = str_replace( ' ', '_', $page );
976 # Decouple the reference to prevent accidental damage
979 # If there were no plural rules, return an empty array
980 if ( $allData['pluralRules'] === null ) {
981 $allData['pluralRules'] = [];
983 if ( $allData['compiledPluralRules'] === null ) {
984 $allData['compiledPluralRules'] = [];
986 # If there were no plural rule types, return an empty array
987 if ( $allData['pluralRuleTypes'] === null ) {
988 $allData['pluralRuleTypes'] = [];
992 $allData['list'] = [];
993 foreach ( self
::$splitKeys as $key ) {
994 $allData['list'][$key] = array_keys( $allData[$key] );
997 $unused = true; // Used to be $purgeBlobs, removed in 1.34
998 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$unused ] );
1000 if ( is_null( $allData['namespaceNames'] ) ) {
1001 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
1002 'Check that your languages/messages/MessagesEn.php file is intact.' );
1005 # Set the preload key
1006 $allData['preload'] = $this->buildPreload( $allData );
1008 # Save to the process cache and register the items loaded
1009 $this->data
[$code] = $allData;
1010 foreach ( $allData as $key => $item ) {
1011 $this->loadedItems
[$code][$key] = true;
1014 # Save to the persistent cache
1015 $this->store
->startWrite( $code );
1016 foreach ( $allData as $key => $value ) {
1017 if ( in_array( $key, self
::$splitKeys ) ) {
1018 foreach ( $value as $subkey => $subvalue ) {
1019 $this->store
->set( "$key:$subkey", $subvalue );
1022 $this->store
->set( $key, $value );
1025 $this->store
->finishWrite();
1027 # Clear out the MessageBlobStore
1028 # HACK: If using a null (i.e. disabled) storage backend, we
1029 # can't write to the MessageBlobStore either
1030 if ( !$this->store
instanceof LCStoreNull
) {
1031 foreach ( $this->clearStoreCallbacks
as $callback ) {
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 $subitem = $data['messages'][$subkey] ??
null;
1053 $preload['messages'][$subkey] = $subitem;
1060 * Unload the data for a given language from the object cache.
1061 * Reduces memory usage.
1062 * @param string $code
1064 public function unload( $code ) {
1065 unset( $this->data
[$code] );
1066 unset( $this->loadedItems
[$code] );
1067 unset( $this->loadedSubitems
[$code] );
1068 unset( $this->initialisedLangs
[$code] );
1069 unset( $this->shallowFallbacks
[$code] );
1071 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1072 if ( $fbCode === $code ) {
1073 $this->unload( $shallowCode );
1081 public function unloadAll() {
1082 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1083 $this->unload( $lang );
1088 * Disable the storage backend
1090 public function disableBackend() {
1091 $this->store
= new LCStoreNull
;
1092 $this->manualRecache
= false;