Merge "Remove JS for FancyCaptcha adjustment"
[mediawiki.git] / includes / cache / LocalisationCache.php
blob276e84aaa9c598dc28b528477d66d2940f2d4e45
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;
27 /**
28 * Class for caching the contents of localisation files, Messages*.php
29 * and *.i18n.php.
31 * An instance of this class is available using Language::getLocalisationCache().
33 * The values retrieved from here are merged, containing items from extension
34 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
35 * zh-hans -> en ). Some common errors are corrected, for example namespace
36 * names with spaces instead of underscores, but heavyweight processing, such
37 * as grammatical transformation, is done by the caller.
39 class LocalisationCache {
40 const VERSION = 3;
42 /** Configuration associative array */
43 private $conf;
45 /**
46 * True if recaching should only be done on an explicit call to recache().
47 * Setting this reduces the overhead of cache freshness checking, which
48 * requires doing a stat() for every extension i18n file.
50 private $manualRecache = false;
52 /**
53 * True to treat all files as expired until they are regenerated by this object.
55 private $forceRecache = false;
57 /**
58 * The cache data. 3-d array, where the first key is the language code,
59 * the second key is the item key e.g. 'messages', and the third key is
60 * an item specific subkey index. Some items are not arrays and so for those
61 * items, there are no subkeys.
63 protected $data = array();
65 /**
66 * The persistent store object. An instance of LCStore.
68 * @var LCStore
70 private $store;
72 /**
73 * A 2-d associative array, code/key, where presence indicates that the item
74 * is loaded. Value arbitrary.
76 * For split items, if set, this indicates that all of the subitems have been
77 * loaded.
79 private $loadedItems = array();
81 /**
82 * A 3-d associative array, code/key/subkey, where presence indicates that
83 * the subitem is loaded. Only used for the split items, i.e. messages.
85 private $loadedSubitems = array();
87 /**
88 * An array where presence of a key indicates that that language has been
89 * initialised. Initialisation includes checking for cache expiry and doing
90 * any necessary updates.
92 private $initialisedLangs = array();
94 /**
95 * An array mapping non-existent pseudo-languages to fallback languages. This
96 * is filled by initShallowFallback() when data is requested from a language
97 * that lacks a Messages*.php file.
99 private $shallowFallbacks = array();
102 * An array where the keys are codes that have been recached by this instance.
104 private $recachedLangs = array();
107 * All item keys
109 static public $allKeys = array(
110 'fallback', 'namespaceNames', 'bookstoreList',
111 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
112 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
113 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
114 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
115 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
116 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
117 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
121 * Keys for items which consist of associative arrays, which may be merged
122 * by a fallback sequence.
124 static public $mergeableMapKeys = array( 'messages', 'namespaceNames',
125 'dateFormats', 'imageFiles', 'preloadedMessages'
129 * Keys for items which are a numbered array.
131 static public $mergeableListKeys = array( 'extraUserToggles' );
134 * Keys for items which contain an array of arrays of equivalent aliases
135 * for each subitem. The aliases may be merged by a fallback sequence.
137 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
140 * Keys for items which contain an associative array, and may be merged if
141 * the primary value contains the special array key "inherit". That array
142 * key is removed after the first merge.
144 static public $optionalMergeKeys = array( 'bookstoreList' );
147 * Keys for items that are formatted like $magicWords
149 static public $magicWordKeys = array( 'magicWords' );
152 * Keys for items where the subitems are stored in the backend separately.
154 static public $splitKeys = array( 'messages' );
157 * Keys which are loaded automatically by initLanguage()
159 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames' );
162 * Associative array of cached plural rules. The key is the language code,
163 * the value is an array of plural rules for that language.
165 private $pluralRules = null;
168 * Associative array of cached plural rule types. The key is the language
169 * code, the value is an array of plural rule types for that language. For
170 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
171 * The index for each rule type matches the index for the rule in
172 * $pluralRules, thus allowing correlation between the two. The reason we
173 * don't just use the type names as the keys in $pluralRules is because
174 * Language::convertPlural applies the rules based on numeric order (or
175 * explicit numeric parameter), not based on the name of the rule type. For
176 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
177 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
179 private $pluralRuleTypes = null;
181 private $mergeableKeys = null;
184 * Constructor.
185 * For constructor parameters, see the documentation in DefaultSettings.php
186 * for $wgLocalisationCacheConf.
188 * @param array $conf
189 * @throws MWException
191 function __construct( $conf ) {
192 global $wgCacheDirectory;
194 $this->conf = $conf;
195 $storeConf = array();
196 if ( !empty( $conf['storeClass'] ) ) {
197 $storeClass = $conf['storeClass'];
198 } else {
199 switch ( $conf['store'] ) {
200 case 'files':
201 case 'file':
202 $storeClass = 'LCStoreCDB';
203 break;
204 case 'db':
205 $storeClass = 'LCStoreDB';
206 break;
207 case 'array':
208 $storeClass = 'LCStoreStaticArray';
209 break;
210 case 'detect':
211 $storeClass = $wgCacheDirectory ? 'LCStoreCDB' : 'LCStoreDB';
212 break;
213 default:
214 throw new MWException(
215 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
219 wfDebugLog( 'caches', get_class( $this ) . ": using store $storeClass" );
220 if ( !empty( $conf['storeDirectory'] ) ) {
221 $storeConf['directory'] = $conf['storeDirectory'];
224 $this->store = new $storeClass( $storeConf );
225 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
226 if ( isset( $conf[$var] ) ) {
227 $this->$var = $conf[$var];
233 * Returns true if the given key is mergeable, that is, if it is an associative
234 * array which can be merged through a fallback sequence.
235 * @param string $key
236 * @return bool
238 public function isMergeableKey( $key ) {
239 if ( $this->mergeableKeys === null ) {
240 $this->mergeableKeys = array_flip( array_merge(
241 self::$mergeableMapKeys,
242 self::$mergeableListKeys,
243 self::$mergeableAliasListKeys,
244 self::$optionalMergeKeys,
245 self::$magicWordKeys
246 ) );
249 return isset( $this->mergeableKeys[$key] );
253 * Get a cache item.
255 * Warning: this may be slow for split items (messages), since it will
256 * need to fetch all of the subitems from the cache individually.
257 * @param string $code
258 * @param string $key
259 * @return mixed
261 public function getItem( $code, $key ) {
262 if ( !isset( $this->loadedItems[$code][$key] ) ) {
263 $this->loadItem( $code, $key );
266 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
267 return $this->shallowFallbacks[$code];
270 return $this->data[$code][$key];
274 * Get a subitem, for instance a single message for a given language.
275 * @param string $code
276 * @param string $key
277 * @param string $subkey
278 * @return mixed|null
280 public function getSubitem( $code, $key, $subkey ) {
281 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) &&
282 !isset( $this->loadedItems[$code][$key] )
284 $this->loadSubitem( $code, $key, $subkey );
287 if ( isset( $this->data[$code][$key][$subkey] ) ) {
288 return $this->data[$code][$key][$subkey];
289 } else {
290 return null;
295 * Get the list of subitem keys for a given item.
297 * This is faster than array_keys($lc->getItem(...)) for the items listed in
298 * self::$splitKeys.
300 * Will return null if the item is not found, or false if the item is not an
301 * array.
302 * @param string $code
303 * @param string $key
304 * @return bool|null|string
306 public function getSubitemList( $code, $key ) {
307 if ( in_array( $key, self::$splitKeys ) ) {
308 return $this->getSubitem( $code, 'list', $key );
309 } else {
310 $item = $this->getItem( $code, $key );
311 if ( is_array( $item ) ) {
312 return array_keys( $item );
313 } else {
314 return false;
320 * Load an item into the cache.
321 * @param string $code
322 * @param string $key
324 protected function loadItem( $code, $key ) {
325 if ( !isset( $this->initialisedLangs[$code] ) ) {
326 $this->initLanguage( $code );
329 // Check to see if initLanguage() loaded it for us
330 if ( isset( $this->loadedItems[$code][$key] ) ) {
331 return;
334 if ( isset( $this->shallowFallbacks[$code] ) ) {
335 $this->loadItem( $this->shallowFallbacks[$code], $key );
337 return;
340 if ( in_array( $key, self::$splitKeys ) ) {
341 $subkeyList = $this->getSubitem( $code, 'list', $key );
342 foreach ( $subkeyList as $subkey ) {
343 if ( isset( $this->data[$code][$key][$subkey] ) ) {
344 continue;
346 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
348 } else {
349 $this->data[$code][$key] = $this->store->get( $code, $key );
352 $this->loadedItems[$code][$key] = true;
356 * Load a subitem into the cache
357 * @param string $code
358 * @param string $key
359 * @param string $subkey
361 protected function loadSubitem( $code, $key, $subkey ) {
362 if ( !in_array( $key, self::$splitKeys ) ) {
363 $this->loadItem( $code, $key );
365 return;
368 if ( !isset( $this->initialisedLangs[$code] ) ) {
369 $this->initLanguage( $code );
372 // Check to see if initLanguage() loaded it for us
373 if ( isset( $this->loadedItems[$code][$key] ) ||
374 isset( $this->loadedSubitems[$code][$key][$subkey] )
376 return;
379 if ( isset( $this->shallowFallbacks[$code] ) ) {
380 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
382 return;
385 $value = $this->store->get( $code, "$key:$subkey" );
386 $this->data[$code][$key][$subkey] = $value;
387 $this->loadedSubitems[$code][$key][$subkey] = true;
391 * Returns true if the cache identified by $code is missing or expired.
393 * @param string $code
395 * @return bool
397 public function isExpired( $code ) {
398 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
399 wfDebug( __METHOD__ . "($code): forced reload\n" );
401 return true;
404 $deps = $this->store->get( $code, 'deps' );
405 $keys = $this->store->get( $code, 'list' );
406 $preload = $this->store->get( $code, 'preload' );
407 // Different keys may expire separately for some stores
408 if ( $deps === null || $keys === null || $preload === null ) {
409 wfDebug( __METHOD__ . "($code): cache missing, need to make one\n" );
411 return true;
414 foreach ( $deps as $dep ) {
415 // Because we're unserializing stuff from cache, we
416 // could receive objects of classes that don't exist
417 // anymore (e.g. uninstalled extensions)
418 // When this happens, always expire the cache
419 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
420 wfDebug( __METHOD__ . "($code): cache for $code expired due to " .
421 get_class( $dep ) . "\n" );
423 return true;
427 return false;
431 * Initialise a language in this object. Rebuild the cache if necessary.
432 * @param string $code
433 * @throws MWException
435 protected function initLanguage( $code ) {
436 if ( isset( $this->initialisedLangs[$code] ) ) {
437 return;
440 $this->initialisedLangs[$code] = true;
442 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
443 if ( !Language::isValidBuiltInCode( $code ) ) {
444 $this->initShallowFallback( $code, 'en' );
446 return;
449 # Recache the data if necessary
450 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
451 if ( Language::isSupportedLanguage( $code ) ) {
452 $this->recache( $code );
453 } elseif ( $code === 'en' ) {
454 throw new MWException( 'MessagesEn.php is missing.' );
455 } else {
456 $this->initShallowFallback( $code, 'en' );
459 return;
462 # Preload some stuff
463 $preload = $this->getItem( $code, 'preload' );
464 if ( $preload === null ) {
465 if ( $this->manualRecache ) {
466 // No Messages*.php file. Do shallow fallback to en.
467 if ( $code === 'en' ) {
468 throw new MWException( 'No localisation cache found for English. ' .
469 'Please run maintenance/rebuildLocalisationCache.php.' );
471 $this->initShallowFallback( $code, 'en' );
473 return;
474 } else {
475 throw new MWException( 'Invalid or missing localisation cache.' );
478 $this->data[$code] = $preload;
479 foreach ( $preload as $key => $item ) {
480 if ( in_array( $key, self::$splitKeys ) ) {
481 foreach ( $item as $subkey => $subitem ) {
482 $this->loadedSubitems[$code][$key][$subkey] = true;
484 } else {
485 $this->loadedItems[$code][$key] = true;
491 * Create a fallback from one language to another, without creating a
492 * complete persistent cache.
493 * @param string $primaryCode
494 * @param string $fallbackCode
496 public function initShallowFallback( $primaryCode, $fallbackCode ) {
497 $this->data[$primaryCode] =& $this->data[$fallbackCode];
498 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
499 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
500 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
504 * Read a PHP file containing localisation data.
505 * @param string $_fileName
506 * @param string $_fileType
507 * @throws MWException
508 * @return array
510 protected function readPHPFile( $_fileName, $_fileType ) {
511 // Disable APC caching
512 MediaWiki\suppressWarnings();
513 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
514 MediaWiki\restoreWarnings();
516 include $_fileName;
518 MediaWiki\suppressWarnings();
519 ini_set( 'apc.cache_by_default', $_apcEnabled );
520 MediaWiki\restoreWarnings();
522 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
523 $data = compact( self::$allKeys );
524 } elseif ( $_fileType == 'aliases' ) {
525 $data = compact( 'aliases' );
526 } else {
527 throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" );
530 return $data;
534 * Read a JSON file containing localisation messages.
535 * @param string $fileName Name of file to read
536 * @throws MWException If there is a syntax error in the JSON file
537 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
539 public function readJSONFile( $fileName ) {
541 if ( !is_readable( $fileName ) ) {
542 return array();
545 $json = file_get_contents( $fileName );
546 if ( $json === false ) {
547 return array();
550 $data = FormatJson::decode( $json, true );
551 if ( $data === null ) {
553 throw new MWException( __METHOD__ . ": Invalid JSON file: $fileName" );
556 // Remove keys starting with '@', they're reserved for metadata and non-message data
557 foreach ( $data as $key => $unused ) {
558 if ( $key === '' || $key[0] === '@' ) {
559 unset( $data[$key] );
563 // The JSON format only supports messages, none of the other variables, so wrap the data
564 return array( 'messages' => $data );
568 * Get the compiled plural rules for a given language from the XML files.
569 * @since 1.20
570 * @param string $code
571 * @return array|null
573 public function getCompiledPluralRules( $code ) {
574 $rules = $this->getPluralRules( $code );
575 if ( $rules === null ) {
576 return null;
578 try {
579 $compiledRules = CLDRPluralRuleEvaluator::compile( $rules );
580 } catch ( CLDRPluralRuleError $e ) {
581 wfDebugLog( 'l10n', $e->getMessage() );
583 return array();
586 return $compiledRules;
590 * Get the plural rules for a given language from the XML files.
591 * Cached.
592 * @since 1.20
593 * @param string $code
594 * @return array|null
596 public function getPluralRules( $code ) {
597 if ( $this->pluralRules === null ) {
598 $this->loadPluralFiles();
600 if ( !isset( $this->pluralRules[$code] ) ) {
601 return null;
602 } else {
603 return $this->pluralRules[$code];
608 * Get the plural rule types for a given language from the XML files.
609 * Cached.
610 * @since 1.22
611 * @param string $code
612 * @return array|null
614 public function getPluralRuleTypes( $code ) {
615 if ( $this->pluralRuleTypes === null ) {
616 $this->loadPluralFiles();
618 if ( !isset( $this->pluralRuleTypes[$code] ) ) {
619 return null;
620 } else {
621 return $this->pluralRuleTypes[$code];
626 * Load the plural XML files.
628 protected function loadPluralFiles() {
629 global $IP;
630 $cldrPlural = "$IP/languages/data/plurals.xml";
631 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
632 // Load CLDR plural rules
633 $this->loadPluralFile( $cldrPlural );
634 if ( file_exists( $mwPlural ) ) {
635 // Override or extend
636 $this->loadPluralFile( $mwPlural );
641 * Load a plural XML file with the given filename, compile the relevant
642 * rules, and save the compiled rules in a process-local cache.
644 * @param string $fileName
645 * @throws MWException
647 protected function loadPluralFile( $fileName ) {
648 // Use file_get_contents instead of DOMDocument::load (T58439)
649 $xml = file_get_contents( $fileName );
650 if ( !$xml ) {
651 throw new MWException( "Unable to read plurals file $fileName" );
653 $doc = new DOMDocument;
654 $doc->loadXML( $xml );
655 $rulesets = $doc->getElementsByTagName( "pluralRules" );
656 foreach ( $rulesets as $ruleset ) {
657 $codes = $ruleset->getAttribute( 'locales' );
658 $rules = array();
659 $ruleTypes = array();
660 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
661 foreach ( $ruleElements as $elt ) {
662 $ruleType = $elt->getAttribute( 'count' );
663 if ( $ruleType === 'other' ) {
664 // Don't record "other" rules, which have an empty condition
665 continue;
667 $rules[] = $elt->nodeValue;
668 $ruleTypes[] = $ruleType;
670 foreach ( explode( ' ', $codes ) as $code ) {
671 $this->pluralRules[$code] = $rules;
672 $this->pluralRuleTypes[$code] = $ruleTypes;
678 * Read the data from the source files for a given language, and register
679 * the relevant dependencies in the $deps array. If the localisation
680 * exists, the data array is returned, otherwise false is returned.
682 * @param string $code
683 * @param array $deps
684 * @return array
686 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
687 global $IP;
689 // This reads in the PHP i18n file with non-messages l10n data
690 $fileName = Language::getMessagesFileName( $code );
691 if ( !file_exists( $fileName ) ) {
692 $data = array();
693 } else {
694 $deps[] = new FileDependency( $fileName );
695 $data = $this->readPHPFile( $fileName, 'core' );
698 # Load CLDR plural rules for JavaScript
699 $data['pluralRules'] = $this->getPluralRules( $code );
700 # And for PHP
701 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
702 # Load plural rule types
703 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
705 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
706 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
708 return $data;
712 * Merge two localisation values, a primary and a fallback, overwriting the
713 * primary value in place.
714 * @param string $key
715 * @param mixed $value
716 * @param mixed $fallbackValue
718 protected function mergeItem( $key, &$value, $fallbackValue ) {
719 if ( !is_null( $value ) ) {
720 if ( !is_null( $fallbackValue ) ) {
721 if ( in_array( $key, self::$mergeableMapKeys ) ) {
722 $value = $value + $fallbackValue;
723 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
724 $value = array_unique( array_merge( $fallbackValue, $value ) );
725 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
726 $value = array_merge_recursive( $value, $fallbackValue );
727 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
728 if ( !empty( $value['inherit'] ) ) {
729 $value = array_merge( $fallbackValue, $value );
732 if ( isset( $value['inherit'] ) ) {
733 unset( $value['inherit'] );
735 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
736 $this->mergeMagicWords( $value, $fallbackValue );
739 } else {
740 $value = $fallbackValue;
745 * @param mixed $value
746 * @param mixed $fallbackValue
748 protected function mergeMagicWords( &$value, $fallbackValue ) {
749 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
750 if ( !isset( $value[$magicName] ) ) {
751 $value[$magicName] = $fallbackInfo;
752 } else {
753 $oldSynonyms = array_slice( $fallbackInfo, 1 );
754 $newSynonyms = array_slice( $value[$magicName], 1 );
755 $synonyms = array_values( array_unique( array_merge(
756 $newSynonyms, $oldSynonyms ) ) );
757 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
763 * Given an array mapping language code to localisation value, such as is
764 * found in extension *.i18n.php files, iterate through a fallback sequence
765 * to merge the given data with an existing primary value.
767 * Returns true if any data from the extension array was used, false
768 * otherwise.
769 * @param array $codeSequence
770 * @param string $key
771 * @param mixed $value
772 * @param mixed $fallbackValue
773 * @return bool
775 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
776 $used = false;
777 foreach ( $codeSequence as $code ) {
778 if ( isset( $fallbackValue[$code] ) ) {
779 $this->mergeItem( $key, $value, $fallbackValue[$code] );
780 $used = true;
784 return $used;
788 * Gets the combined list of messages dirs from
789 * core and extensions
791 * @since 1.25
792 * @return array
794 public function getMessagesDirs() {
795 global $wgMessagesDirs, $IP;
796 return array(
797 'core' => "$IP/languages/i18n",
798 'api' => "$IP/includes/api/i18n",
799 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
800 ) + $wgMessagesDirs;
804 * Load localisation data for a given language for both core and extensions
805 * and save it to the persistent cache store and the process cache
806 * @param string $code
807 * @throws MWException
809 public function recache( $code ) {
810 global $wgExtensionMessagesFiles;
812 if ( !$code ) {
813 throw new MWException( "Invalid language code requested" );
815 $this->recachedLangs[$code] = true;
817 # Initial values
818 $initialData = array_combine(
819 self::$allKeys,
820 array_fill( 0, count( self::$allKeys ), null ) );
821 $coreData = $initialData;
822 $deps = array();
824 # Load the primary localisation from the source file
825 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
826 if ( $data === false ) {
827 wfDebug( __METHOD__ . ": no localisation file for $code, using fallback to en\n" );
828 $coreData['fallback'] = 'en';
829 } else {
830 wfDebug( __METHOD__ . ": got localisation for $code from source\n" );
832 # Merge primary localisation
833 foreach ( $data as $key => $value ) {
834 $this->mergeItem( $key, $coreData[$key], $value );
838 # Fill in the fallback if it's not there already
839 if ( is_null( $coreData['fallback'] ) ) {
840 $coreData['fallback'] = $code === 'en' ? false : 'en';
842 if ( $coreData['fallback'] === false ) {
843 $coreData['fallbackSequence'] = array();
844 } else {
845 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
846 $len = count( $coreData['fallbackSequence'] );
848 # Ensure that the sequence ends at en
849 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
850 $coreData['fallbackSequence'][] = 'en';
854 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
855 $messageDirs = $this->getMessagesDirs();
857 # Load non-JSON localisation data for extensions
858 $extensionData = array_combine(
859 $codeSequence,
860 array_fill( 0, count( $codeSequence ), $initialData ) );
861 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
862 if ( isset( $messageDirs[$extension] ) ) {
863 # This extension has JSON message data; skip the PHP shim
864 continue;
867 $data = $this->readPHPFile( $fileName, 'extension' );
868 $used = false;
870 foreach ( $data as $key => $item ) {
871 foreach ( $codeSequence as $csCode ) {
872 if ( isset( $item[$csCode] ) ) {
873 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
874 $used = true;
879 if ( $used ) {
880 $deps[] = new FileDependency( $fileName );
884 # Load the localisation data for each fallback, then merge it into the full array
885 $allData = $initialData;
886 foreach ( $codeSequence as $csCode ) {
887 $csData = $initialData;
889 # Load core messages and the extension localisations.
890 foreach ( $messageDirs as $dirs ) {
891 foreach ( (array)$dirs as $dir ) {
892 $fileName = "$dir/$csCode.json";
893 $data = $this->readJSONFile( $fileName );
895 foreach ( $data as $key => $item ) {
896 $this->mergeItem( $key, $csData[$key], $item );
899 $deps[] = new FileDependency( $fileName );
903 # Merge non-JSON extension data
904 if ( isset( $extensionData[$csCode] ) ) {
905 foreach ( $extensionData[$csCode] as $key => $item ) {
906 $this->mergeItem( $key, $csData[$key], $item );
910 if ( $csCode === $code ) {
911 # Merge core data into extension data
912 foreach ( $coreData as $key => $item ) {
913 $this->mergeItem( $key, $csData[$key], $item );
915 } else {
916 # Load the secondary localisation from the source file to
917 # avoid infinite cycles on cyclic fallbacks
918 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
919 if ( $fbData !== false ) {
920 # Only merge the keys that make sense to merge
921 foreach ( self::$allKeys as $key ) {
922 if ( !isset( $fbData[$key] ) ) {
923 continue;
926 if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) {
927 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
933 # Allow extensions an opportunity to adjust the data for this
934 # fallback
935 Hooks::run( 'LocalisationCacheRecacheFallback', array( $this, $csCode, &$csData ) );
937 # Merge the data for this fallback into the final array
938 if ( $csCode === $code ) {
939 $allData = $csData;
940 } else {
941 foreach ( self::$allKeys as $key ) {
942 if ( !isset( $csData[$key] ) ) {
943 continue;
946 if ( is_null( $allData[$key] ) || $this->isMergeableKey( $key ) ) {
947 $this->mergeItem( $key, $allData[$key], $csData[$key] );
953 # Add cache dependencies for any referenced globals
954 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
955 // $wgMessagesDirs is used in LocalisationCache::getMessagesDirs()
956 $deps['wgMessagesDirs'] = new GlobalDependency( 'wgMessagesDirs' );
957 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
959 # Add dependencies to the cache entry
960 $allData['deps'] = $deps;
962 # Replace spaces with underscores in namespace names
963 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
965 # And do the same for special page aliases. $page is an array.
966 foreach ( $allData['specialPageAliases'] as &$page ) {
967 $page = str_replace( ' ', '_', $page );
969 # Decouple the reference to prevent accidental damage
970 unset( $page );
972 # If there were no plural rules, return an empty array
973 if ( $allData['pluralRules'] === null ) {
974 $allData['pluralRules'] = array();
976 if ( $allData['compiledPluralRules'] === null ) {
977 $allData['compiledPluralRules'] = array();
979 # If there were no plural rule types, return an empty array
980 if ( $allData['pluralRuleTypes'] === null ) {
981 $allData['pluralRuleTypes'] = array();
984 # Set the list keys
985 $allData['list'] = array();
986 foreach ( self::$splitKeys as $key ) {
987 $allData['list'][$key] = array_keys( $allData[$key] );
989 # Run hooks
990 $purgeBlobs = true;
991 Hooks::run( 'LocalisationCacheRecache', array( $this, $code, &$allData, &$purgeBlobs ) );
993 if ( is_null( $allData['namespaceNames'] ) ) {
994 throw new MWException( __METHOD__ . ': Localisation data failed sanity check! ' .
995 'Check that your languages/messages/MessagesEn.php file is intact.' );
998 # Set the preload key
999 $allData['preload'] = $this->buildPreload( $allData );
1001 # Save to the process cache and register the items loaded
1002 $this->data[$code] = $allData;
1003 foreach ( $allData as $key => $item ) {
1004 $this->loadedItems[$code][$key] = true;
1007 # Save to the persistent cache
1008 $this->store->startWrite( $code );
1009 foreach ( $allData as $key => $value ) {
1010 if ( in_array( $key, self::$splitKeys ) ) {
1011 foreach ( $value as $subkey => $subvalue ) {
1012 $this->store->set( "$key:$subkey", $subvalue );
1014 } else {
1015 $this->store->set( $key, $value );
1018 $this->store->finishWrite();
1020 # Clear out the MessageBlobStore
1021 # HACK: If using a null (i.e. disabled) storage backend, we
1022 # can't write to the MessageBlobStore either
1023 if ( $purgeBlobs && !$this->store instanceof LCStoreNull ) {
1024 $blobStore = new MessageBlobStore();
1025 $blobStore->clear();
1031 * Build the preload item from the given pre-cache data.
1033 * The preload item will be loaded automatically, improving performance
1034 * for the commonly-requested items it contains.
1035 * @param array $data
1036 * @return array
1038 protected function buildPreload( $data ) {
1039 $preload = array( 'messages' => array() );
1040 foreach ( self::$preloadedKeys as $key ) {
1041 $preload[$key] = $data[$key];
1044 foreach ( $data['preloadedMessages'] as $subkey ) {
1045 if ( isset( $data['messages'][$subkey] ) ) {
1046 $subitem = $data['messages'][$subkey];
1047 } else {
1048 $subitem = null;
1050 $preload['messages'][$subkey] = $subitem;
1053 return $preload;
1057 * Unload the data for a given language from the object cache.
1058 * Reduces memory usage.
1059 * @param string $code
1061 public function unload( $code ) {
1062 unset( $this->data[$code] );
1063 unset( $this->loadedItems[$code] );
1064 unset( $this->loadedSubitems[$code] );
1065 unset( $this->initialisedLangs[$code] );
1066 unset( $this->shallowFallbacks[$code] );
1068 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
1069 if ( $fbCode === $code ) {
1070 $this->unload( $shallowCode );
1076 * Unload all data
1078 public function unloadAll() {
1079 foreach ( $this->initialisedLangs as $lang => $unused ) {
1080 $this->unload( $lang );
1085 * Disable the storage backend
1087 public function disableBackend() {
1088 $this->store = new LCStoreNull;
1089 $this->manualRecache = false;
1094 * Interface for the persistence layer of LocalisationCache.
1096 * The persistence layer is two-level hierarchical cache. The first level
1097 * is the language, the second level is the item or subitem.
1099 * Since the data for a whole language is rebuilt in one operation, it needs
1100 * to have a fast and atomic method for deleting or replacing all of the
1101 * current data for a given language. The interface reflects this bulk update
1102 * operation. Callers writing to the cache must first call startWrite(), then
1103 * will call set() a couple of thousand times, then will call finishWrite()
1104 * to commit the operation. When finishWrite() is called, the cache is
1105 * expected to delete all data previously stored for that language.
1107 * The values stored are PHP variables suitable for serialize(). Implementations
1108 * of LCStore are responsible for serializing and unserializing.
1110 interface LCStore {
1112 * Get a value.
1113 * @param string $code Language code
1114 * @param string $key Cache key
1116 function get( $code, $key );
1119 * Start a write transaction.
1120 * @param string $code Language code
1122 function startWrite( $code );
1125 * Finish a write transaction.
1127 function finishWrite();
1130 * Set a key to a given value. startWrite() must be called before this
1131 * is called, and finishWrite() must be called afterwards.
1132 * @param string $key
1133 * @param mixed $value
1135 function set( $key, $value );
1139 * LCStore implementation which uses the standard DB functions to store data.
1140 * This will work on any MediaWiki installation.
1142 class LCStoreDB implements LCStore {
1143 private $currentLang;
1144 private $writesDone = false;
1146 /** @var DatabaseBase */
1147 private $dbw;
1148 /** @var array */
1149 private $batch = array();
1151 private $readOnly = false;
1153 public function get( $code, $key ) {
1154 if ( $this->writesDone ) {
1155 $db = wfGetDB( DB_MASTER );
1156 } else {
1157 $db = wfGetDB( DB_SLAVE );
1159 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
1160 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ );
1161 if ( $row ) {
1162 return unserialize( $db->decodeBlob( $row->lc_value ) );
1163 } else {
1164 return null;
1168 public function startWrite( $code ) {
1169 if ( $this->readOnly ) {
1170 return;
1171 } elseif ( !$code ) {
1172 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1175 $this->dbw = wfGetDB( DB_MASTER );
1177 $this->currentLang = $code;
1178 $this->batch = array();
1181 public function finishWrite() {
1182 if ( $this->readOnly ) {
1183 return;
1184 } elseif ( is_null( $this->currentLang ) ) {
1185 throw new MWException( __CLASS__ . ': must call startWrite() before finishWrite()' );
1188 $this->dbw->begin( __METHOD__ );
1189 try {
1190 $this->dbw->delete( 'l10n_cache',
1191 array( 'lc_lang' => $this->currentLang ), __METHOD__ );
1192 foreach ( array_chunk( $this->batch, 500 ) as $rows ) {
1193 $this->dbw->insert( 'l10n_cache', $rows, __METHOD__ );
1195 $this->writesDone = true;
1196 } catch ( DBQueryError $e ) {
1197 if ( $this->dbw->wasReadOnlyError() ) {
1198 $this->readOnly = true; // just avoid site down time
1199 } else {
1200 throw $e;
1203 $this->dbw->commit( __METHOD__ );
1205 $this->currentLang = null;
1206 $this->batch = array();
1209 public function set( $key, $value ) {
1210 if ( $this->readOnly ) {
1211 return;
1212 } elseif ( is_null( $this->currentLang ) ) {
1213 throw new MWException( __CLASS__ . ': must call startWrite() before set()' );
1216 $this->batch[] = array(
1217 'lc_lang' => $this->currentLang,
1218 'lc_key' => $key,
1219 'lc_value' => $this->dbw->encodeBlob( serialize( $value ) ) );
1224 * LCStore implementation which stores data as a collection of CDB files in the
1225 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
1226 * will throw an exception.
1228 * Profiling indicates that on Linux, this implementation outperforms MySQL if
1229 * the directory is on a local filesystem and there is ample kernel cache
1230 * space. The performance advantage is greater when the DBA extension is
1231 * available than it is with the PHP port.
1233 * See Cdb.php and http://cr.yp.to/cdb.html
1235 class LCStoreCDB implements LCStore {
1236 /** @var CdbReader[] */
1237 private $readers;
1239 /** @var CdbWriter */
1240 private $writer;
1242 /** @var string Current language code */
1243 private $currentLang;
1245 /** @var bool|string Cache directory. False if not set */
1246 private $directory;
1248 function __construct( $conf = array() ) {
1249 global $wgCacheDirectory;
1251 if ( isset( $conf['directory'] ) ) {
1252 $this->directory = $conf['directory'];
1253 } else {
1254 $this->directory = $wgCacheDirectory;
1258 public function get( $code, $key ) {
1259 if ( !isset( $this->readers[$code] ) ) {
1260 $fileName = $this->getFileName( $code );
1262 $this->readers[$code] = false;
1263 if ( file_exists( $fileName ) ) {
1264 try {
1265 $this->readers[$code] = CdbReader::open( $fileName );
1266 } catch ( CdbException $e ) {
1267 wfDebug( __METHOD__ . ": unable to open cdb file for reading\n" );
1272 if ( !$this->readers[$code] ) {
1273 return null;
1274 } else {
1275 $value = false;
1276 try {
1277 $value = $this->readers[$code]->get( $key );
1278 } catch ( CdbException $e ) {
1279 wfDebug( __METHOD__ . ": CdbException caught, error message was "
1280 . $e->getMessage() . "\n" );
1282 if ( $value === false ) {
1283 return null;
1286 return unserialize( $value );
1290 public function startWrite( $code ) {
1291 if ( !file_exists( $this->directory ) ) {
1292 if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) {
1293 throw new MWException( "Unable to create the localisation store " .
1294 "directory \"{$this->directory}\"" );
1298 // Close reader to stop permission errors on write
1299 if ( !empty( $this->readers[$code] ) ) {
1300 $this->readers[$code]->close();
1303 try {
1304 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
1305 } catch ( CdbException $e ) {
1306 throw new MWException( $e->getMessage() );
1308 $this->currentLang = $code;
1311 public function finishWrite() {
1312 // Close the writer
1313 try {
1314 $this->writer->close();
1315 } catch ( CdbException $e ) {
1316 throw new MWException( $e->getMessage() );
1318 $this->writer = null;
1319 unset( $this->readers[$this->currentLang] );
1320 $this->currentLang = null;
1323 public function set( $key, $value ) {
1324 if ( is_null( $this->writer ) ) {
1325 throw new MWException( __CLASS__ . ': must call startWrite() before calling set()' );
1327 try {
1328 $this->writer->set( $key, serialize( $value ) );
1329 } catch ( CdbException $e ) {
1330 throw new MWException( $e->getMessage() );
1334 protected function getFileName( $code ) {
1335 if ( strval( $code ) === '' || strpos( $code, '/' ) !== false ) {
1336 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1339 return "{$this->directory}/l10n_cache-$code.cdb";
1344 * Null store backend, used to avoid DB errors during install
1346 class LCStoreNull implements LCStore {
1347 public function get( $code, $key ) {
1348 return null;
1351 public function startWrite( $code ) {
1354 public function finishWrite() {
1357 public function set( $key, $value ) {
1362 * A localisation cache optimised for loading large amounts of data for many
1363 * languages. Used by rebuildLocalisationCache.php.
1365 class LocalisationCacheBulkLoad extends LocalisationCache {
1367 * A cache of the contents of data files.
1368 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1370 private $fileCache = array();
1373 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1374 * to keep the most recently used language codes at the end of the array, and
1375 * the language codes that are ready to be deleted at the beginning.
1377 private $mruLangs = array();
1380 * Maximum number of languages that may be loaded into $this->data
1382 private $maxLoadedLangs = 10;
1385 * @param string $fileName
1386 * @param string $fileType
1387 * @return array|mixed
1389 protected function readPHPFile( $fileName, $fileType ) {
1390 $serialize = $fileType === 'core';
1391 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
1392 $data = parent::readPHPFile( $fileName, $fileType );
1394 if ( $serialize ) {
1395 $encData = serialize( $data );
1396 } else {
1397 $encData = $data;
1400 $this->fileCache[$fileName][$fileType] = $encData;
1402 return $data;
1403 } elseif ( $serialize ) {
1404 return unserialize( $this->fileCache[$fileName][$fileType] );
1405 } else {
1406 return $this->fileCache[$fileName][$fileType];
1411 * @param string $code
1412 * @param string $key
1413 * @return mixed
1415 public function getItem( $code, $key ) {
1416 unset( $this->mruLangs[$code] );
1417 $this->mruLangs[$code] = true;
1419 return parent::getItem( $code, $key );
1423 * @param string $code
1424 * @param string $key
1425 * @param string $subkey
1426 * @return mixed
1428 public function getSubitem( $code, $key, $subkey ) {
1429 unset( $this->mruLangs[$code] );
1430 $this->mruLangs[$code] = true;
1432 return parent::getSubitem( $code, $key, $subkey );
1436 * @param string $code
1438 public function recache( $code ) {
1439 parent::recache( $code );
1440 unset( $this->mruLangs[$code] );
1441 $this->mruLangs[$code] = true;
1442 $this->trimCache();
1446 * @param string $code
1448 public function unload( $code ) {
1449 unset( $this->mruLangs[$code] );
1450 parent::unload( $code );
1454 * Unload cached languages until there are less than $this->maxLoadedLangs
1456 protected function trimCache() {
1457 while ( count( $this->data ) > $this->maxLoadedLangs && count( $this->mruLangs ) ) {
1458 reset( $this->mruLangs );
1459 $code = key( $this->mruLangs );
1460 wfDebug( __METHOD__ . ": unloading $code\n" );
1461 $this->unload( $code );