3 define( 'MW_LC_VERSION', 2 );
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', 'bookstoreList',
85 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
86 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
87 'linkTrail', 'namespaceAliases',
88 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
89 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
90 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
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',
98 'dateFormats', 'imageFiles', 'preloadedMessages',
102 * Keys for items which are a numbered array.
104 static public $mergeableListKeys = array( 'extraUserToggles' );
107 * Keys for items which contain an array of arrays of equivalent aliases
108 * for each subitem. The aliases may be merged by a fallback sequence.
110 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
113 * Keys for items which contain an associative array, and may be merged if
114 * the primary value contains the special array key "inherit". That array
115 * key is removed after the first merge.
117 static public $optionalMergeKeys = array( 'bookstoreList' );
120 * Keys for items that are formatted like $magicWords
122 static public $magicWordKeys = array( 'magicWords' );
125 * Keys for items where the subitems are stored in the backend separately.
127 static public $splitKeys = array( 'messages' );
130 * Keys which are loaded automatically by initLanguage()
132 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames' );
136 * For constructor parameters, see the documentation in DefaultSettings.php
137 * for $wgLocalisationCacheConf.
141 function __construct( $conf ) {
142 global $wgCacheDirectory;
145 $storeConf = array();
146 if ( !empty( $conf['storeClass'] ) ) {
147 $storeClass = $conf['storeClass'];
149 switch ( $conf['store'] ) {
152 $storeClass = 'LCStore_CDB';
155 $storeClass = 'LCStore_DB';
158 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
161 throw new MWException(
162 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
166 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
167 if ( !empty( $conf['storeDirectory'] ) ) {
168 $storeConf['directory'] = $conf['storeDirectory'];
171 $this->store
= new $storeClass( $storeConf );
172 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
173 if ( isset( $conf[$var] ) ) {
174 $this->$var = $conf[$var];
180 * Returns true if the given key is mergeable, that is, if it is an associative
181 * array which can be merged through a fallback sequence.
183 public function isMergeableKey( $key ) {
184 if ( !isset( $this->mergeableKeys
) ) {
185 $this->mergeableKeys
= array_flip( array_merge(
186 self
::$mergeableMapKeys,
187 self
::$mergeableListKeys,
188 self
::$mergeableAliasListKeys,
189 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->loadedSubitems
[$code][$key][$subkey] )
219 && !isset( $this->loadedItems
[$code][$key] ) )
221 wfProfileIn( __METHOD__
.'-load' );
222 $this->loadSubitem( $code, $key, $subkey );
223 wfProfileOut( __METHOD__
.'-load' );
225 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
226 return $this->data
[$code][$key][$subkey];
233 * Get the list of subitem keys for a given item.
235 * This is faster than array_keys($lc->getItem(...)) for the items listed in
238 * Will return null if the item is not found, or false if the item is not an
241 public function getSubitemList( $code, $key ) {
242 if ( in_array( $key, self
::$splitKeys ) ) {
243 return $this->getSubitem( $code, 'list', $key );
245 $item = $this->getItem( $code, $key );
246 if ( is_array( $item ) ) {
247 return array_keys( $item );
255 * Load an item into the cache.
257 protected function loadItem( $code, $key ) {
258 if ( !isset( $this->initialisedLangs
[$code] ) ) {
259 $this->initLanguage( $code );
261 // Check to see if initLanguage() loaded it for us
262 if ( isset( $this->loadedItems
[$code][$key] ) ) {
265 if ( isset( $this->shallowFallbacks
[$code] ) ) {
266 $this->loadItem( $this->shallowFallbacks
[$code], $key );
269 if ( in_array( $key, self
::$splitKeys ) ) {
270 $subkeyList = $this->getSubitem( $code, 'list', $key );
271 foreach ( $subkeyList as $subkey ) {
272 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
275 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
278 $this->data
[$code][$key] = $this->store
->get( $code, $key );
280 $this->loadedItems
[$code][$key] = true;
284 * Load a subitem into the cache
286 protected function loadSubitem( $code, $key, $subkey ) {
287 if ( !in_array( $key, self
::$splitKeys ) ) {
288 $this->loadItem( $code, $key );
291 if ( !isset( $this->initialisedLangs
[$code] ) ) {
292 $this->initLanguage( $code );
294 // Check to see if initLanguage() loaded it for us
295 if ( isset( $this->loadedItems
[$code][$key] )
296 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
300 if ( isset( $this->shallowFallbacks
[$code] ) ) {
301 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
304 $value = $this->store
->get( $code, "$key:$subkey" );
305 $this->data
[$code][$key][$subkey] = $value;
306 $this->loadedSubitems
[$code][$key][$subkey] = true;
310 * Returns true if the cache identified by $code is missing or expired.
312 public function isExpired( $code ) {
313 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
314 wfDebug( __METHOD__
."($code): forced reload\n" );
318 $deps = $this->store
->get( $code, 'deps' );
319 if ( $deps === null ) {
320 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
323 foreach ( $deps as $dep ) {
324 // Because we're unserializing stuff from cache, we
325 // could receive objects of classes that don't exist
326 // anymore (e.g. uninstalled extensions)
327 // When this happens, always expire the cache
328 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
329 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
330 get_class( $dep ) . "\n" );
338 * Initialise a language in this object. Rebuild the cache if necessary.
340 protected function initLanguage( $code ) {
341 if ( isset( $this->initialisedLangs
[$code] ) ) {
344 $this->initialisedLangs
[$code] = true;
346 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
347 if ( !Language
::isValidBuiltInCode( $code ) ) {
348 $this->initShallowFallback( $code, 'en' );
352 # Recache the data if necessary
353 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
354 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
355 $this->recache( $code );
356 } elseif ( $code === 'en' ) {
357 throw new MWException( 'MessagesEn.php is missing.' );
359 $this->initShallowFallback( $code, 'en' );
365 $preload = $this->getItem( $code, 'preload' );
366 if ( $preload === null ) {
367 if ( $this->manualRecache
) {
368 // No Messages*.php file. Do shallow fallback to en.
369 if ( $code === 'en' ) {
370 throw new MWException( 'No localisation cache found for English. ' .
371 'Please run maintenance/rebuildLocalisationCache.php.' );
373 $this->initShallowFallback( $code, 'en' );
376 throw new MWException( 'Invalid or missing localisation cache.' );
379 $this->data
[$code] = $preload;
380 foreach ( $preload as $key => $item ) {
381 if ( in_array( $key, self
::$splitKeys ) ) {
382 foreach ( $item as $subkey => $subitem ) {
383 $this->loadedSubitems
[$code][$key][$subkey] = true;
386 $this->loadedItems
[$code][$key] = true;
392 * Create a fallback from one language to another, without creating a
393 * complete persistent cache.
395 public function initShallowFallback( $primaryCode, $fallbackCode ) {
396 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
397 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
398 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
399 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
403 * Read a PHP file containing localisation data.
405 protected function readPHPFile( $_fileName, $_fileType ) {
406 // Disable APC caching
407 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
408 include( $_fileName );
409 ini_set( 'apc.cache_by_default', $_apcEnabled );
411 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
412 $data = compact( self
::$allKeys );
413 } elseif ( $_fileType == 'aliases' ) {
414 $data = compact( 'aliases' );
416 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
422 * Merge two localisation values, a primary and a fallback, overwriting the
423 * primary value in place.
425 protected function mergeItem( $key, &$value, $fallbackValue ) {
426 if ( !is_null( $value ) ) {
427 if ( !is_null( $fallbackValue ) ) {
428 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
429 $value = $value +
$fallbackValue;
430 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
431 $value = array_unique( array_merge( $fallbackValue, $value ) );
432 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
433 $value = array_merge_recursive( $value, $fallbackValue );
434 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
435 if ( !empty( $value['inherit'] ) ) {
436 $value = array_merge( $fallbackValue, $value );
438 if ( isset( $value['inherit'] ) ) {
439 unset( $value['inherit'] );
441 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
442 $this->mergeMagicWords( $value, $fallbackValue );
446 $value = $fallbackValue;
450 protected function mergeMagicWords( &$value, $fallbackValue ) {
451 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
452 if ( !isset( $value[$magicName] ) ) {
453 $value[$magicName] = $fallbackInfo;
455 $oldSynonyms = array_slice( $fallbackInfo, 1 );
456 $newSynonyms = array_slice( $value[$magicName], 1 );
457 $synonyms = array_values( array_unique( array_merge(
458 $newSynonyms, $oldSynonyms ) ) );
459 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
465 * Given an array mapping language code to localisation value, such as is
466 * found in extension *.i18n.php files, iterate through a fallback sequence
467 * to merge the given data with an existing primary value.
469 * Returns true if any data from the extension array was used, false
472 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
474 foreach ( $codeSequence as $code ) {
475 if ( isset( $fallbackValue[$code] ) ) {
476 $this->mergeItem( $key, $value, $fallbackValue[$code] );
484 * Load localisation data for a given language for both core and extensions
485 * and save it to the persistent cache store and the process cache
487 public function recache( $code ) {
488 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
489 wfProfileIn( __METHOD__
);
492 throw new MWException( "Invalid language code requested" );
494 $this->recachedLangs
[$code] = true;
497 $initialData = array_combine(
499 array_fill( 0, count( self
::$allKeys ), null ) );
500 $coreData = $initialData;
503 # Load the primary localisation from the source file
504 $fileName = Language
::getMessagesFileName( $code );
505 if ( !file_exists( $fileName ) ) {
506 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
507 $coreData['fallback'] = 'en';
509 $deps[] = new FileDependency( $fileName );
510 $data = $this->readPHPFile( $fileName, 'core' );
511 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
513 # Merge primary localisation
514 foreach ( $data as $key => $value ) {
515 $this->mergeItem( $key, $coreData[$key], $value );
520 # Fill in the fallback if it's not there already
521 if ( is_null( $coreData['fallback'] ) ) {
522 $coreData['fallback'] = $code === 'en' ?
false : 'en';
525 if ( $coreData['fallback'] === false ) {
526 $coreData['fallbackSequence'] = array();
528 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
529 $len = count( $coreData['fallbackSequence'] );
530 # Ensure that the sequence ends at en
531 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
532 $coreData['fallbackSequence'][] = 'en';
535 # Load the fallback localisation item by item and merge it
536 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
538 # Load the secondary localisation from the source file to
539 # avoid infinite cycles on cyclic fallbacks
540 $fbFilename = Language
::getMessagesFileName( $fbCode );
541 if ( !file_exists( $fbFilename ) ) continue;
543 $deps[] = new FileDependency( $fbFilename );
544 $fbData = $this->readPHPFile( $fbFilename, 'core' );
545 foreach ( self
::$allKeys as $key ) {
546 if ( !isset( $fbData[$key] ) ) continue;
547 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
548 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
554 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
556 # Load the extension localisations
557 # This is done after the core because we know the fallback sequence now.
558 # But it has a higher precedence for merging so that we can support things
559 # like site-specific message overrides.
560 $allData = $initialData;
561 foreach ( $wgExtensionMessagesFiles as $fileName ) {
562 $data = $this->readPHPFile( $fileName, 'extension' );
564 foreach ( $data as $key => $item ) {
565 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
570 $deps[] = new FileDependency( $fileName );
574 # Load deprecated $wgExtensionAliasesFiles
575 foreach ( $wgExtensionAliasesFiles as $fileName ) {
576 $data = $this->readPHPFile( $fileName, 'aliases' );
577 if ( !isset( $data['aliases'] ) ) {
580 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
581 $allData['specialPageAliases'], $data['aliases'] );
583 $deps[] = new FileDependency( $fileName );
587 # Merge core data into extension data
588 foreach ( $coreData as $key => $item ) {
589 $this->mergeItem( $key, $allData[$key], $item );
592 # Add cache dependencies for any referenced globals
593 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
594 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
595 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
597 # Add dependencies to the cache entry
598 $allData['deps'] = $deps;
600 # Replace spaces with underscores in namespace names
601 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
603 # And do the same for special page aliases. $page is an array.
604 foreach ( $allData['specialPageAliases'] as &$page ) {
605 $page = str_replace( ' ', '_', $page );
607 # Decouple the reference to prevent accidental damage
611 $allData['list'] = array();
612 foreach ( self
::$splitKeys as $key ) {
613 $allData['list'][$key] = array_keys( $allData[$key] );
617 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
619 # Set the preload key
620 $allData['preload'] = $this->buildPreload( $allData );
622 # Save to the process cache and register the items loaded
623 $this->data
[$code] = $allData;
624 foreach ( $allData as $key => $item ) {
625 $this->loadedItems
[$code][$key] = true;
628 # Save to the persistent cache
629 $this->store
->startWrite( $code );
630 foreach ( $allData as $key => $value ) {
631 if ( in_array( $key, self
::$splitKeys ) ) {
632 foreach ( $value as $subkey => $subvalue ) {
633 $this->store
->set( "$key:$subkey", $subvalue );
636 $this->store
->set( $key, $value );
639 $this->store
->finishWrite();
641 # Clear out the MessageBlobStore
642 # HACK: If using a null (i.e. disabled) storage backend, we
643 # can't write to the MessageBlobStore either
644 if ( !$this->store
instanceof LCStore_Null
) {
645 MessageBlobStore
::clear();
648 wfProfileOut( __METHOD__
);
652 * Build the preload item from the given pre-cache data.
654 * The preload item will be loaded automatically, improving performance
655 * for the commonly-requested items it contains.
657 protected function buildPreload( $data ) {
658 $preload = array( 'messages' => array() );
659 foreach ( self
::$preloadedKeys as $key ) {
660 $preload[$key] = $data[$key];
662 foreach ( $data['preloadedMessages'] as $subkey ) {
663 if ( isset( $data['messages'][$subkey] ) ) {
664 $subitem = $data['messages'][$subkey];
668 $preload['messages'][$subkey] = $subitem;
674 * Unload the data for a given language from the object cache.
675 * Reduces memory usage.
677 public function unload( $code ) {
678 unset( $this->data
[$code] );
679 unset( $this->loadedItems
[$code] );
680 unset( $this->loadedSubitems
[$code] );
681 unset( $this->initialisedLangs
[$code] );
682 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
683 if ( $fbCode === $code ) {
684 $this->unload( $shallowCode );
692 public function unloadAll() {
693 foreach ( $this->initialisedLangs
as $lang => $unused ) {
694 $this->unload( $lang );
699 * Disable the storage backend
701 public function disableBackend() {
702 $this->store
= new LCStore_Null
;
703 $this->manualRecache
= false;
708 * Interface for the persistence layer of LocalisationCache.
710 * The persistence layer is two-level hierarchical cache. The first level
711 * is the language, the second level is the item or subitem.
713 * Since the data for a whole language is rebuilt in one operation, it needs
714 * to have a fast and atomic method for deleting or replacing all of the
715 * current data for a given language. The interface reflects this bulk update
716 * operation. Callers writing to the cache must first call startWrite(), then
717 * will call set() a couple of thousand times, then will call finishWrite()
718 * to commit the operation. When finishWrite() is called, the cache is
719 * expected to delete all data previously stored for that language.
721 * The values stored are PHP variables suitable for serialize(). Implementations
722 * of LCStore are responsible for serializing and unserializing.
727 * @param $code Language code
728 * @param $key Cache key
730 function get( $code, $key );
733 * Start a write transaction.
734 * @param $code Language code
736 function startWrite( $code );
739 * Finish a write transaction.
741 function finishWrite();
744 * Set a key to a given value. startWrite() must be called before this
745 * is called, and finishWrite() must be called afterwards.
747 function set( $key, $value );
752 * LCStore implementation which uses the standard DB functions to store data.
753 * This will work on any MediaWiki installation.
755 class LCStore_DB
implements LCStore
{
757 var $writesDone = false;
759 var $readOnly = false;
761 public function get( $code, $key ) {
762 if ( $this->writesDone
) {
763 $db = wfGetDB( DB_MASTER
);
765 $db = wfGetDB( DB_SLAVE
);
767 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
768 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
770 return unserialize( $row->lc_value
);
776 public function startWrite( $code ) {
777 if ( $this->readOnly
) {
781 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
783 $this->dbw
= wfGetDB( DB_MASTER
);
786 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
787 } catch ( DBQueryError
$e ) {
788 if ( $this->dbw
->wasReadOnlyError() ) {
789 $this->readOnly
= true;
790 $this->dbw
->rollback();
791 $this->dbw
->ignoreErrors( false );
797 $this->currentLang
= $code;
798 $this->batch
= array();
801 public function finishWrite() {
802 if ( $this->readOnly
) {
805 if ( $this->batch
) {
806 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
808 $this->dbw
->commit();
809 $this->currentLang
= null;
811 $this->batch
= array();
812 $this->writesDone
= true;
815 public function set( $key, $value ) {
816 if ( $this->readOnly
) {
819 if ( is_null( $this->currentLang
) ) {
820 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
822 $this->batch
[] = array(
823 'lc_lang' => $this->currentLang
,
825 'lc_value' => serialize( $value ) );
826 if ( count( $this->batch
) >= 100 ) {
827 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
828 $this->batch
= array();
834 * LCStore implementation which stores data as a collection of CDB files in the
835 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
836 * will throw an exception.
838 * Profiling indicates that on Linux, this implementation outperforms MySQL if
839 * the directory is on a local filesystem and there is ample kernel cache
840 * space. The performance advantage is greater when the DBA extension is
841 * available than it is with the PHP port.
843 * See Cdb.php and http://cr.yp.to/cdb.html
845 class LCStore_CDB
implements LCStore
{
846 var $readers, $writer, $currentLang, $directory;
848 function __construct( $conf = array() ) {
849 global $wgCacheDirectory;
850 if ( isset( $conf['directory'] ) ) {
851 $this->directory
= $conf['directory'];
853 $this->directory
= $wgCacheDirectory;
857 public function get( $code, $key ) {
858 if ( !isset( $this->readers
[$code] ) ) {
859 $fileName = $this->getFileName( $code );
860 if ( !file_exists( $fileName ) ) {
861 $this->readers
[$code] = false;
863 $this->readers
[$code] = CdbReader
::open( $fileName );
866 if ( !$this->readers
[$code] ) {
869 $value = $this->readers
[$code]->get( $key );
870 if ( $value === false ) {
873 return unserialize( $value );
877 public function startWrite( $code ) {
878 if ( !file_exists( $this->directory
) ) {
879 if ( !wfMkdirParents( $this->directory
, null, __METHOD__
) ) {
880 throw new MWException( "Unable to create the localisation store " .
881 "directory \"{$this->directory}\"" );
884 // Close reader to stop permission errors on write
885 if( !empty($this->readers
[$code]) ) {
886 $this->readers
[$code]->close();
888 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
889 $this->currentLang
= $code;
892 public function finishWrite() {
894 $this->writer
->close();
895 $this->writer
= null;
896 unset( $this->readers
[$this->currentLang
] );
897 $this->currentLang
= null;
900 public function set( $key, $value ) {
901 if ( is_null( $this->writer
) ) {
902 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
904 $this->writer
->set( $key, serialize( $value ) );
907 protected function getFileName( $code ) {
908 if ( !$code ||
strpos( $code, '/' ) !== false ) {
909 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
911 return "{$this->directory}/l10n_cache-$code.cdb";
916 * Null store backend, used to avoid DB errors during install
918 class LCStore_Null
implements LCStore
{
919 public function get( $code, $key ) {
923 public function startWrite( $code ) {}
924 public function finishWrite() {}
925 public function set( $key, $value ) {}
929 * A localisation cache optimised for loading large amounts of data for many
930 * languages. Used by rebuildLocalisationCache.php.
932 class LocalisationCache_BulkLoad
extends LocalisationCache
{
934 * A cache of the contents of data files.
935 * Core files are serialized to avoid using ~1GB of RAM during a recache.
937 var $fileCache = array();
940 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
941 * to keep the most recently used language codes at the end of the array, and
942 * the language codes that are ready to be deleted at the beginning.
944 var $mruLangs = array();
947 * Maximum number of languages that may be loaded into $this->data
949 var $maxLoadedLangs = 10;
951 protected function readPHPFile( $fileName, $fileType ) {
952 $serialize = $fileType === 'core';
953 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
954 $data = parent
::readPHPFile( $fileName, $fileType );
956 $encData = serialize( $data );
960 $this->fileCache
[$fileName][$fileType] = $encData;
962 } elseif ( $serialize ) {
963 return unserialize( $this->fileCache
[$fileName][$fileType] );
965 return $this->fileCache
[$fileName][$fileType];
969 public function getItem( $code, $key ) {
970 unset( $this->mruLangs
[$code] );
971 $this->mruLangs
[$code] = true;
972 return parent
::getItem( $code, $key );
975 public function getSubitem( $code, $key, $subkey ) {
976 unset( $this->mruLangs
[$code] );
977 $this->mruLangs
[$code] = true;
978 return parent
::getSubitem( $code, $key, $subkey );
981 public function recache( $code ) {
982 parent
::recache( $code );
983 unset( $this->mruLangs
[$code] );
984 $this->mruLangs
[$code] = true;
988 public function unload( $code ) {
989 unset( $this->mruLangs
[$code] );
990 parent
::unload( $code );
994 * Unload cached languages until there are less than $this->maxLoadedLangs
996 protected function trimCache() {
997 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
998 reset( $this->mruLangs
);
999 $code = key( $this->mruLangs
);
1000 wfDebug( __METHOD__
.": unloading $code\n" );
1001 $this->unload( $code );