Merge "Request-local caching of DjVu dimensions"
[mediawiki.git] / includes / cache / LocalisationCache.php
blob6efeabef4aa06518b8df48c033d1e4b4daa33ce8
1 <?php
2 /**
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
20 * @file
23 use Cdb\Exception as CdbException;
24 use Cdb\Reader as CdbReader;
25 use Cdb\Writer as CdbWriter;
26 use CLDRPluralRuleParser\Evaluator;
28 /**
29 * Class for caching the contents of localisation files, Messages*.php
30 * and *.i18n.php.
32 * An instance of this class is available using Language::getLocalisationCache().
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 {
41 const VERSION = 4;
43 /** Configuration associative array */
44 private $conf;
46 /**
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;
53 /**
54 * True to treat all files as expired until they are regenerated by this object.
56 private $forceRecache = false;
58 /**
59 * The cache data. 3-d array, where the first key is the language code,
60 * the second key is the item key e.g. 'messages', and the third key is
61 * an item specific subkey index. Some items are not arrays and so for those
62 * items, there are no subkeys.
64 protected $data = [];
66 /**
67 * The persistent store object. An instance of LCStore.
69 * @var LCStore
71 private $store;
73 /**
74 * A 2-d associative array, code/key, where presence indicates that the item
75 * is loaded. Value arbitrary.
77 * For split items, if set, this indicates that all of the subitems have been
78 * loaded.
80 private $loadedItems = [];
82 /**
83 * A 3-d associative array, code/key/subkey, where presence indicates that
84 * the subitem is loaded. Only used for the split items, i.e. messages.
86 private $loadedSubitems = [];
88 /**
89 * An array where presence of a key indicates that that language has been
90 * initialised. Initialisation includes checking for cache expiry and doing
91 * any necessary updates.
93 private $initialisedLangs = [];
95 /**
96 * An array mapping non-existent pseudo-languages to fallback languages. This
97 * is filled by initShallowFallback() when data is requested from a language
98 * that lacks a Messages*.php file.
100 private $shallowFallbacks = [];
103 * An array where the keys are codes that have been recached by this instance.
105 private $recachedLangs = [];
108 * All item keys
110 static public $allKeys = [
111 'fallback', 'namespaceNames', 'bookstoreList',
112 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
113 'separatorTransformTable', '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 * Constructor.
186 * For constructor parameters, see the documentation in DefaultSettings.php
187 * for $wgLocalisationCacheConf.
189 * @param array $conf
190 * @throws MWException
192 function __construct( $conf ) {
193 global $wgCacheDirectory;
195 $this->conf = $conf;
196 $storeConf = [];
197 if ( !empty( $conf['storeClass'] ) ) {
198 $storeClass = $conf['storeClass'];
199 } else {
200 switch ( $conf['store'] ) {
201 case 'files':
202 case 'file':
203 $storeClass = 'LCStoreCDB';
204 break;
205 case 'db':
206 $storeClass = 'LCStoreDB';
207 break;
208 case 'array':
209 $storeClass = 'LCStoreStaticArray';
210 break;
211 case 'detect':
212 if ( !empty( $conf['storeDirectory'] ) ) {
213 $storeClass = 'LCStoreCDB';
214 } else {
215 $cacheDir = $wgCacheDirectory ?: wfTempDir();
216 if ( $cacheDir ) {
217 $storeConf['directory'] = $cacheDir;
218 $storeClass = 'LCStoreCDB';
219 } else {
220 $storeClass = 'LCStoreDB';
223 break;
224 default:
225 throw new MWException(
226 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
230 wfDebugLog( 'caches', get_class( $this ) . ": using store $storeClass" );
231 if ( !empty( $conf['storeDirectory'] ) ) {
232 $storeConf['directory'] = $conf['storeDirectory'];
235 $this->store = new $storeClass( $storeConf );
236 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
237 if ( isset( $conf[$var] ) ) {
238 $this->$var = $conf[$var];
244 * Returns true if the given key is mergeable, that is, if it is an associative
245 * array which can be merged through a fallback sequence.
246 * @param string $key
247 * @return bool
249 public function isMergeableKey( $key ) {
250 if ( $this->mergeableKeys === null ) {
251 $this->mergeableKeys = array_flip( array_merge(
252 self::$mergeableMapKeys,
253 self::$mergeableListKeys,
254 self::$mergeableAliasListKeys,
255 self::$optionalMergeKeys,
256 self::$magicWordKeys
257 ) );
260 return isset( $this->mergeableKeys[$key] );
264 * Get a cache item.
266 * Warning: this may be slow for split items (messages), since it will
267 * need to fetch all of the subitems from the cache individually.
268 * @param string $code
269 * @param string $key
270 * @return mixed
272 public function getItem( $code, $key ) {
273 if ( !isset( $this->loadedItems[$code][$key] ) ) {
274 $this->loadItem( $code, $key );
277 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
278 return $this->shallowFallbacks[$code];
281 return $this->data[$code][$key];
285 * Get a subitem, for instance a single message for a given language.
286 * @param string $code
287 * @param string $key
288 * @param string $subkey
289 * @return mixed|null
291 public function getSubitem( $code, $key, $subkey ) {
292 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) &&
293 !isset( $this->loadedItems[$code][$key] )
295 $this->loadSubitem( $code, $key, $subkey );
298 if ( isset( $this->data[$code][$key][$subkey] ) ) {
299 return $this->data[$code][$key][$subkey];
300 } else {
301 return null;
306 * Get the list of subitem keys for a given item.
308 * This is faster than array_keys($lc->getItem(...)) for the items listed in
309 * self::$splitKeys.
311 * Will return null if the item is not found, or false if the item is not an
312 * array.
313 * @param string $code
314 * @param string $key
315 * @return bool|null|string
317 public function getSubitemList( $code, $key ) {
318 if ( in_array( $key, self::$splitKeys ) ) {
319 return $this->getSubitem( $code, 'list', $key );
320 } else {
321 $item = $this->getItem( $code, $key );
322 if ( is_array( $item ) ) {
323 return array_keys( $item );
324 } else {
325 return false;
331 * Load an item into the cache.
332 * @param string $code
333 * @param string $key
335 protected function loadItem( $code, $key ) {
336 if ( !isset( $this->initialisedLangs[$code] ) ) {
337 $this->initLanguage( $code );
340 // Check to see if initLanguage() loaded it for us
341 if ( isset( $this->loadedItems[$code][$key] ) ) {
342 return;
345 if ( isset( $this->shallowFallbacks[$code] ) ) {
346 $this->loadItem( $this->shallowFallbacks[$code], $key );
348 return;
351 if ( in_array( $key, self::$splitKeys ) ) {
352 $subkeyList = $this->getSubitem( $code, 'list', $key );
353 foreach ( $subkeyList as $subkey ) {
354 if ( isset( $this->data[$code][$key][$subkey] ) ) {
355 continue;
357 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
359 } else {
360 $this->data[$code][$key] = $this->store->get( $code, $key );
363 $this->loadedItems[$code][$key] = true;
367 * Load a subitem into the cache
368 * @param string $code
369 * @param string $key
370 * @param string $subkey
372 protected function loadSubitem( $code, $key, $subkey ) {
373 if ( !in_array( $key, self::$splitKeys ) ) {
374 $this->loadItem( $code, $key );
376 return;
379 if ( !isset( $this->initialisedLangs[$code] ) ) {
380 $this->initLanguage( $code );
383 // Check to see if initLanguage() loaded it for us
384 if ( isset( $this->loadedItems[$code][$key] ) ||
385 isset( $this->loadedSubitems[$code][$key][$subkey] )
387 return;
390 if ( isset( $this->shallowFallbacks[$code] ) ) {
391 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
393 return;
396 $value = $this->store->get( $code, "$key:$subkey" );
397 $this->data[$code][$key][$subkey] = $value;
398 $this->loadedSubitems[$code][$key][$subkey] = true;
402 * Returns true if the cache identified by $code is missing or expired.
404 * @param string $code
406 * @return bool
408 public function isExpired( $code ) {
409 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
410 wfDebug( __METHOD__ . "($code): forced reload\n" );
412 return true;
415 $deps = $this->store->get( $code, 'deps' );
416 $keys = $this->store->get( $code, 'list' );
417 $preload = $this->store->get( $code, 'preload' );
418 // Different keys may expire separately for some stores
419 if ( $deps === null || $keys === null || $preload === null ) {
420 wfDebug( __METHOD__ . "($code): cache missing, need to make one\n" );
422 return true;
425 foreach ( $deps as $dep ) {
426 // Because we're unserializing stuff from cache, we
427 // could receive objects of classes that don't exist
428 // anymore (e.g. uninstalled extensions)
429 // When this happens, always expire the cache
430 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
431 wfDebug( __METHOD__ . "($code): cache for $code expired due to " .
432 get_class( $dep ) . "\n" );
434 return true;
438 return false;
442 * Initialise a language in this object. Rebuild the cache if necessary.
443 * @param string $code
444 * @throws MWException
446 protected function initLanguage( $code ) {
447 if ( isset( $this->initialisedLangs[$code] ) ) {
448 return;
451 $this->initialisedLangs[$code] = true;
453 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
454 if ( !Language::isValidBuiltInCode( $code ) ) {
455 $this->initShallowFallback( $code, 'en' );
457 return;
460 # Recache the data if necessary
461 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
462 if ( Language::isSupportedLanguage( $code ) ) {
463 $this->recache( $code );
464 } elseif ( $code === 'en' ) {
465 throw new MWException( 'MessagesEn.php is missing.' );
466 } else {
467 $this->initShallowFallback( $code, 'en' );
470 return;
473 # Preload some stuff
474 $preload = $this->getItem( $code, 'preload' );
475 if ( $preload === null ) {
476 if ( $this->manualRecache ) {
477 // No Messages*.php file. Do shallow fallback to en.
478 if ( $code === 'en' ) {
479 throw new MWException( 'No localisation cache found for English. ' .
480 'Please run maintenance/rebuildLocalisationCache.php.' );
482 $this->initShallowFallback( $code, 'en' );
484 return;
485 } else {
486 throw new MWException( 'Invalid or missing localisation cache.' );
489 $this->data[$code] = $preload;
490 foreach ( $preload as $key => $item ) {
491 if ( in_array( $key, self::$splitKeys ) ) {
492 foreach ( $item as $subkey => $subitem ) {
493 $this->loadedSubitems[$code][$key][$subkey] = true;
495 } else {
496 $this->loadedItems[$code][$key] = true;
502 * Create a fallback from one language to another, without creating a
503 * complete persistent cache.
504 * @param string $primaryCode
505 * @param string $fallbackCode
507 public function initShallowFallback( $primaryCode, $fallbackCode ) {
508 $this->data[$primaryCode] =& $this->data[$fallbackCode];
509 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
510 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
511 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
515 * Read a PHP file containing localisation data.
516 * @param string $_fileName
517 * @param string $_fileType
518 * @throws MWException
519 * @return array
521 protected function readPHPFile( $_fileName, $_fileType ) {
522 // Disable APC caching
523 MediaWiki\suppressWarnings();
524 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
525 MediaWiki\restoreWarnings();
527 include $_fileName;
529 MediaWiki\suppressWarnings();
530 ini_set( 'apc.cache_by_default', $_apcEnabled );
531 MediaWiki\restoreWarnings();
533 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
534 $data = compact( self::$allKeys );
535 } elseif ( $_fileType == 'aliases' ) {
536 $data = compact( 'aliases' );
537 } else {
538 throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" );
541 return $data;
545 * Read a JSON file containing localisation messages.
546 * @param string $fileName Name of file to read
547 * @throws MWException If there is a syntax error in the JSON file
548 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
550 public function readJSONFile( $fileName ) {
552 if ( !is_readable( $fileName ) ) {
553 return [];
556 $json = file_get_contents( $fileName );
557 if ( $json === false ) {
558 return [];
561 $data = FormatJson::decode( $json, true );
562 if ( $data === null ) {
564 throw new MWException( __METHOD__ . ": Invalid JSON file: $fileName" );
567 // Remove keys starting with '@', they're reserved for metadata and non-message data
568 foreach ( $data as $key => $unused ) {
569 if ( $key === '' || $key[0] === '@' ) {
570 unset( $data[$key] );
574 // The JSON format only supports messages, none of the other variables, so wrap the data
575 return [ 'messages' => $data ];
579 * Get the compiled plural rules for a given language from the XML files.
580 * @since 1.20
581 * @param string $code
582 * @return array|null
584 public function getCompiledPluralRules( $code ) {
585 $rules = $this->getPluralRules( $code );
586 if ( $rules === null ) {
587 return null;
589 try {
590 $compiledRules = Evaluator::compile( $rules );
591 } catch ( CLDRPluralRuleError $e ) {
592 wfDebugLog( 'l10n', $e->getMessage() );
594 return [];
597 return $compiledRules;
601 * Get the plural rules for a given language from the XML files.
602 * Cached.
603 * @since 1.20
604 * @param string $code
605 * @return array|null
607 public function getPluralRules( $code ) {
608 if ( $this->pluralRules === null ) {
609 $this->loadPluralFiles();
611 if ( !isset( $this->pluralRules[$code] ) ) {
612 return null;
613 } else {
614 return $this->pluralRules[$code];
619 * Get the plural rule types for a given language from the XML files.
620 * Cached.
621 * @since 1.22
622 * @param string $code
623 * @return array|null
625 public function getPluralRuleTypes( $code ) {
626 if ( $this->pluralRuleTypes === null ) {
627 $this->loadPluralFiles();
629 if ( !isset( $this->pluralRuleTypes[$code] ) ) {
630 return null;
631 } else {
632 return $this->pluralRuleTypes[$code];
637 * Load the plural XML files.
639 protected function loadPluralFiles() {
640 global $IP;
641 $cldrPlural = "$IP/languages/data/plurals.xml";
642 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
643 // Load CLDR plural rules
644 $this->loadPluralFile( $cldrPlural );
645 if ( file_exists( $mwPlural ) ) {
646 // Override or extend
647 $this->loadPluralFile( $mwPlural );
652 * Load a plural XML file with the given filename, compile the relevant
653 * rules, and save the compiled rules in a process-local cache.
655 * @param string $fileName
656 * @throws MWException
658 protected function loadPluralFile( $fileName ) {
659 // Use file_get_contents instead of DOMDocument::load (T58439)
660 $xml = file_get_contents( $fileName );
661 if ( !$xml ) {
662 throw new MWException( "Unable to read plurals file $fileName" );
664 $doc = new DOMDocument;
665 $doc->loadXML( $xml );
666 $rulesets = $doc->getElementsByTagName( "pluralRules" );
667 foreach ( $rulesets as $ruleset ) {
668 $codes = $ruleset->getAttribute( 'locales' );
669 $rules = [];
670 $ruleTypes = [];
671 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
672 foreach ( $ruleElements as $elt ) {
673 $ruleType = $elt->getAttribute( 'count' );
674 if ( $ruleType === 'other' ) {
675 // Don't record "other" rules, which have an empty condition
676 continue;
678 $rules[] = $elt->nodeValue;
679 $ruleTypes[] = $ruleType;
681 foreach ( explode( ' ', $codes ) as $code ) {
682 $this->pluralRules[$code] = $rules;
683 $this->pluralRuleTypes[$code] = $ruleTypes;
689 * Read the data from the source files for a given language, and register
690 * the relevant dependencies in the $deps array. If the localisation
691 * exists, the data array is returned, otherwise false is returned.
693 * @param string $code
694 * @param array $deps
695 * @return array
697 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
698 global $IP;
700 // This reads in the PHP i18n file with non-messages l10n data
701 $fileName = Language::getMessagesFileName( $code );
702 if ( !file_exists( $fileName ) ) {
703 $data = [];
704 } else {
705 $deps[] = new FileDependency( $fileName );
706 $data = $this->readPHPFile( $fileName, 'core' );
709 # Load CLDR plural rules for JavaScript
710 $data['pluralRules'] = $this->getPluralRules( $code );
711 # And for PHP
712 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
713 # Load plural rule types
714 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
716 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
717 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
719 return $data;
723 * Merge two localisation values, a primary and a fallback, overwriting the
724 * primary value in place.
725 * @param string $key
726 * @param mixed $value
727 * @param mixed $fallbackValue
729 protected function mergeItem( $key, &$value, $fallbackValue ) {
730 if ( !is_null( $value ) ) {
731 if ( !is_null( $fallbackValue ) ) {
732 if ( in_array( $key, self::$mergeableMapKeys ) ) {
733 $value = $value + $fallbackValue;
734 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
735 $value = array_unique( array_merge( $fallbackValue, $value ) );
736 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
737 $value = array_merge_recursive( $value, $fallbackValue );
738 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
739 if ( !empty( $value['inherit'] ) ) {
740 $value = array_merge( $fallbackValue, $value );
743 if ( isset( $value['inherit'] ) ) {
744 unset( $value['inherit'] );
746 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
747 $this->mergeMagicWords( $value, $fallbackValue );
750 } else {
751 $value = $fallbackValue;
756 * @param mixed $value
757 * @param mixed $fallbackValue
759 protected function mergeMagicWords( &$value, $fallbackValue ) {
760 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
761 if ( !isset( $value[$magicName] ) ) {
762 $value[$magicName] = $fallbackInfo;
763 } else {
764 $oldSynonyms = array_slice( $fallbackInfo, 1 );
765 $newSynonyms = array_slice( $value[$magicName], 1 );
766 $synonyms = array_values( array_unique( array_merge(
767 $newSynonyms, $oldSynonyms ) ) );
768 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
774 * Given an array mapping language code to localisation value, such as is
775 * found in extension *.i18n.php files, iterate through a fallback sequence
776 * to merge the given data with an existing primary value.
778 * Returns true if any data from the extension array was used, false
779 * otherwise.
780 * @param array $codeSequence
781 * @param string $key
782 * @param mixed $value
783 * @param mixed $fallbackValue
784 * @return bool
786 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
787 $used = false;
788 foreach ( $codeSequence as $code ) {
789 if ( isset( $fallbackValue[$code] ) ) {
790 $this->mergeItem( $key, $value, $fallbackValue[$code] );
791 $used = true;
795 return $used;
799 * Gets the combined list of messages dirs from
800 * core and extensions
802 * @since 1.25
803 * @return array
805 public function getMessagesDirs() {
806 global $wgMessagesDirs, $IP;
807 return [
808 'core' => "$IP/languages/i18n",
809 'api' => "$IP/includes/api/i18n",
810 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
811 ] + $wgMessagesDirs;
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;
823 if ( !$code ) {
824 throw new MWException( "Invalid language code requested" );
826 $this->recachedLangs[$code] = true;
828 # Initial values
829 $initialData = array_fill_keys( self::$allKeys, null );
830 $coreData = $initialData;
831 $deps = [];
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';
838 } else {
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'] = [];
853 } else {
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
871 continue;
874 $data = $this->readPHPFile( $fileName, 'extension' );
875 $used = false;
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] );
881 $used = true;
886 if ( $used ) {
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 );
922 } else {
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] ) ) {
930 continue;
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
941 # fallback
942 Hooks::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
944 # Merge the data for this fallback into the final array
945 if ( $csCode === $code ) {
946 $allData = $csData;
947 } else {
948 foreach ( self::$allKeys as $key ) {
949 if ( !isset( $csData[$key] ) ) {
950 continue;
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 // $wgMessagesDirs is used in LocalisationCache::getMessagesDirs()
963 $deps['wgMessagesDirs'] = new GlobalDependency( 'wgMessagesDirs' );
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
977 unset( $page );
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'] = [];
991 # Set the list keys
992 $allData['list'] = [];
993 foreach ( self::$splitKeys as $key ) {
994 $allData['list'][$key] = array_keys( $allData[$key] );
996 # Run hooks
997 $purgeBlobs = true;
998 Hooks::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$purgeBlobs ] );
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 );
1021 } else {
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 ( $purgeBlobs && !$this->store instanceof LCStoreNull ) {
1031 $blobStore = new MessageBlobStore();
1032 $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
1043 * @return array
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];
1054 } else {
1055 $subitem = null;
1057 $preload['messages'][$subkey] = $subitem;
1060 return $preload;
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 );
1083 * Unload all data
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;
1101 * Interface for the persistence layer of LocalisationCache.
1103 * The persistence layer is two-level hierarchical cache. The first level
1104 * is the language, the second level is the item or subitem.
1106 * Since the data for a whole language is rebuilt in one operation, it needs
1107 * to have a fast and atomic method for deleting or replacing all of the
1108 * current data for a given language. The interface reflects this bulk update
1109 * operation. Callers writing to the cache must first call startWrite(), then
1110 * will call set() a couple of thousand times, then will call finishWrite()
1111 * to commit the operation. When finishWrite() is called, the cache is
1112 * expected to delete all data previously stored for that language.
1114 * The values stored are PHP variables suitable for serialize(). Implementations
1115 * of LCStore are responsible for serializing and unserializing.
1117 interface LCStore {
1119 * Get a value.
1120 * @param string $code Language code
1121 * @param string $key Cache key
1123 function get( $code, $key );
1126 * Start a write transaction.
1127 * @param string $code Language code
1129 function startWrite( $code );
1132 * Finish a write transaction.
1134 function finishWrite();
1137 * Set a key to a given value. startWrite() must be called before this
1138 * is called, and finishWrite() must be called afterwards.
1139 * @param string $key
1140 * @param mixed $value
1142 function set( $key, $value );
1146 * LCStore implementation which uses the standard DB functions to store data.
1147 * This will work on any MediaWiki installation.
1149 class LCStoreDB implements LCStore {
1150 /** @var string */
1151 private $currentLang;
1152 /** @var bool */
1153 private $writesDone = false;
1154 /** @var IDatabase */
1155 private $dbw;
1156 /** @var array */
1157 private $batch = [];
1158 /** @var bool */
1159 private $readOnly = false;
1161 public function get( $code, $key ) {
1162 if ( $this->writesDone && $this->dbw ) {
1163 $db = $this->dbw; // see the changes in finishWrite()
1164 } else {
1165 $db = wfGetDB( DB_SLAVE );
1168 $value = $db->selectField(
1169 'l10n_cache',
1170 'lc_value',
1171 [ 'lc_lang' => $code, 'lc_key' => $key ],
1172 __METHOD__
1175 return ( $value !== false ) ? unserialize( $db->decodeBlob( $value ) ) : null;
1178 public function startWrite( $code ) {
1179 if ( $this->readOnly ) {
1180 return;
1181 } elseif ( !$code ) {
1182 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1185 $this->dbw = wfGetDB( DB_MASTER );
1186 $this->readOnly = $this->dbw->isReadOnly();
1188 $this->currentLang = $code;
1189 $this->batch = [];
1192 public function finishWrite() {
1193 if ( $this->readOnly ) {
1194 return;
1195 } elseif ( is_null( $this->currentLang ) ) {
1196 throw new MWException( __CLASS__ . ': must call startWrite() before finishWrite()' );
1199 $this->dbw->startAtomic( __METHOD__ );
1200 try {
1201 $this->dbw->delete(
1202 'l10n_cache',
1203 [ 'lc_lang' => $this->currentLang ],
1204 __METHOD__
1206 foreach ( array_chunk( $this->batch, 500 ) as $rows ) {
1207 $this->dbw->insert( 'l10n_cache', $rows, __METHOD__ );
1209 $this->writesDone = true;
1210 } catch ( DBQueryError $e ) {
1211 if ( $this->dbw->wasReadOnlyError() ) {
1212 $this->readOnly = true; // just avoid site down time
1213 } else {
1214 throw $e;
1217 $this->dbw->endAtomic( __METHOD__ );
1219 $this->currentLang = null;
1220 $this->batch = [];
1223 public function set( $key, $value ) {
1224 if ( $this->readOnly ) {
1225 return;
1226 } elseif ( is_null( $this->currentLang ) ) {
1227 throw new MWException( __CLASS__ . ': must call startWrite() before set()' );
1230 $this->batch[] = [
1231 'lc_lang' => $this->currentLang,
1232 'lc_key' => $key,
1233 'lc_value' => $this->dbw->encodeBlob( serialize( $value ) )
1239 * LCStore implementation which stores data as a collection of CDB files in the
1240 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
1241 * will throw an exception.
1243 * Profiling indicates that on Linux, this implementation outperforms MySQL if
1244 * the directory is on a local filesystem and there is ample kernel cache
1245 * space. The performance advantage is greater when the DBA extension is
1246 * available than it is with the PHP port.
1248 * See Cdb.php and http://cr.yp.to/cdb.html
1250 class LCStoreCDB implements LCStore {
1251 /** @var CdbReader[] */
1252 private $readers;
1254 /** @var CdbWriter */
1255 private $writer;
1257 /** @var string Current language code */
1258 private $currentLang;
1260 /** @var bool|string Cache directory. False if not set */
1261 private $directory;
1263 function __construct( $conf = [] ) {
1264 global $wgCacheDirectory;
1266 if ( isset( $conf['directory'] ) ) {
1267 $this->directory = $conf['directory'];
1268 } else {
1269 $this->directory = $wgCacheDirectory;
1273 public function get( $code, $key ) {
1274 if ( !isset( $this->readers[$code] ) ) {
1275 $fileName = $this->getFileName( $code );
1277 $this->readers[$code] = false;
1278 if ( file_exists( $fileName ) ) {
1279 try {
1280 $this->readers[$code] = CdbReader::open( $fileName );
1281 } catch ( CdbException $e ) {
1282 wfDebug( __METHOD__ . ": unable to open cdb file for reading\n" );
1287 if ( !$this->readers[$code] ) {
1288 return null;
1289 } else {
1290 $value = false;
1291 try {
1292 $value = $this->readers[$code]->get( $key );
1293 } catch ( CdbException $e ) {
1294 wfDebug( __METHOD__ . ": CdbException caught, error message was "
1295 . $e->getMessage() . "\n" );
1297 if ( $value === false ) {
1298 return null;
1301 return unserialize( $value );
1305 public function startWrite( $code ) {
1306 if ( !file_exists( $this->directory ) ) {
1307 if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) {
1308 throw new MWException( "Unable to create the localisation store " .
1309 "directory \"{$this->directory}\"" );
1313 // Close reader to stop permission errors on write
1314 if ( !empty( $this->readers[$code] ) ) {
1315 $this->readers[$code]->close();
1318 try {
1319 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
1320 } catch ( CdbException $e ) {
1321 throw new MWException( $e->getMessage() );
1323 $this->currentLang = $code;
1326 public function finishWrite() {
1327 // Close the writer
1328 try {
1329 $this->writer->close();
1330 } catch ( CdbException $e ) {
1331 throw new MWException( $e->getMessage() );
1333 $this->writer = null;
1334 unset( $this->readers[$this->currentLang] );
1335 $this->currentLang = null;
1338 public function set( $key, $value ) {
1339 if ( is_null( $this->writer ) ) {
1340 throw new MWException( __CLASS__ . ': must call startWrite() before calling set()' );
1342 try {
1343 $this->writer->set( $key, serialize( $value ) );
1344 } catch ( CdbException $e ) {
1345 throw new MWException( $e->getMessage() );
1349 protected function getFileName( $code ) {
1350 if ( strval( $code ) === '' || strpos( $code, '/' ) !== false ) {
1351 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1354 return "{$this->directory}/l10n_cache-$code.cdb";
1359 * Null store backend, used to avoid DB errors during install
1361 class LCStoreNull implements LCStore {
1362 public function get( $code, $key ) {
1363 return null;
1366 public function startWrite( $code ) {
1369 public function finishWrite() {
1372 public function set( $key, $value ) {
1377 * A localisation cache optimised for loading large amounts of data for many
1378 * languages. Used by rebuildLocalisationCache.php.
1380 class LocalisationCacheBulkLoad extends LocalisationCache {
1382 * A cache of the contents of data files.
1383 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1385 private $fileCache = [];
1388 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1389 * to keep the most recently used language codes at the end of the array, and
1390 * the language codes that are ready to be deleted at the beginning.
1392 private $mruLangs = [];
1395 * Maximum number of languages that may be loaded into $this->data
1397 private $maxLoadedLangs = 10;
1400 * @param string $fileName
1401 * @param string $fileType
1402 * @return array|mixed
1404 protected function readPHPFile( $fileName, $fileType ) {
1405 $serialize = $fileType === 'core';
1406 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
1407 $data = parent::readPHPFile( $fileName, $fileType );
1409 if ( $serialize ) {
1410 $encData = serialize( $data );
1411 } else {
1412 $encData = $data;
1415 $this->fileCache[$fileName][$fileType] = $encData;
1417 return $data;
1418 } elseif ( $serialize ) {
1419 return unserialize( $this->fileCache[$fileName][$fileType] );
1420 } else {
1421 return $this->fileCache[$fileName][$fileType];
1426 * @param string $code
1427 * @param string $key
1428 * @return mixed
1430 public function getItem( $code, $key ) {
1431 unset( $this->mruLangs[$code] );
1432 $this->mruLangs[$code] = true;
1434 return parent::getItem( $code, $key );
1438 * @param string $code
1439 * @param string $key
1440 * @param string $subkey
1441 * @return mixed
1443 public function getSubitem( $code, $key, $subkey ) {
1444 unset( $this->mruLangs[$code] );
1445 $this->mruLangs[$code] = true;
1447 return parent::getSubitem( $code, $key, $subkey );
1451 * @param string $code
1453 public function recache( $code ) {
1454 parent::recache( $code );
1455 unset( $this->mruLangs[$code] );
1456 $this->mruLangs[$code] = true;
1457 $this->trimCache();
1461 * @param string $code
1463 public function unload( $code ) {
1464 unset( $this->mruLangs[$code] );
1465 parent::unload( $code );
1469 * Unload cached languages until there are less than $this->maxLoadedLangs
1471 protected function trimCache() {
1472 while ( count( $this->data ) > $this->maxLoadedLangs && count( $this->mruLangs ) ) {
1473 reset( $this->mruLangs );
1474 $code = key( $this->mruLangs );
1475 wfDebug( __METHOD__ . ": unloading $code\n" );
1476 $this->unload( $code );