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();
83 static public $allKeys = array(
84 'fallback', 'namespaceNames', 'mathNames', 'bookstoreList',
85 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
86 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
87 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
88 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
89 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
90 'imageFiles', 'preloadedMessages',
94 * Keys for items which consist of associative arrays, which may be merged
95 * by a fallback sequence.
97 static public $mergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
98 'dateFormats', 'defaultUserOptionOverrides', 'magicWords', 'imageFiles',
103 * Keys for items which are a numbered array.
105 static public $mergeableListKeys = array( 'extraUserToggles' );
108 * Keys for items which contain an array of arrays of equivalent aliases
109 * for each subitem. The aliases may be merged by a fallback sequence.
111 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
114 * Keys for items which contain an associative array, and may be merged if
115 * the primary value contains the special array key "inherit". That array
116 * key is removed after the first merge.
118 static public $optionalMergeKeys = array( 'bookstoreList' );
121 * Keys for items where the subitems are stored in the backend separately.
123 static public $splitKeys = array( 'messages' );
126 * Keys which are loaded automatically by initLanguage()
128 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames',
129 'defaultUserOptionOverrides' );
133 * For constructor parameters, see the documentation in DefaultSettings.php
134 * for $wgLocalisationCacheConf.
136 function __construct( $conf ) {
137 global $wgCacheDirectory;
140 $storeConf = array();
141 if ( !empty( $conf['storeClass'] ) ) {
142 $storeClass = $conf['storeClass'];
144 switch ( $conf['store'] ) {
147 $storeClass = 'LCStore_CDB';
150 $storeClass = 'LCStore_DB';
153 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
156 throw new MWException(
157 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
161 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
162 if ( !empty( $conf['storeDirectory'] ) ) {
163 $storeConf['directory'] = $conf['storeDirectory'];
166 $this->store
= new $storeClass( $storeConf );
167 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
168 if ( isset( $conf[$var] ) ) {
169 $this->$var = $conf[$var];
175 * Returns true if the given key is mergeable, that is, if it is an associative
176 * array which can be merged through a fallback sequence.
178 public function isMergeableKey( $key ) {
179 if ( !isset( $this->mergeableKeys
) ) {
180 $this->mergeableKeys
= array_flip( array_merge(
181 self
::$mergeableMapKeys,
182 self
::$mergeableListKeys,
183 self
::$mergeableAliasListKeys,
184 self
::$optionalMergeKeys
187 return isset( $this->mergeableKeys
[$key] );
193 * Warning: this may be slow for split items (messages), since it will
194 * need to fetch all of the subitems from the cache individually.
196 public function getItem( $code, $key ) {
197 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
198 wfProfileIn( __METHOD__
.'-load' );
199 $this->loadItem( $code, $key );
200 wfProfileOut( __METHOD__
.'-load' );
202 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
203 return $this->shallowFallbacks
[$code];
205 return $this->data
[$code][$key];
209 * Get a subitem, for instance a single message for a given language.
211 public function getSubitem( $code, $key, $subkey ) {
212 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] )
213 && !isset( $this->loadedItems
[$code][$key] ) )
215 wfProfileIn( __METHOD__
.'-load' );
216 $this->loadSubitem( $code, $key, $subkey );
217 wfProfileOut( __METHOD__
.'-load' );
219 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
220 return $this->data
[$code][$key][$subkey];
227 * Get the list of subitem keys for a given item.
229 * This is faster than array_keys($lc->getItem(...)) for the items listed in
232 * Will return null if the item is not found, or false if the item is not an
235 public function getSubitemList( $code, $key ) {
236 if ( in_array( $key, self
::$splitKeys ) ) {
237 return $this->getSubitem( $code, 'list', $key );
239 $item = $this->getItem( $code, $key );
240 if ( is_array( $item ) ) {
241 return array_keys( $item );
249 * Load an item into the cache.
251 protected function loadItem( $code, $key ) {
252 if ( !isset( $this->initialisedLangs
[$code] ) ) {
253 $this->initLanguage( $code );
255 // Check to see if initLanguage() loaded it for us
256 if ( isset( $this->loadedItems
[$code][$key] ) ) {
259 if ( isset( $this->shallowFallbacks
[$code] ) ) {
260 $this->loadItem( $this->shallowFallbacks
[$code], $key );
263 if ( in_array( $key, self
::$splitKeys ) ) {
264 $subkeyList = $this->getSubitem( $code, 'list', $key );
265 foreach ( $subkeyList as $subkey ) {
266 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
269 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
272 $this->data
[$code][$key] = $this->store
->get( $code, $key );
274 $this->loadedItems
[$code][$key] = true;
278 * Load a subitem into the cache
280 protected function loadSubitem( $code, $key, $subkey ) {
281 if ( !in_array( $key, self
::$splitKeys ) ) {
282 $this->loadItem( $code, $key );
285 if ( !isset( $this->initialisedLangs
[$code] ) ) {
286 $this->initLanguage( $code );
288 // Check to see if initLanguage() loaded it for us
289 if ( isset( $this->loadedItems
[$code][$key] )
290 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
294 if ( isset( $this->shallowFallbacks
[$code] ) ) {
295 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
298 $value = $this->store
->get( $code, "$key:$subkey" );
299 $this->data
[$code][$key][$subkey] = $value;
300 $this->loadedSubitems
[$code][$key][$subkey] = true;
304 * Returns true if the cache identified by $code is missing or expired.
306 public function isExpired( $code ) {
307 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
308 wfDebug( __METHOD__
."($code): forced reload\n" );
312 $deps = $this->store
->get( $code, 'deps' );
313 if ( $deps === null ) {
314 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
317 foreach ( $deps as $dep ) {
318 // Because we're unserializing stuff from cache, we
319 // could receive objects of classes that don't exist
320 // anymore (e.g. uninstalled extensions)
321 // When this happens, always expire the cache
322 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
323 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
324 get_class( $dep ) . "\n" );
332 * Initialise a language in this object. Rebuild the cache if necessary.
334 protected function initLanguage( $code ) {
335 if ( isset( $this->initialisedLangs
[$code] ) ) {
338 $this->initialisedLangs
[$code] = true;
340 # Recache the data if necessary
341 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
342 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
343 $this->recache( $code );
344 } elseif ( $code === 'en' ) {
345 throw new MWException( 'MessagesEn.php is missing.' );
347 $this->initShallowFallback( $code, 'en' );
353 $preload = $this->getItem( $code, 'preload' );
354 if ( $preload === null ) {
355 if ( $this->manualRecache
) {
356 // No Messages*.php file. Do shallow fallback to en.
357 if ( $code === 'en' ) {
358 throw new MWException( 'No localisation cache found for English. ' .
359 'Please run maintenance/rebuildLocalisationCache.php.' );
361 $this->initShallowFallback( $code, 'en' );
364 throw new MWException( 'Invalid or missing localisation cache.' );
367 $this->data
[$code] = $preload;
368 foreach ( $preload as $key => $item ) {
369 if ( in_array( $key, self
::$splitKeys ) ) {
370 foreach ( $item as $subkey => $subitem ) {
371 $this->loadedSubitems
[$code][$key][$subkey] = true;
374 $this->loadedItems
[$code][$key] = true;
380 * Create a fallback from one language to another, without creating a
381 * complete persistent cache.
383 public function initShallowFallback( $primaryCode, $fallbackCode ) {
384 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
385 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
386 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
387 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
391 * Read a PHP file containing localisation data.
393 protected function readPHPFile( $_fileName, $_fileType ) {
394 // Disable APC caching
395 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
396 include( $_fileName );
397 ini_set( 'apc.cache_by_default', $_apcEnabled );
399 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
400 $data = compact( self
::$allKeys );
401 } elseif ( $_fileType == 'aliases' ) {
402 $data = compact( 'aliases' );
404 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
410 * Merge two localisation values, a primary and a fallback, overwriting the
411 * primary value in place.
413 protected function mergeItem( $key, &$value, $fallbackValue ) {
414 if ( !is_null( $value ) ) {
415 if ( !is_null( $fallbackValue ) ) {
416 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
417 $value = $value +
$fallbackValue;
418 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
419 $value = array_unique( array_merge( $fallbackValue, $value ) );
420 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
421 $value = array_merge_recursive( $value, $fallbackValue );
422 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
423 if ( !empty( $value['inherit'] ) ) {
424 $value = array_merge( $fallbackValue, $value );
426 if ( isset( $value['inherit'] ) ) {
427 unset( $value['inherit'] );
432 $value = $fallbackValue;
437 * Given an array mapping language code to localisation value, such as is
438 * found in extension *.i18n.php files, iterate through a fallback sequence
439 * to merge the given data with an existing primary value.
441 * Returns true if any data from the extension array was used, false
444 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
446 foreach ( $codeSequence as $code ) {
447 if ( isset( $fallbackValue[$code] ) ) {
448 $this->mergeItem( $key, $value, $fallbackValue[$code] );
456 * Load localisation data for a given language for both core and extensions
457 * and save it to the persistent cache store and the process cache
459 public function recache( $code ) {
460 static $recursionGuard = array();
461 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
462 wfProfileIn( __METHOD__
);
465 throw new MWException( "Invalid language code requested" );
467 $this->recachedLangs
[$code] = true;
470 $initialData = array_combine(
472 array_fill( 0, count( self
::$allKeys ), null ) );
473 $coreData = $initialData;
476 # Load the primary localisation from the source file
477 $fileName = Language
::getMessagesFileName( $code );
478 if ( !file_exists( $fileName ) ) {
479 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
480 $coreData['fallback'] = 'en';
482 $deps[] = new FileDependency( $fileName );
483 $data = $this->readPHPFile( $fileName, 'core' );
484 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
486 # Merge primary localisation
487 foreach ( $data as $key => $value ) {
488 $this->mergeItem( $key, $coreData[$key], $value );
492 # Fill in the fallback if it's not there already
493 if ( is_null( $coreData['fallback'] ) ) {
494 $coreData['fallback'] = $code === 'en' ?
false : 'en';
497 if ( $coreData['fallback'] !== false ) {
498 # Guard against circular references
499 if ( isset( $recursionGuard[$code] ) ) {
500 throw new MWException( "Error: Circular fallback reference in language code $code" );
502 $recursionGuard[$code] = true;
504 # Load the fallback localisation item by item and merge it
505 $deps = array_merge( $deps, $this->getItem( $coreData['fallback'], 'deps' ) );
506 foreach ( self
::$allKeys as $key ) {
507 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
508 $fallbackValue = $this->getItem( $coreData['fallback'], $key );
509 $this->mergeItem( $key, $coreData[$key], $fallbackValue );
512 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
513 array_unshift( $fallbackSequence, $coreData['fallback'] );
514 $coreData['fallbackSequence'] = $fallbackSequence;
515 unset( $recursionGuard[$code] );
517 $coreData['fallbackSequence'] = array();
519 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
521 # Load the extension localisations
522 # This is done after the core because we know the fallback sequence now.
523 # But it has a higher precedence for merging so that we can support things
524 # like site-specific message overrides.
525 $allData = $initialData;
526 foreach ( $wgExtensionMessagesFiles as $fileName ) {
527 $data = $this->readPHPFile( $fileName, 'extension' );
529 foreach ( $data as $key => $item ) {
530 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
535 $deps[] = new FileDependency( $fileName );
539 # Load deprecated $wgExtensionAliasesFiles
540 foreach ( $wgExtensionAliasesFiles as $fileName ) {
541 $data = $this->readPHPFile( $fileName, 'aliases' );
542 if ( !isset( $data['aliases'] ) ) {
545 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
546 $allData['specialPageAliases'], $data['aliases'] );
548 $deps[] = new FileDependency( $fileName );
552 # Merge core data into extension data
553 foreach ( $coreData as $key => $item ) {
554 $this->mergeItem( $key, $allData[$key], $item );
557 # Add cache dependencies for any referenced globals
558 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
559 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
560 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
562 # Add dependencies to the cache entry
563 $allData['deps'] = $deps;
565 # Replace spaces with underscores in namespace names
566 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
568 # And do the same for special page aliases. $page is an array.
569 foreach ( $allData['specialPageAliases'] as &$page ) {
570 $page = str_replace( ' ', '_', $page );
572 # Decouple the reference to prevent accidental damage
575 # Fix broken defaultUserOptionOverrides
576 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
577 $allData['defaultUserOptionOverrides'] = array();
581 $allData['list'] = array();
582 foreach ( self
::$splitKeys as $key ) {
583 $allData['list'][$key] = array_keys( $allData[$key] );
587 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
589 if ( is_null( $allData['defaultUserOptionOverrides'] ) ) {
590 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
591 'Check that your languages/messages/MessagesEn.php file is intact.' );
594 # Set the preload key
595 $allData['preload'] = $this->buildPreload( $allData );
597 # Save to the process cache and register the items loaded
598 $this->data
[$code] = $allData;
599 foreach ( $allData as $key => $item ) {
600 $this->loadedItems
[$code][$key] = true;
603 # Save to the persistent cache
604 $this->store
->startWrite( $code );
605 foreach ( $allData as $key => $value ) {
606 if ( in_array( $key, self
::$splitKeys ) ) {
607 foreach ( $value as $subkey => $subvalue ) {
608 $this->store
->set( "$key:$subkey", $subvalue );
611 $this->store
->set( $key, $value );
614 $this->store
->finishWrite();
616 # Clear out the MessageBlobStore
617 # HACK: If using a null (i.e. disabled) storage backend, we
618 # can't write to the MessageBlobStore either
619 if ( !$this->store
instanceof LCStore_Null
) {
620 MessageBlobStore
::clear();
623 wfProfileOut( __METHOD__
);
627 * Build the preload item from the given pre-cache data.
629 * The preload item will be loaded automatically, improving performance
630 * for the commonly-requested items it contains.
632 protected function buildPreload( $data ) {
633 $preload = array( 'messages' => array() );
634 foreach ( self
::$preloadedKeys as $key ) {
635 $preload[$key] = $data[$key];
637 foreach ( $data['preloadedMessages'] as $subkey ) {
638 if ( isset( $data['messages'][$subkey] ) ) {
639 $subitem = $data['messages'][$subkey];
643 $preload['messages'][$subkey] = $subitem;
649 * Unload the data for a given language from the object cache.
650 * Reduces memory usage.
652 public function unload( $code ) {
653 unset( $this->data
[$code] );
654 unset( $this->loadedItems
[$code] );
655 unset( $this->loadedSubitems
[$code] );
656 unset( $this->initialisedLangs
[$code] );
657 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
658 if ( $fbCode === $code ) {
659 $this->unload( $shallowCode );
667 public function unloadAll() {
668 foreach ( $this->initialisedLangs
as $lang => $unused ) {
669 $this->unload( $lang );
674 * Disable the storage backend
676 public function disableBackend() {
677 $this->store
= new LCStore_Null
;
678 $this->manualRecache
= false;
683 * Interface for the persistence layer of LocalisationCache.
685 * The persistence layer is two-level hierarchical cache. The first level
686 * is the language, the second level is the item or subitem.
688 * Since the data for a whole language is rebuilt in one operation, it needs
689 * to have a fast and atomic method for deleting or replacing all of the
690 * current data for a given language. The interface reflects this bulk update
691 * operation. Callers writing to the cache must first call startWrite(), then
692 * will call set() a couple of thousand times, then will call finishWrite()
693 * to commit the operation. When finishWrite() is called, the cache is
694 * expected to delete all data previously stored for that language.
696 * The values stored are PHP variables suitable for serialize(). Implementations
697 * of LCStore are responsible for serializing and unserializing.
702 * @param $code Language code
703 * @param $key Cache key
705 function get( $code, $key );
708 * Start a write transaction.
709 * @param $code Language code
711 function startWrite( $code );
714 * Finish a write transaction.
716 function finishWrite();
719 * Set a key to a given value. startWrite() must be called before this
720 * is called, and finishWrite() must be called afterwards.
722 function set( $key, $value );
727 * LCStore implementation which uses the standard DB functions to store data.
728 * This will work on any MediaWiki installation.
730 class LCStore_DB
implements LCStore
{
732 var $writesDone = false;
734 var $readOnly = false;
736 public function get( $code, $key ) {
737 if ( $this->writesDone
) {
738 $db = wfGetDB( DB_MASTER
);
740 $db = wfGetDB( DB_SLAVE
);
742 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
743 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
745 return unserialize( $row->lc_value
);
751 public function startWrite( $code ) {
752 if ( $this->readOnly
) {
756 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
758 $this->dbw
= wfGetDB( DB_MASTER
);
761 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
762 } catch ( DBQueryError
$e ) {
763 if ( $this->dbw
->wasReadOnlyError() ) {
764 $this->readOnly
= true;
765 $this->dbw
->rollback();
766 $this->dbw
->ignoreErrors( false );
772 $this->currentLang
= $code;
773 $this->batch
= array();
776 public function finishWrite() {
777 if ( $this->readOnly
) {
780 if ( $this->batch
) {
781 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
783 $this->dbw
->commit();
784 $this->currentLang
= null;
786 $this->batch
= array();
787 $this->writesDone
= true;
790 public function set( $key, $value ) {
791 if ( $this->readOnly
) {
794 if ( is_null( $this->currentLang
) ) {
795 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
797 $this->batch
[] = array(
798 'lc_lang' => $this->currentLang
,
800 'lc_value' => serialize( $value ) );
801 if ( count( $this->batch
) >= 100 ) {
802 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
803 $this->batch
= array();
809 * LCStore implementation which stores data as a collection of CDB files in the
810 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
811 * will throw an exception.
813 * Profiling indicates that on Linux, this implementation outperforms MySQL if
814 * the directory is on a local filesystem and there is ample kernel cache
815 * space. The performance advantage is greater when the DBA extension is
816 * available than it is with the PHP port.
818 * See Cdb.php and http://cr.yp.to/cdb.html
820 class LCStore_CDB
implements LCStore
{
821 var $readers, $writer, $currentLang, $directory;
823 function __construct( $conf = array() ) {
824 global $wgCacheDirectory;
825 if ( isset( $conf['directory'] ) ) {
826 $this->directory
= $conf['directory'];
828 $this->directory
= $wgCacheDirectory;
832 public function get( $code, $key ) {
833 if ( !isset( $this->readers
[$code] ) ) {
834 $fileName = $this->getFileName( $code );
835 if ( !file_exists( $fileName ) ) {
836 $this->readers
[$code] = false;
838 $this->readers
[$code] = CdbReader
::open( $fileName );
841 if ( !$this->readers
[$code] ) {
844 $value = $this->readers
[$code]->get( $key );
845 if ( $value === false ) {
848 return unserialize( $value );
852 public function startWrite( $code ) {
853 if ( !file_exists( $this->directory
) ) {
854 if ( !wfMkdirParents( $this->directory
) ) {
855 throw new MWException( "Unable to create the localisation store " .
856 "directory \"{$this->directory}\"" );
859 // Close reader to stop permission errors on write
860 if( !empty($this->readers
[$code]) ) {
861 $this->readers
[$code]->close();
863 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
864 $this->currentLang
= $code;
867 public function finishWrite() {
869 $this->writer
->close();
870 $this->writer
= null;
871 unset( $this->readers
[$this->currentLang
] );
872 $this->currentLang
= null;
875 public function set( $key, $value ) {
876 if ( is_null( $this->writer
) ) {
877 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
879 $this->writer
->set( $key, serialize( $value ) );
882 protected function getFileName( $code ) {
883 if ( !$code ||
strpos( $code, '/' ) !== false ) {
884 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
886 return "{$this->directory}/l10n_cache-$code.cdb";
891 * Null store backend, used to avoid DB errors during install
893 class LCStore_Null
implements LCStore
{
894 public function get( $code, $key ) {
898 public function startWrite( $code ) {}
899 public function finishWrite() {}
900 public function set( $key, $value ) {}
904 * A localisation cache optimised for loading large amounts of data for many
905 * languages. Used by rebuildLocalisationCache.php.
907 class LocalisationCache_BulkLoad
extends LocalisationCache
{
909 * A cache of the contents of data files.
910 * Core files are serialized to avoid using ~1GB of RAM during a recache.
912 var $fileCache = array();
915 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
916 * to keep the most recently used language codes at the end of the array, and
917 * the language codes that are ready to be deleted at the beginning.
919 var $mruLangs = array();
922 * Maximum number of languages that may be loaded into $this->data
924 var $maxLoadedLangs = 10;
926 protected function readPHPFile( $fileName, $fileType ) {
927 $serialize = $fileType === 'core';
928 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
929 $data = parent
::readPHPFile( $fileName, $fileType );
931 $encData = serialize( $data );
935 $this->fileCache
[$fileName][$fileType] = $encData;
937 } elseif ( $serialize ) {
938 return unserialize( $this->fileCache
[$fileName][$fileType] );
940 return $this->fileCache
[$fileName][$fileType];
944 public function getItem( $code, $key ) {
945 unset( $this->mruLangs
[$code] );
946 $this->mruLangs
[$code] = true;
947 return parent
::getItem( $code, $key );
950 public function getSubitem( $code, $key, $subkey ) {
951 unset( $this->mruLangs
[$code] );
952 $this->mruLangs
[$code] = true;
953 return parent
::getSubitem( $code, $key, $subkey );
956 public function recache( $code ) {
957 parent
::recache( $code );
958 unset( $this->mruLangs
[$code] );
959 $this->mruLangs
[$code] = true;
963 public function unload( $code ) {
964 unset( $this->mruLangs
[$code] );
965 parent
::unload( $code );
969 * Unload cached languages until there are less than $this->maxLoadedLangs
971 protected function trimCache() {
972 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
973 reset( $this->mruLangs
);
974 $code = key( $this->mruLangs
);
975 wfDebug( __METHOD__
.": unloading $code\n" );
976 $this->unload( $code );