3 define( 'MW_LC_VERSION', 1 );
6 * Class for caching the contents of localisation files, Messages*.php
9 * An instance of this class is available using Language::getLocalisationCache().
11 * The values retrieved from here are merged, containing items from extension
12 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
13 * zh-hans -> en ). Some common errors are corrected, for example namespace
14 * names with spaces instead of underscores, but heavyweight processing, such
15 * as grammatical transformation, is done by the caller.
17 class LocalisationCache
{
18 /** Configuration associative array */
22 * True if recaching should only be done on an explicit call to recache().
23 * Setting this reduces the overhead of cache freshness checking, which
24 * requires doing a stat() for every extension i18n file.
26 var $manualRecache = false;
29 * True to treat all files as expired until they are regenerated by this object.
31 var $forceRecache = false;
34 * The cache data. 3-d array, where the first key is the language code,
35 * the second key is the item key e.g. 'messages', and the third key is
36 * an item specific subkey index. Some items are not arrays and so for those
37 * items, there are no subkeys.
42 * The persistent store object. An instance of LCStore.
47 * A 2-d associative array, code/key, where presence indicates that the item
48 * is loaded. Value arbitrary.
50 * For split items, if set, this indicates that all of the subitems have been
53 var $loadedItems = array();
56 * A 3-d associative array, code/key/subkey, where presence indicates that
57 * the subitem is loaded. Only used for the split items, i.e. messages.
59 var $loadedSubitems = array();
62 * An array where presence of a key indicates that that language has been
63 * initialised. Initialisation includes checking for cache expiry and doing
64 * any necessary updates.
66 var $initialisedLangs = array();
69 * An array mapping non-existent pseudo-languages to fallback languages. This
70 * is filled by initShallowFallback() when data is requested from a language
71 * that lacks a Messages*.php file.
73 var $shallowFallbacks = array();
76 * An array where the keys are codes that have been recached by this instance.
78 var $recachedLangs = array();
81 * Data added by extensions using the deprecated $wgMessageCache->addMessages()
84 var $legacyData = array();
89 static public $allKeys = array(
90 'fallback', 'namespaceNames', 'mathNames', 'bookstoreList',
91 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
92 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
93 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
94 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
95 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
96 'imageFiles', 'preloadedMessages',
100 * Keys for items which consist of associative arrays, which may be merged
101 * by a fallback sequence.
103 static public $mergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
104 'dateFormats', 'defaultUserOptionOverrides', 'magicWords', 'imageFiles',
109 * Keys for items which are a numbered array.
111 static public $mergeableListKeys = array( 'extraUserToggles' );
114 * Keys for items which contain an array of arrays of equivalent aliases
115 * for each subitem. The aliases may be merged by a fallback sequence.
117 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
120 * Keys for items which contain an associative array, and may be merged if
121 * the primary value contains the special array key "inherit". That array
122 * key is removed after the first merge.
124 static public $optionalMergeKeys = array( 'bookstoreList' );
127 * Keys for items where the subitems are stored in the backend separately.
129 static public $splitKeys = array( 'messages' );
132 * Keys which are loaded automatically by initLanguage()
134 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames',
135 'defaultUserOptionOverrides' );
139 * For constructor parameters, see the documentation in DefaultSettings.php
140 * for $wgLocalisationCacheConf.
142 function __construct( $conf ) {
143 global $wgCacheDirectory;
146 $storeConf = array();
147 if ( !empty( $conf['storeClass'] ) ) {
148 $storeClass = $conf['storeClass'];
150 switch ( $conf['store'] ) {
153 $storeClass = 'LCStore_CDB';
156 $storeClass = 'LCStore_DB';
159 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
162 throw new MWException(
163 'Please set $wgLocalisationConf[\'store\'] to something sensible.' );
167 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
168 if ( !empty( $conf['storeDirectory'] ) ) {
169 $storeConf['directory'] = $conf['storeDirectory'];
172 $this->store
= new $storeClass( $storeConf );
173 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
174 if ( isset( $conf[$var] ) ) {
175 $this->$var = $conf[$var];
181 * Returns true if the given key is mergeable, that is, if it is an associative
182 * array which can be merged through a fallback sequence.
184 public function isMergeableKey( $key ) {
185 if ( !isset( $this->mergeableKeys
) ) {
186 $this->mergeableKeys
= array_flip( array_merge(
187 self
::$mergeableMapKeys,
188 self
::$mergeableListKeys,
189 self
::$mergeableAliasListKeys,
190 self
::$optionalMergeKeys
193 return isset( $this->mergeableKeys
[$key] );
199 * Warning: this may be slow for split items (messages), since it will
200 * need to fetch all of the subitems from the cache individually.
202 public function getItem( $code, $key ) {
203 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
204 wfProfileIn( __METHOD__
.'-load' );
205 $this->loadItem( $code, $key );
206 wfProfileOut( __METHOD__
.'-load' );
208 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
209 return $this->shallowFallbacks
[$code];
211 return $this->data
[$code][$key];
215 * Get a subitem, for instance a single message for a given language.
217 public function getSubitem( $code, $key, $subkey ) {
218 if ( isset( $this->legacyData
[$code][$key][$subkey] ) ) {
219 return $this->legacyData
[$code][$key][$subkey];
221 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) ) {
222 if ( isset( $this->loadedItems
[$code][$key] ) ) {
223 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
224 return $this->data
[$code][$key][$subkey];
229 wfProfileIn( __METHOD__
.'-load' );
230 $this->loadSubitem( $code, $key, $subkey );
231 wfProfileOut( __METHOD__
.'-load' );
234 return $this->data
[$code][$key][$subkey];
238 * Load an item into the cache.
240 protected function loadItem( $code, $key ) {
241 if ( !isset( $this->initialisedLangs
[$code] ) ) {
242 $this->initLanguage( $code );
244 // Check to see if initLanguage() loaded it for us
245 if ( isset( $this->loadedItems
[$code][$key] ) ) {
248 if ( isset( $this->shallowFallbacks
[$code] ) ) {
249 $this->loadItem( $this->shallowFallbacks
[$code], $key );
252 if ( in_array( $key, self
::$splitKeys ) ) {
253 $subkeyList = $this->getSubitem( $code, 'list', $key );
254 foreach ( $subkeyList as $subkey ) {
255 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
258 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
261 $this->data
[$code][$key] = $this->store
->get( $code, $key );
263 $this->loadedItems
[$code][$key] = true;
267 * Load a subitem into the cache
269 protected function loadSubitem( $code, $key, $subkey ) {
270 if ( !in_array( $key, self
::$splitKeys ) ) {
271 $this->loadItem( $code, $key );
274 if ( !isset( $this->initialisedLangs
[$code] ) ) {
275 $this->initLanguage( $code );
277 // Check to see if initLanguage() loaded it for us
278 if ( isset( $this->loadedItems
[$code][$key] )
279 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
283 if ( isset( $this->shallowFallbacks
[$code] ) ) {
284 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
287 $value = $this->store
->get( $code, "$key:$subkey" );
288 $this->data
[$code][$key][$subkey] = $value;
289 $this->loadedSubitems
[$code][$key][$subkey] = true;
293 * Returns true if the cache identified by $code is missing or expired.
295 public function isExpired( $code ) {
296 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
297 wfDebug( __METHOD__
."($code): forced reload\n" );
301 $deps = $this->store
->get( $code, 'deps' );
302 if ( $deps === null ) {
303 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
306 foreach ( $deps as $dep ) {
307 if ( $dep->isExpired() ) {
308 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
309 get_class( $dep ) . "\n" );
317 * Initialise a language in this object. Rebuild the cache if necessary.
319 protected function initLanguage( $code ) {
320 if ( isset( $this->initialisedLangs
[$code] ) ) {
323 $this->initialisedLangs
[$code] = true;
325 # Recache the data if necessary
326 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
327 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
328 $this->recache( $code );
329 } elseif ( $code === 'en' ) {
330 throw new MWException( 'MessagesEn.php is missing.' );
332 $this->initShallowFallback( $code, 'en' );
338 $preload = $this->getItem( $code, 'preload' );
339 if ( $preload === null ) {
340 if ( $this->manualRecache
) {
341 // No Messages*.php file. Do shallow fallback to en.
342 if ( $code === 'en' ) {
343 throw new MWException( 'No localisation cache found for English. ' .
344 'Please run maintenance/rebuildLocalisationCache.php.' );
346 $this->initShallowFallback( $code, 'en' );
349 throw new MWException( 'Invalid or missing localisation cache.' );
352 $this->data
[$code] = $preload;
353 foreach ( $preload as $key => $item ) {
354 if ( in_array( $key, self
::$splitKeys ) ) {
355 foreach ( $item as $subkey => $subitem ) {
356 $this->loadedSubitems
[$code][$key][$subkey] = true;
359 $this->loadedItems
[$code][$key] = true;
365 * Create a fallback from one language to another, without creating a
366 * complete persistent cache.
368 public function initShallowFallback( $primaryCode, $fallbackCode ) {
369 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
370 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
371 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
372 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
376 * Read a PHP file containing localisation data.
378 protected function readPHPFile( $_fileName, $_fileType ) {
379 // Disable APC caching
380 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
381 include( $_fileName );
382 ini_set( 'apc.cache_by_default', $_apcEnabled );
384 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
385 $data = compact( self
::$allKeys );
386 } elseif ( $_fileType == 'aliases' ) {
387 $data = compact( 'aliases' );
389 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
395 * Merge two localisation values, a primary and a fallback, overwriting the
396 * primary value in place.
398 protected function mergeItem( $key, &$value, $fallbackValue ) {
399 if ( !is_null( $value ) ) {
400 if ( !is_null( $fallbackValue ) ) {
401 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
402 $value = $value +
$fallbackValue;
403 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
404 $value = array_unique( array_merge( $fallbackValue, $value ) );
405 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
406 $value = array_merge_recursive( $value, $fallbackValue );
407 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
408 if ( !empty( $value['inherit'] ) ) {
409 $value = array_merge( $fallbackValue, $value );
411 if ( isset( $value['inherit'] ) ) {
412 unset( $value['inherit'] );
417 $value = $fallbackValue;
422 * Given an array mapping language code to localisation value, such as is
423 * found in extension *.i18n.php files, iterate through a fallback sequence
424 * to merge the given data with an existing primary value.
426 * Returns true if any data from the extension array was used, false
429 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
431 foreach ( $codeSequence as $code ) {
432 if ( isset( $fallbackValue[$code] ) ) {
433 $this->mergeItem( $key, $value, $fallbackValue[$code] );
441 * Load localisation data for a given language for both core and extensions
442 * and save it to the persistent cache store and the process cache
444 public function recache( $code ) {
445 static $recursionGuard = array();
446 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
447 wfProfileIn( __METHOD__
);
450 throw new MWException( "Invalid language code requested" );
452 $this->recachedLangs
[$code] = true;
455 $initialData = array_combine(
457 array_fill( 0, count( self
::$allKeys ), null ) );
458 $coreData = $initialData;
461 # Load the primary localisation from the source file
462 $fileName = Language
::getMessagesFileName( $code );
463 if ( !file_exists( $fileName ) ) {
464 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
465 $coreData['fallback'] = 'en';
467 $deps[] = new FileDependency( $fileName );
468 $data = $this->readPHPFile( $fileName, 'core' );
469 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
471 # Merge primary localisation
472 foreach ( $data as $key => $value ) {
473 $this->mergeItem( $key, $coreData[$key], $value );
477 # Fill in the fallback if it's not there already
478 if ( is_null( $coreData['fallback'] ) ) {
479 $coreData['fallback'] = $code === 'en' ?
false : 'en';
482 if ( $coreData['fallback'] !== false ) {
483 # Guard against circular references
484 if ( isset( $recursionGuard[$code] ) ) {
485 throw new MWException( "Error: Circular fallback reference in language code $code" );
487 $recursionGuard[$code] = true;
489 # Load the fallback localisation item by item and merge it
490 $deps = array_merge( $deps, $this->getItem( $coreData['fallback'], 'deps' ) );
491 foreach ( self
::$allKeys as $key ) {
492 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
493 $fallbackValue = $this->getItem( $coreData['fallback'], $key );
494 $this->mergeItem( $key, $coreData[$key], $fallbackValue );
497 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
498 array_unshift( $fallbackSequence, $coreData['fallback'] );
499 $coreData['fallbackSequence'] = $fallbackSequence;
500 unset( $recursionGuard[$code] );
502 $coreData['fallbackSequence'] = array();
504 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
506 # Load the extension localisations
507 # This is done after the core because we know the fallback sequence now.
508 # But it has a higher precedence for merging so that we can support things
509 # like site-specific message overrides.
510 $allData = $initialData;
511 foreach ( $wgExtensionMessagesFiles as $fileName ) {
512 $data = $this->readPHPFile( $fileName, 'extension' );
514 foreach ( $data as $key => $item ) {
515 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
520 $deps[] = new FileDependency( $fileName );
524 # Load deprecated $wgExtensionAliasesFiles
525 foreach ( $wgExtensionAliasesFiles as $fileName ) {
526 $data = $this->readPHPFile( $fileName, 'aliases' );
527 if ( !isset( $data['aliases'] ) ) {
530 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
531 $allData['specialPageAliases'], $data['aliases'] );
533 $deps[] = new FileDependency( $fileName );
537 # Merge core data into extension data
538 foreach ( $coreData as $key => $item ) {
539 $this->mergeItem( $key, $allData[$key], $item );
542 # Add cache dependencies for any referenced globals
543 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
544 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
545 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
547 # Add dependencies to the cache entry
548 $allData['deps'] = $deps;
550 # Replace spaces with underscores in namespace names
551 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
553 # And do the same for special page aliases. $page is an array.
554 foreach ( $allData['specialPageAliases'] as &$page ) {
555 $page = str_replace( ' ', '_', $page );
557 # Decouple the reference to prevent accidental damage
560 # Fix broken defaultUserOptionOverrides
561 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
562 $allData['defaultUserOptionOverrides'] = array();
565 # Set the preload key
566 $allData['preload'] = $this->buildPreload( $allData );
569 $allData['list'] = array();
570 foreach ( self
::$splitKeys as $key ) {
571 $allData['list'][$key] = array_keys( $allData[$key] );
575 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
577 if ( is_null( $allData['defaultUserOptionOverrides'] ) ) {
578 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
579 'Check that your languages/messages/MessagesEn.php file is intact.' );
582 # Save to the process cache and register the items loaded
583 $this->data
[$code] = $allData;
584 foreach ( $allData as $key => $item ) {
585 $this->loadedItems
[$code][$key] = true;
588 # Save to the persistent cache
589 $this->store
->startWrite( $code );
590 foreach ( $allData as $key => $value ) {
591 if ( in_array( $key, self
::$splitKeys ) ) {
592 foreach ( $value as $subkey => $subvalue ) {
593 $this->store
->set( "$key:$subkey", $subvalue );
596 $this->store
->set( $key, $value );
599 $this->store
->finishWrite();
601 wfProfileOut( __METHOD__
);
605 * Build the preload item from the given pre-cache data.
607 * The preload item will be loaded automatically, improving performance
608 * for the commonly-requested items it contains.
610 protected function buildPreload( $data ) {
611 $preload = array( 'messages' => array() );
612 foreach ( self
::$preloadedKeys as $key ) {
613 $preload[$key] = $data[$key];
615 foreach ( $data['preloadedMessages'] as $subkey ) {
616 if ( isset( $data['messages'][$subkey] ) ) {
617 $subitem = $data['messages'][$subkey];
621 $preload['messages'][$subkey] = $subitem;
627 * Unload the data for a given language from the object cache.
628 * Reduces memory usage.
630 public function unload( $code ) {
631 unset( $this->data
[$code] );
632 unset( $this->loadedItems
[$code] );
633 unset( $this->loadedSubitems
[$code] );
634 unset( $this->initialisedLangs
[$code] );
635 // We don't unload legacyData because there's no way to get it back
636 // again, it's not really a cache
637 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
638 if ( $fbCode === $code ) {
639 $this->unload( $shallowCode );
647 public function unloadAll() {
648 foreach ( $this->initialisedLangs
as $lang => $unused ) {
649 $this->unload( $lang );
654 * Add messages to the cache, from an extension that has not yet been
655 * migrated to $wgExtensionMessages or the LocalisationCacheRecache hook.
656 * Called by deprecated function $wgMessageCache->addMessages().
658 public function addLegacyMessages( $messages ) {
659 foreach ( $messages as $lang => $langMessages ) {
660 if ( isset( $this->legacyData
[$lang]['messages'] ) ) {
661 $this->legacyData
[$lang]['messages'] =
662 $langMessages +
$this->legacyData
[$lang]['messages'];
664 $this->legacyData
[$lang]['messages'] = $langMessages;
670 * Disable the storage backend
672 public function disableBackend() {
673 $this->store
= new LCStore_Null
;
674 $this->manualRecache
= false;
679 * Interface for the persistence layer of LocalisationCache.
681 * The persistence layer is two-level hierarchical cache. The first level
682 * is the language, the second level is the item or subitem.
684 * Since the data for a whole language is rebuilt in one operation, it needs
685 * to have a fast and atomic method for deleting or replacing all of the
686 * current data for a given language. The interface reflects this bulk update
687 * operation. Callers writing to the cache must first call startWrite(), then
688 * will call set() a couple of thousand times, then will call finishWrite()
689 * to commit the operation. When finishWrite() is called, the cache is
690 * expected to delete all data previously stored for that language.
692 * The values stored are PHP variables suitable for serialize(). Implementations
693 * of LCStore are responsible for serializing and unserializing.
698 * @param $code Language code
699 * @param $key Cache key
701 public function get( $code, $key );
704 * Start a write transaction.
705 * @param $code Language code
707 public function startWrite( $code );
710 * Finish a write transaction.
712 public function finishWrite();
715 * Set a key to a given value. startWrite() must be called before this
716 * is called, and finishWrite() must be called afterwards.
718 public function set( $key, $value );
723 * LCStore implementation which uses the standard DB functions to store data.
724 * This will work on any MediaWiki installation.
726 class LCStore_DB
implements LCStore
{
728 var $writesDone = false;
730 var $readOnly = false;
732 public function get( $code, $key ) {
733 if ( $this->writesDone
) {
734 $db = wfGetDB( DB_MASTER
);
736 $db = wfGetDB( DB_SLAVE
);
738 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
739 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
741 return unserialize( $row->lc_value
);
747 public function startWrite( $code ) {
748 if ( $this->readOnly
) {
752 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
754 $this->dbw
= wfGetDB( DB_MASTER
);
757 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
758 } catch ( DBQueryError
$e ) {
759 if ( $this->dbw
->wasReadOnlyError() ) {
760 $this->readOnly
= true;
761 $this->dbw
->rollback();
762 $this->dbw
->ignoreErrors( false );
768 $this->currentLang
= $code;
769 $this->batch
= array();
772 public function finishWrite() {
773 if ( $this->readOnly
) {
776 if ( $this->batch
) {
777 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
779 $this->dbw
->commit();
780 $this->currentLang
= null;
782 $this->batch
= array();
783 $this->writesDone
= true;
786 public function set( $key, $value ) {
787 if ( $this->readOnly
) {
790 if ( is_null( $this->currentLang
) ) {
791 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
793 $this->batch
[] = array(
794 'lc_lang' => $this->currentLang
,
796 'lc_value' => serialize( $value ) );
797 if ( count( $this->batch
) >= 100 ) {
798 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
799 $this->batch
= array();
805 * LCStore implementation which stores data as a collection of CDB files in the
806 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
807 * will throw an exception.
809 * Profiling indicates that on Linux, this implementation outperforms MySQL if
810 * the directory is on a local filesystem and there is ample kernel cache
811 * space. The performance advantage is greater when the DBA extension is
812 * available than it is with the PHP port.
814 * See Cdb.php and http://cr.yp.to/cdb.html
816 class LCStore_CDB
implements LCStore
{
817 var $readers, $writer, $currentLang, $directory;
819 function __construct( $conf = array() ) {
820 global $wgCacheDirectory;
821 if ( isset( $conf['directory'] ) ) {
822 $this->directory
= $conf['directory'];
824 $this->directory
= $wgCacheDirectory;
828 public function get( $code, $key ) {
829 if ( !isset( $this->readers
[$code] ) ) {
830 $fileName = $this->getFileName( $code );
831 if ( !file_exists( $fileName ) ) {
832 $this->readers
[$code] = false;
834 $this->readers
[$code] = CdbReader
::open( $fileName );
837 if ( !$this->readers
[$code] ) {
840 $value = $this->readers
[$code]->get( $key );
841 if ( $value === false ) {
844 return unserialize( $value );
848 public function startWrite( $code ) {
849 if ( !file_exists( $this->directory
) ) {
850 if ( !wfMkdirParents( $this->directory
) ) {
851 throw new MWException( "Unable to create the localisation store " .
852 "directory \"{$this->directory}\"" );
855 // Close reader to stop permission errors on write
856 if( !empty($this->readers
[$code]) ) {
857 $this->readers
[$code]->close();
859 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
860 $this->currentLang
= $code;
863 public function finishWrite() {
865 $this->writer
->close();
866 $this->writer
= null;
867 unset( $this->readers
[$this->currentLang
] );
868 $this->currentLang
= null;
871 public function set( $key, $value ) {
872 if ( is_null( $this->writer
) ) {
873 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
875 $this->writer
->set( $key, serialize( $value ) );
878 protected function getFileName( $code ) {
879 if ( !$code ||
strpos( $code, '/' ) !== false ) {
880 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
882 return "{$this->directory}/l10n_cache-$code.cdb";
887 * Null store backend, used to avoid DB errors during install
889 class LCStore_Null
implements LCStore
{
890 public function get( $code, $key ) {
894 public function startWrite( $code ) {}
895 public function finishWrite() {}
896 public function set( $key, $value ) {}
900 * A localisation cache optimised for loading large amounts of data for many
901 * languages. Used by rebuildLocalisationCache.php.
903 class LocalisationCache_BulkLoad
extends LocalisationCache
{
905 * A cache of the contents of data files.
906 * Core files are serialized to avoid using ~1GB of RAM during a recache.
908 var $fileCache = array();
911 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
912 * to keep the most recently used language codes at the end of the array, and
913 * the language codes that are ready to be deleted at the beginning.
915 var $mruLangs = array();
918 * Maximum number of languages that may be loaded into $this->data
920 var $maxLoadedLangs = 10;
922 protected function readPHPFile( $fileName, $fileType ) {
923 $serialize = $fileType === 'core';
924 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
925 $data = parent
::readPHPFile( $fileName, $fileType );
927 $encData = serialize( $data );
931 $this->fileCache
[$fileName][$fileType] = $encData;
933 } elseif ( $serialize ) {
934 return unserialize( $this->fileCache
[$fileName][$fileType] );
936 return $this->fileCache
[$fileName][$fileType];
940 public function getItem( $code, $key ) {
941 unset( $this->mruLangs
[$code] );
942 $this->mruLangs
[$code] = true;
943 return parent
::getItem( $code, $key );
946 public function getSubitem( $code, $key, $subkey ) {
947 unset( $this->mruLangs
[$code] );
948 $this->mruLangs
[$code] = true;
949 return parent
::getSubitem( $code, $key, $subkey );
952 public function recache( $code ) {
953 parent
::recache( $code );
954 unset( $this->mruLangs
[$code] );
955 $this->mruLangs
[$code] = true;
959 public function unload( $code ) {
960 unset( $this->mruLangs
[$code] );
961 parent
::unload( $code );
965 * Unload cached languages until there are less than $this->maxLoadedLangs
967 protected function trimCache() {
968 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
969 reset( $this->mruLangs
);
970 $code = key( $this->mruLangs
);
971 wfDebug( __METHOD__
.": unloading $code\n" );
972 $this->unload( $code );