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 Psr\Log\LoggerInterface
;
29 * Class for caching the contents of localisation files, Messages*.php
32 * An instance of this class is available using MediaWikiServices.
34 * The values retrieved from here are merged, containing items from extension
35 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
36 * zh-hans -> en ). Some common errors are corrected, for example namespace
37 * names with spaces instead of underscores, but heavyweight processing, such
38 * as grammatical transformation, is done by the caller.
40 class LocalisationCache
{
43 /** @var ServiceOptions */
47 * True if recaching should only be done on an explicit call to recache().
48 * Setting this reduces the overhead of cache freshness checking, which
49 * requires doing a stat() for every extension i18n file.
51 private $manualRecache = false;
54 * The cache data. 3-d array, where the first key is the language code,
55 * the second key is the item key e.g. 'messages', and the third key is
56 * an item specific subkey index. Some items are not arrays and so for those
57 * items, there are no subkeys.
62 * The persistent store object. An instance of LCStore.
69 * @var LoggerInterface
73 /** @var callable[] See comment for parameter in constructor */
74 private $clearStoreCallbacks;
77 * A 2-d associative array, code/key, where presence indicates that the item
78 * is loaded. Value arbitrary.
80 * For split items, if set, this indicates that all of the subitems have been
84 private $loadedItems = [];
87 * A 3-d associative array, code/key/subkey, where presence indicates that
88 * the subitem is loaded. Only used for the split items, i.e. messages.
90 private $loadedSubitems = [];
93 * An array where presence of a key indicates that that language has been
94 * initialised. Initialisation includes checking for cache expiry and doing
95 * any necessary updates.
97 private $initialisedLangs = [];
100 * An array mapping non-existent pseudo-languages to fallback languages. This
101 * is filled by initShallowFallback() when data is requested from a language
102 * that lacks a Messages*.php file.
104 private $shallowFallbacks = [];
107 * An array where the keys are codes that have been recached by this instance.
109 private $recachedLangs = [];
114 public static $allKeys = [
115 'fallback', 'namespaceNames', 'bookstoreList',
116 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns',
117 'digitTransformTable', 'separatorTransformTable',
118 'minimumGroupingDigits', 'fallback8bitEncoding',
119 'linkPrefixExtension', 'linkTrail', 'linkPrefixCharset',
120 'namespaceAliases', 'dateFormats', 'datePreferences',
121 'datePreferenceMigrationMap', 'defaultDateFormat',
122 'specialPageAliases', 'imageFiles', 'preloadedMessages',
123 'namespaceGenderAliases', 'digitGroupingPattern', 'pluralRules',
124 'pluralRuleTypes', 'compiledPluralRules',
128 * Keys for items which consist of associative arrays, which may be merged
129 * by a fallback sequence.
131 public static $mergeableMapKeys = [ 'messages', 'namespaceNames',
132 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
136 * Keys for items which are a numbered array.
138 public static $mergeableListKeys = [];
141 * Keys for items which contain an array of arrays of equivalent aliases
142 * for each subitem. The aliases may be merged by a fallback sequence.
144 public static $mergeableAliasListKeys = [ 'specialPageAliases' ];
147 * Keys for items which contain an associative array, and may be merged if
148 * the primary value contains the special array key "inherit". That array
149 * key is removed after the first merge.
151 public static $optionalMergeKeys = [ 'bookstoreList' ];
154 * Keys for items that are formatted like $magicWords
156 public static $magicWordKeys = [ 'magicWords' ];
159 * Keys for items where the subitems are stored in the backend separately.
161 public static $splitKeys = [ 'messages' ];
164 * Keys which are loaded automatically by initLanguage()
166 public static $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
169 * Associative array of cached plural rules. The key is the language code,
170 * the value is an array of plural rules for that language.
172 private $pluralRules = null;
175 * Associative array of cached plural rule types. The key is the language
176 * code, the value is an array of plural rule types for that language. For
177 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
178 * The index for each rule type matches the index for the rule in
179 * $pluralRules, thus allowing correlation between the two. The reason we
180 * don't just use the type names as the keys in $pluralRules is because
181 * Language::convertPlural applies the rules based on numeric order (or
182 * explicit numeric parameter), not based on the name of the rule type. For
183 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
184 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
186 private $pluralRuleTypes = null;
188 private $mergeableKeys = null;
191 * Return a suitable LCStore as specified by the given configuration.
194 * @param array $conf In the format of $wgLocalisationCacheConf
195 * @param string|false|null $fallbackCacheDir In case 'storeDirectory' isn't specified
198 public static function getStoreFromConf( array $conf, $fallbackCacheDir ) : LCStore
{
200 $storeArg['directory'] =
201 $conf['storeDirectory'] ?
: $fallbackCacheDir;
203 if ( !empty( $conf['storeClass'] ) ) {
204 $storeClass = $conf['storeClass'];
205 } elseif ( $conf['store'] === 'files' ||
$conf['store'] === 'file' ||
206 ( $conf['store'] === 'detect' && $storeArg['directory'] )
208 $storeClass = LCStoreCDB
::class;
209 } elseif ( $conf['store'] === 'db' ||
$conf['store'] === 'detect' ) {
210 $storeClass = LCStoreDB
::class;
211 $storeArg['server'] = $conf['storeServer'] ??
[];
212 } elseif ( $conf['store'] === 'array' ) {
213 $storeClass = LCStoreStaticArray
::class;
215 throw new MWException(
216 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
220 return new $storeClass( $storeArg );
224 * @todo Make this a const when HHVM support is dropped (T192166)
229 public static $constructorOptions = [
230 // True to treat all files as expired until they are regenerated by this object.
233 'ExtensionMessagesFiles',
238 * For constructor parameters, see the documentation in DefaultSettings.php
239 * for $wgLocalisationCacheConf.
241 * Do not construct this directly. Use MediaWikiServices.
243 * @param ServiceOptions $options
244 * @param LCStore $store What backend to use for storage
245 * @param LoggerInterface $logger
246 * @param callable[] $clearStoreCallbacks To be called whenever the cache is cleared. Can be
247 * used to clear other caches that depend on this one, such as ResourceLoader's
249 * @throws MWException
251 function __construct(
252 ServiceOptions
$options,
254 LoggerInterface
$logger,
255 array $clearStoreCallbacks = []
257 $options->assertRequiredOptions( self
::$constructorOptions );
259 $this->options
= $options;
260 $this->store
= $store;
261 $this->logger
= $logger;
262 $this->clearStoreCallbacks
= $clearStoreCallbacks;
264 // Keep this separate from $this->options so it can be mutable
265 $this->manualRecache
= $options->get( 'manualRecache' );
269 * Returns true if the given key is mergeable, that is, if it is an associative
270 * array which can be merged through a fallback sequence.
274 public function isMergeableKey( $key ) {
275 if ( $this->mergeableKeys
=== null ) {
276 $this->mergeableKeys
= array_flip( array_merge(
277 self
::$mergeableMapKeys,
278 self
::$mergeableListKeys,
279 self
::$mergeableAliasListKeys,
280 self
::$optionalMergeKeys,
285 return isset( $this->mergeableKeys
[$key] );
291 * Warning: this may be slow for split items (messages), since it will
292 * need to fetch all of the subitems from the cache individually.
293 * @param string $code
297 public function getItem( $code, $key ) {
298 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
299 $this->loadItem( $code, $key );
302 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
303 return $this->shallowFallbacks
[$code];
306 return $this->data
[$code][$key];
310 * Get a subitem, for instance a single message for a given language.
311 * @param string $code
313 * @param string $subkey
316 public function getSubitem( $code, $key, $subkey ) {
317 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
318 !isset( $this->loadedItems
[$code][$key] )
320 $this->loadSubitem( $code, $key, $subkey );
323 return $this->data
[$code][$key][$subkey] ??
null;
327 * Get the list of subitem keys for a given item.
329 * This is faster than array_keys($lc->getItem(...)) for the items listed in
332 * Will return null if the item is not found, or false if the item is not an
334 * @param string $code
336 * @return bool|null|string|string[]
338 public function getSubitemList( $code, $key ) {
339 if ( in_array( $key, self
::$splitKeys ) ) {
340 return $this->getSubitem( $code, 'list', $key );
342 $item = $this->getItem( $code, $key );
343 if ( is_array( $item ) ) {
344 return array_keys( $item );
352 * Load an item into the cache.
353 * @param string $code
356 protected function loadItem( $code, $key ) {
357 if ( !isset( $this->initialisedLangs
[$code] ) ) {
358 $this->initLanguage( $code );
361 // Check to see if initLanguage() loaded it for us
362 if ( isset( $this->loadedItems
[$code][$key] ) ) {
366 if ( isset( $this->shallowFallbacks
[$code] ) ) {
367 $this->loadItem( $this->shallowFallbacks
[$code], $key );
372 if ( in_array( $key, self
::$splitKeys ) ) {
373 $subkeyList = $this->getSubitem( $code, 'list', $key );
374 foreach ( $subkeyList as $subkey ) {
375 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
378 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
381 $this->data
[$code][$key] = $this->store
->get( $code, $key );
384 $this->loadedItems
[$code][$key] = true;
388 * Load a subitem into the cache
389 * @param string $code
391 * @param string $subkey
393 protected function loadSubitem( $code, $key, $subkey ) {
394 if ( !in_array( $key, self
::$splitKeys ) ) {
395 $this->loadItem( $code, $key );
400 if ( !isset( $this->initialisedLangs
[$code] ) ) {
401 $this->initLanguage( $code );
404 // Check to see if initLanguage() loaded it for us
405 if ( isset( $this->loadedItems
[$code][$key] ) ||
406 isset( $this->loadedSubitems
[$code][$key][$subkey] )
411 if ( isset( $this->shallowFallbacks
[$code] ) ) {
412 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
417 $value = $this->store
->get( $code, "$key:$subkey" );
418 $this->data
[$code][$key][$subkey] = $value;
419 $this->loadedSubitems
[$code][$key][$subkey] = true;
423 * Returns true if the cache identified by $code is missing or expired.
425 * @param string $code
429 public function isExpired( $code ) {
430 if ( $this->options
->get( 'forceRecache' ) && !isset( $this->recachedLangs
[$code] ) ) {
431 $this->logger
->debug( __METHOD__
. "($code): forced reload" );
436 $deps = $this->store
->get( $code, 'deps' );
437 $keys = $this->store
->get( $code, 'list' );
438 $preload = $this->store
->get( $code, 'preload' );
439 // Different keys may expire separately for some stores
440 if ( $deps === null ||
$keys === null ||
$preload === null ) {
441 $this->logger
->debug( __METHOD__
. "($code): cache missing, need to make one" );
446 foreach ( $deps as $dep ) {
447 // Because we're unserializing stuff from cache, we
448 // could receive objects of classes that don't exist
449 // anymore (e.g. uninstalled extensions)
450 // When this happens, always expire the cache
451 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
452 $this->logger
->debug( __METHOD__
. "($code): cache for $code expired due to " .
463 * Initialise a language in this object. Rebuild the cache if necessary.
464 * @param string $code
465 * @throws MWException
467 protected function initLanguage( $code ) {
468 if ( isset( $this->initialisedLangs
[$code] ) ) {
472 $this->initialisedLangs
[$code] = true;
474 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
475 if ( !Language
::isValidBuiltInCode( $code ) ) {
476 $this->initShallowFallback( $code, 'en' );
481 # Recache the data if necessary
482 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
483 if ( Language
::isSupportedLanguage( $code ) ) {
484 $this->recache( $code );
485 } elseif ( $code === 'en' ) {
486 throw new MWException( 'MessagesEn.php is missing.' );
488 $this->initShallowFallback( $code, 'en' );
495 $preload = $this->getItem( $code, 'preload' );
496 if ( $preload === null ) {
497 if ( $this->manualRecache
) {
498 // No Messages*.php file. Do shallow fallback to en.
499 if ( $code === 'en' ) {
500 throw new MWException( 'No localisation cache found for English. ' .
501 'Please run maintenance/rebuildLocalisationCache.php.' );
503 $this->initShallowFallback( $code, 'en' );
507 throw new MWException( 'Invalid or missing localisation cache.' );
510 $this->data
[$code] = $preload;
511 foreach ( $preload as $key => $item ) {
512 if ( in_array( $key, self
::$splitKeys ) ) {
513 foreach ( $item as $subkey => $subitem ) {
514 $this->loadedSubitems
[$code][$key][$subkey] = true;
517 $this->loadedItems
[$code][$key] = true;
523 * Create a fallback from one language to another, without creating a
524 * complete persistent cache.
525 * @param string $primaryCode
526 * @param string $fallbackCode
528 public function initShallowFallback( $primaryCode, $fallbackCode ) {
529 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
530 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
531 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
532 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
536 * Read a PHP file containing localisation data.
537 * @param string $_fileName
538 * @param string $_fileType
539 * @throws MWException
542 protected function readPHPFile( $_fileName, $_fileType ) {
546 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
547 foreach ( self
::$allKeys as $key ) {
548 // Not all keys are set in language files, so
549 // check they exist first
550 if ( isset( $
$key ) ) {
554 } elseif ( $_fileType == 'aliases' ) {
555 if ( isset( $aliases ) ) {
556 $data['aliases'] = $aliases;
559 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
566 * Read a JSON file containing localisation messages.
567 * @param string $fileName Name of file to read
568 * @throws MWException If there is a syntax error in the JSON file
569 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
571 public function readJSONFile( $fileName ) {
572 if ( !is_readable( $fileName ) ) {
576 $json = file_get_contents( $fileName );
577 if ( $json === false ) {
581 $data = FormatJson
::decode( $json, true );
582 if ( $data === null ) {
583 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
586 // Remove keys starting with '@', they're reserved for metadata and non-message data
587 foreach ( $data as $key => $unused ) {
588 if ( $key === '' ||
$key[0] === '@' ) {
589 unset( $data[$key] );
593 // The JSON format only supports messages, none of the other variables, so wrap the data
594 return [ 'messages' => $data ];
598 * Get the compiled plural rules for a given language from the XML files.
600 * @param string $code
603 public function getCompiledPluralRules( $code ) {
604 $rules = $this->getPluralRules( $code );
605 if ( $rules === null ) {
609 $compiledRules = Evaluator
::compile( $rules );
610 } catch ( CLDRPluralRuleError
$e ) {
611 $this->logger
->debug( $e->getMessage() );
616 return $compiledRules;
620 * Get the plural rules for a given language from the XML files.
623 * @param string $code
626 public function getPluralRules( $code ) {
627 if ( $this->pluralRules
=== null ) {
628 $this->loadPluralFiles();
630 return $this->pluralRules
[$code] ??
null;
634 * Get the plural rule types for a given language from the XML files.
637 * @param string $code
640 public function getPluralRuleTypes( $code ) {
641 if ( $this->pluralRuleTypes
=== null ) {
642 $this->loadPluralFiles();
644 return $this->pluralRuleTypes
[$code] ??
null;
648 * Load the plural XML files.
650 protected function loadPluralFiles() {
652 $cldrPlural = "$IP/languages/data/plurals.xml";
653 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
654 // Load CLDR plural rules
655 $this->loadPluralFile( $cldrPlural );
656 if ( file_exists( $mwPlural ) ) {
657 // Override or extend
658 $this->loadPluralFile( $mwPlural );
663 * Load a plural XML file with the given filename, compile the relevant
664 * rules, and save the compiled rules in a process-local cache.
666 * @param string $fileName
667 * @throws MWException
669 protected function loadPluralFile( $fileName ) {
670 // Use file_get_contents instead of DOMDocument::load (T58439)
671 $xml = file_get_contents( $fileName );
673 throw new MWException( "Unable to read plurals file $fileName" );
675 $doc = new DOMDocument
;
676 $doc->loadXML( $xml );
677 $rulesets = $doc->getElementsByTagName( "pluralRules" );
678 foreach ( $rulesets as $ruleset ) {
679 $codes = $ruleset->getAttribute( 'locales' );
682 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
683 foreach ( $ruleElements as $elt ) {
684 $ruleType = $elt->getAttribute( 'count' );
685 if ( $ruleType === 'other' ) {
686 // Don't record "other" rules, which have an empty condition
689 $rules[] = $elt->nodeValue
;
690 $ruleTypes[] = $ruleType;
692 foreach ( explode( ' ', $codes ) as $code ) {
693 $this->pluralRules
[$code] = $rules;
694 $this->pluralRuleTypes
[$code] = $ruleTypes;
700 * Read the data from the source files for a given language, and register
701 * the relevant dependencies in the $deps array. If the localisation
702 * exists, the data array is returned, otherwise false is returned.
704 * @param string $code
705 * @param array &$deps
708 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
711 // This reads in the PHP i18n file with non-messages l10n data
712 $fileName = Language
::getMessagesFileName( $code );
713 if ( !file_exists( $fileName ) ) {
716 $deps[] = new FileDependency( $fileName );
717 $data = $this->readPHPFile( $fileName, 'core' );
720 # Load CLDR plural rules for JavaScript
721 $data['pluralRules'] = $this->getPluralRules( $code );
723 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
724 # Load plural rule types
725 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
727 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
728 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
734 * Merge two localisation values, a primary and a fallback, overwriting the
735 * primary value in place.
737 * @param mixed &$value
738 * @param mixed $fallbackValue
740 protected function mergeItem( $key, &$value, $fallbackValue ) {
741 if ( !is_null( $value ) ) {
742 if ( !is_null( $fallbackValue ) ) {
743 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
744 $value = $value +
$fallbackValue;
745 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
746 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
747 $value = array_unique( array_merge( $fallbackValue, $value ) );
748 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
749 $value = array_merge_recursive( $value, $fallbackValue );
750 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
751 if ( !empty( $value['inherit'] ) ) {
752 $value = array_merge( $fallbackValue, $value );
755 if ( isset( $value['inherit'] ) ) {
756 unset( $value['inherit'] );
758 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
759 $this->mergeMagicWords( $value, $fallbackValue );
763 $value = $fallbackValue;
768 * @param mixed &$value
769 * @param mixed $fallbackValue
771 protected function mergeMagicWords( &$value, $fallbackValue ) {
772 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
773 if ( !isset( $value[$magicName] ) ) {
774 $value[$magicName] = $fallbackInfo;
776 $oldSynonyms = array_slice( $fallbackInfo, 1 );
777 $newSynonyms = array_slice( $value[$magicName], 1 );
778 $synonyms = array_values( array_unique( array_merge(
779 $newSynonyms, $oldSynonyms ) ) );
780 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
786 * Given an array mapping language code to localisation value, such as is
787 * found in extension *.i18n.php files, iterate through a fallback sequence
788 * to merge the given data with an existing primary value.
790 * Returns true if any data from the extension array was used, false
792 * @param array $codeSequence
794 * @param mixed &$value
795 * @param mixed $fallbackValue
798 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
800 foreach ( $codeSequence as $code ) {
801 if ( isset( $fallbackValue[$code] ) ) {
802 $this->mergeItem( $key, $value, $fallbackValue[$code] );
811 * Gets the combined list of messages dirs from
812 * core and extensions
817 public function getMessagesDirs() {
821 'core' => "$IP/languages/i18n",
822 'exif' => "$IP/languages/i18n/exif",
823 'api' => "$IP/includes/api/i18n",
824 'oojs-ui' => "$IP/resources/lib/ooui/i18n",
825 ] +
$this->options
->get( 'MessagesDirs' );
829 * Load localisation data for a given language for both core and extensions
830 * and save it to the persistent cache store and the process cache
831 * @param string $code
832 * @throws MWException
834 public function recache( $code ) {
836 throw new MWException( "Invalid language code requested" );
838 $this->recachedLangs
[ $code ] = true;
841 $initialData = array_fill_keys( self
::$allKeys, null );
842 $coreData = $initialData;
845 # Load the primary localisation from the source file
846 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
847 $this->logger
->debug( __METHOD__
. ": got localisation for $code from source" );
849 # Merge primary localisation
850 foreach ( $data as $key => $value ) {
851 $this->mergeItem( $key, $coreData[ $key ], $value );
854 # Fill in the fallback if it's not there already
855 if ( ( is_null( $coreData['fallback'] ) ||
$coreData['fallback'] === false ) && $code === 'en' ) {
856 $coreData['fallback'] = false;
857 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
859 if ( !is_null( $coreData['fallback'] ) ) {
860 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
862 $coreData['fallbackSequence'] = [];
864 $len = count( $coreData['fallbackSequence'] );
866 # Before we add the 'en' fallback for messages, keep a copy of
867 # the original fallback sequence
868 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
870 # Ensure that the sequence ends at 'en' for messages
871 if ( !$len ||
$coreData['fallbackSequence'][$len - 1] !== 'en' ) {
872 $coreData['fallbackSequence'][] = 'en';
876 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
877 $messageDirs = $this->getMessagesDirs();
879 # Load non-JSON localisation data for extensions
880 $extensionData = array_fill_keys( $codeSequence, $initialData );
881 foreach ( $this->options
->get( 'ExtensionMessagesFiles' ) as $extension => $fileName ) {
882 if ( isset( $messageDirs[$extension] ) ) {
883 # This extension has JSON message data; skip the PHP shim
887 $data = $this->readPHPFile( $fileName, 'extension' );
890 foreach ( $data as $key => $item ) {
891 foreach ( $codeSequence as $csCode ) {
892 if ( isset( $item[$csCode] ) ) {
893 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
900 $deps[] = new FileDependency( $fileName );
904 # Load the localisation data for each fallback, then merge it into the full array
905 $allData = $initialData;
906 foreach ( $codeSequence as $csCode ) {
907 $csData = $initialData;
909 # Load core messages and the extension localisations.
910 foreach ( $messageDirs as $dirs ) {
911 foreach ( (array)$dirs as $dir ) {
912 $fileName = "$dir/$csCode.json";
913 $data = $this->readJSONFile( $fileName );
915 foreach ( $data as $key => $item ) {
916 $this->mergeItem( $key, $csData[$key], $item );
919 $deps[] = new FileDependency( $fileName );
923 # Merge non-JSON extension data
924 if ( isset( $extensionData[$csCode] ) ) {
925 foreach ( $extensionData[$csCode] as $key => $item ) {
926 $this->mergeItem( $key, $csData[$key], $item );
930 if ( $csCode === $code ) {
931 # Merge core data into extension data
932 foreach ( $coreData as $key => $item ) {
933 $this->mergeItem( $key, $csData[$key], $item );
936 # Load the secondary localisation from the source file to
937 # avoid infinite cycles on cyclic fallbacks
938 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
939 # Only merge the keys that make sense to merge
940 foreach ( self
::$allKeys as $key ) {
941 if ( !isset( $fbData[ $key ] ) ) {
945 if ( is_null( $coreData[ $key ] ) ||
$this->isMergeableKey( $key ) ) {
946 $this->mergeItem( $key, $csData[ $key ], $fbData[ $key ] );
951 # Allow extensions an opportunity to adjust the data for this
953 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
955 # Merge the data for this fallback into the final array
956 if ( $csCode === $code ) {
959 foreach ( self
::$allKeys as $key ) {
960 if ( !isset( $csData[$key] ) ) {
964 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
965 $this->mergeItem( $key, $allData[$key], $csData[$key] );
971 # Add cache dependencies for any referenced globals
972 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
973 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
974 // We use the key 'wgMessagesDirs' for historical reasons.
975 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
976 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
978 # Add dependencies to the cache entry
979 $allData['deps'] = $deps;
981 # Replace spaces with underscores in namespace names
982 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
984 # And do the same for special page aliases. $page is an array.
985 foreach ( $allData['specialPageAliases'] as &$page ) {
986 $page = str_replace( ' ', '_', $page );
988 # Decouple the reference to prevent accidental damage
991 # If there were no plural rules, return an empty array
992 if ( $allData['pluralRules'] === null ) {
993 $allData['pluralRules'] = [];
995 if ( $allData['compiledPluralRules'] === null ) {
996 $allData['compiledPluralRules'] = [];
998 # If there were no plural rule types, return an empty array
999 if ( $allData['pluralRuleTypes'] === null ) {
1000 $allData['pluralRuleTypes'] = [];
1004 $allData['list'] = [];
1005 foreach ( self
::$splitKeys as $key ) {
1006 $allData['list'][$key] = array_keys( $allData[$key] );
1009 $unused = true; // Used to be $purgeBlobs, removed in 1.34
1010 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$unused ] );
1012 if ( is_null( $allData['namespaceNames'] ) ) {
1013 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
1014 'Check that your languages/messages/MessagesEn.php file is intact.' );
1017 # Set the preload key
1018 $allData['preload'] = $this->buildPreload( $allData );
1020 # Save to the process cache and register the items loaded
1021 $this->data
[$code] = $allData;
1022 foreach ( $allData as $key => $item ) {
1023 $this->loadedItems
[$code][$key] = true;
1026 # Save to the persistent cache
1027 $this->store
->startWrite( $code );
1028 foreach ( $allData as $key => $value ) {
1029 if ( in_array( $key, self
::$splitKeys ) ) {
1030 foreach ( $value as $subkey => $subvalue ) {
1031 $this->store
->set( "$key:$subkey", $subvalue );
1034 $this->store
->set( $key, $value );
1037 $this->store
->finishWrite();
1039 # Clear out the MessageBlobStore
1040 # HACK: If using a null (i.e. disabled) storage backend, we
1041 # can't write to the MessageBlobStore either
1042 if ( !$this->store
instanceof LCStoreNull
) {
1043 foreach ( $this->clearStoreCallbacks
as $callback ) {
1050 * Build the preload item from the given pre-cache data.
1052 * The preload item will be loaded automatically, improving performance
1053 * for the commonly-requested items it contains.
1054 * @param array $data
1057 protected function buildPreload( $data ) {
1058 $preload = [ 'messages' => [] ];
1059 foreach ( self
::$preloadedKeys as $key ) {
1060 $preload[$key] = $data[$key];
1063 foreach ( $data['preloadedMessages'] as $subkey ) {
1064 $subitem = $data['messages'][$subkey] ??
null;
1065 $preload['messages'][$subkey] = $subitem;
1072 * Unload the data for a given language from the object cache.
1073 * Reduces memory usage.
1074 * @param string $code
1076 public function unload( $code ) {
1077 unset( $this->data
[$code] );
1078 unset( $this->loadedItems
[$code] );
1079 unset( $this->loadedSubitems
[$code] );
1080 unset( $this->initialisedLangs
[$code] );
1081 unset( $this->shallowFallbacks
[$code] );
1083 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1084 if ( $fbCode === $code ) {
1085 $this->unload( $shallowCode );
1093 public function unloadAll() {
1094 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1095 $this->unload( $lang );
1100 * Disable the storage backend
1102 public function disableBackend() {
1103 $this->store
= new LCStoreNull
;
1104 $this->manualRecache
= false;