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',
91 'digitGroupingPattern'
95 * Keys for items which consist of associative arrays, which may be merged
96 * by a fallback sequence.
98 static public $mergeableMapKeys = array( 'messages', 'namespaceNames',
99 'dateFormats', 'imageFiles', 'preloadedMessages',
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 that are formatted like $magicWords
123 static public $magicWordKeys = array( 'magicWords' );
126 * Keys for items where the subitems are stored in the backend separately.
128 static public $splitKeys = array( 'messages' );
131 * Keys which are loaded automatically by initLanguage()
133 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames' );
137 * For constructor parameters, see the documentation in DefaultSettings.php
138 * 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 $wgLocalisationCacheConf[\'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,
194 return isset( $this->mergeableKeys
[$key] );
200 * Warning: this may be slow for split items (messages), since it will
201 * need to fetch all of the subitems from the cache individually.
203 public function getItem( $code, $key ) {
204 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
205 wfProfileIn( __METHOD__
.'-load' );
206 $this->loadItem( $code, $key );
207 wfProfileOut( __METHOD__
.'-load' );
210 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
211 return $this->shallowFallbacks
[$code];
214 return $this->data
[$code][$key];
218 * Get a subitem, for instance a single message for a given language.
220 public function getSubitem( $code, $key, $subkey ) {
221 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] )
222 && !isset( $this->loadedItems
[$code][$key] ) )
224 wfProfileIn( __METHOD__
.'-load' );
225 $this->loadSubitem( $code, $key, $subkey );
226 wfProfileOut( __METHOD__
.'-load' );
229 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
230 return $this->data
[$code][$key][$subkey];
237 * Get the list of subitem keys for a given item.
239 * This is faster than array_keys($lc->getItem(...)) for the items listed in
242 * Will return null if the item is not found, or false if the item is not an
245 public function getSubitemList( $code, $key ) {
246 if ( in_array( $key, self
::$splitKeys ) ) {
247 return $this->getSubitem( $code, 'list', $key );
249 $item = $this->getItem( $code, $key );
250 if ( is_array( $item ) ) {
251 return array_keys( $item );
259 * Load an item into the cache.
261 protected function loadItem( $code, $key ) {
262 if ( !isset( $this->initialisedLangs
[$code] ) ) {
263 $this->initLanguage( $code );
266 // Check to see if initLanguage() loaded it for us
267 if ( isset( $this->loadedItems
[$code][$key] ) ) {
271 if ( isset( $this->shallowFallbacks
[$code] ) ) {
272 $this->loadItem( $this->shallowFallbacks
[$code], $key );
276 if ( in_array( $key, self
::$splitKeys ) ) {
277 $subkeyList = $this->getSubitem( $code, 'list', $key );
278 foreach ( $subkeyList as $subkey ) {
279 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
282 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
285 $this->data
[$code][$key] = $this->store
->get( $code, $key );
288 $this->loadedItems
[$code][$key] = true;
292 * Load a subitem into the cache
294 protected function loadSubitem( $code, $key, $subkey ) {
295 if ( !in_array( $key, self
::$splitKeys ) ) {
296 $this->loadItem( $code, $key );
300 if ( !isset( $this->initialisedLangs
[$code] ) ) {
301 $this->initLanguage( $code );
304 // Check to see if initLanguage() loaded it for us
305 if ( isset( $this->loadedItems
[$code][$key] )
306 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
311 if ( isset( $this->shallowFallbacks
[$code] ) ) {
312 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
316 $value = $this->store
->get( $code, "$key:$subkey" );
317 $this->data
[$code][$key][$subkey] = $value;
318 $this->loadedSubitems
[$code][$key][$subkey] = true;
322 * Returns true if the cache identified by $code is missing or expired.
324 public function isExpired( $code ) {
325 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
326 wfDebug( __METHOD__
."($code): forced reload\n" );
330 $deps = $this->store
->get( $code, 'deps' );
331 if ( $deps === null ) {
332 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
336 foreach ( $deps as $dep ) {
337 // Because we're unserializing stuff from cache, we
338 // could receive objects of classes that don't exist
339 // anymore (e.g. uninstalled extensions)
340 // When this happens, always expire the cache
341 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
342 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
343 get_class( $dep ) . "\n" );
352 * Initialise a language in this object. Rebuild the cache if necessary.
354 protected function initLanguage( $code ) {
355 if ( isset( $this->initialisedLangs
[$code] ) ) {
359 $this->initialisedLangs
[$code] = true;
361 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
362 if ( !Language
::isValidBuiltInCode( $code ) ) {
363 $this->initShallowFallback( $code, 'en' );
367 # Recache the data if necessary
368 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
369 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
370 $this->recache( $code );
371 } elseif ( $code === 'en' ) {
372 throw new MWException( 'MessagesEn.php is missing.' );
374 $this->initShallowFallback( $code, 'en' );
380 $preload = $this->getItem( $code, 'preload' );
381 if ( $preload === null ) {
382 if ( $this->manualRecache
) {
383 // No Messages*.php file. Do shallow fallback to en.
384 if ( $code === 'en' ) {
385 throw new MWException( 'No localisation cache found for English. ' .
386 'Please run maintenance/rebuildLocalisationCache.php.' );
388 $this->initShallowFallback( $code, 'en' );
391 throw new MWException( 'Invalid or missing localisation cache.' );
394 $this->data
[$code] = $preload;
395 foreach ( $preload as $key => $item ) {
396 if ( in_array( $key, self
::$splitKeys ) ) {
397 foreach ( $item as $subkey => $subitem ) {
398 $this->loadedSubitems
[$code][$key][$subkey] = true;
401 $this->loadedItems
[$code][$key] = true;
407 * Create a fallback from one language to another, without creating a
408 * complete persistent cache.
410 public function initShallowFallback( $primaryCode, $fallbackCode ) {
411 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
412 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
413 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
414 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
418 * Read a PHP file containing localisation data.
420 protected function readPHPFile( $_fileName, $_fileType ) {
421 // Disable APC caching
422 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
423 include( $_fileName );
424 ini_set( 'apc.cache_by_default', $_apcEnabled );
426 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
427 $data = compact( self
::$allKeys );
428 } elseif ( $_fileType == 'aliases' ) {
429 $data = compact( 'aliases' );
431 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
438 * Merge two localisation values, a primary and a fallback, overwriting the
439 * primary value in place.
441 protected function mergeItem( $key, &$value, $fallbackValue ) {
442 if ( !is_null( $value ) ) {
443 if ( !is_null( $fallbackValue ) ) {
444 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
445 $value = $value +
$fallbackValue;
446 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
447 $value = array_unique( array_merge( $fallbackValue, $value ) );
448 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
449 $value = array_merge_recursive( $value, $fallbackValue );
450 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
451 if ( !empty( $value['inherit'] ) ) {
452 $value = array_merge( $fallbackValue, $value );
455 if ( isset( $value['inherit'] ) ) {
456 unset( $value['inherit'] );
458 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
459 $this->mergeMagicWords( $value, $fallbackValue );
463 $value = $fallbackValue;
467 protected function mergeMagicWords( &$value, $fallbackValue ) {
468 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
469 if ( !isset( $value[$magicName] ) ) {
470 $value[$magicName] = $fallbackInfo;
472 $oldSynonyms = array_slice( $fallbackInfo, 1 );
473 $newSynonyms = array_slice( $value[$magicName], 1 );
474 $synonyms = array_values( array_unique( array_merge(
475 $newSynonyms, $oldSynonyms ) ) );
476 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
482 * Given an array mapping language code to localisation value, such as is
483 * found in extension *.i18n.php files, iterate through a fallback sequence
484 * to merge the given data with an existing primary value.
486 * Returns true if any data from the extension array was used, false
489 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
491 foreach ( $codeSequence as $code ) {
492 if ( isset( $fallbackValue[$code] ) ) {
493 $this->mergeItem( $key, $value, $fallbackValue[$code] );
502 * Load localisation data for a given language for both core and extensions
503 * and save it to the persistent cache store and the process cache
505 public function recache( $code ) {
506 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
507 wfProfileIn( __METHOD__
);
510 throw new MWException( "Invalid language code requested" );
512 $this->recachedLangs
[$code] = true;
515 $initialData = array_combine(
517 array_fill( 0, count( self
::$allKeys ), null ) );
518 $coreData = $initialData;
521 # Load the primary localisation from the source file
522 $fileName = Language
::getMessagesFileName( $code );
523 if ( !file_exists( $fileName ) ) {
524 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
525 $coreData['fallback'] = 'en';
527 $deps[] = new FileDependency( $fileName );
528 $data = $this->readPHPFile( $fileName, 'core' );
529 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
531 # Merge primary localisation
532 foreach ( $data as $key => $value ) {
533 $this->mergeItem( $key, $coreData[$key], $value );
538 # Fill in the fallback if it's not there already
539 if ( is_null( $coreData['fallback'] ) ) {
540 $coreData['fallback'] = $code === 'en' ?
false : 'en';
543 if ( $coreData['fallback'] === false ) {
544 $coreData['fallbackSequence'] = array();
546 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
547 $len = count( $coreData['fallbackSequence'] );
549 # Ensure that the sequence ends at en
550 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
551 $coreData['fallbackSequence'][] = 'en';
554 # Load the fallback localisation item by item and merge it
555 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
556 # Load the secondary localisation from the source file to
557 # avoid infinite cycles on cyclic fallbacks
558 $fbFilename = Language
::getMessagesFileName( $fbCode );
560 if ( !file_exists( $fbFilename ) ) {
564 $deps[] = new FileDependency( $fbFilename );
565 $fbData = $this->readPHPFile( $fbFilename, 'core' );
567 foreach ( self
::$allKeys as $key ) {
568 if ( !isset( $fbData[$key] ) ) {
572 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
573 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
579 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
581 # Load the extension localisations
582 # This is done after the core because we know the fallback sequence now.
583 # But it has a higher precedence for merging so that we can support things
584 # like site-specific message overrides.
585 $allData = $initialData;
586 foreach ( $wgExtensionMessagesFiles as $fileName ) {
587 $data = $this->readPHPFile( $fileName, 'extension' );
590 foreach ( $data as $key => $item ) {
591 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
597 $deps[] = new FileDependency( $fileName );
601 # Load deprecated $wgExtensionAliasesFiles
602 foreach ( $wgExtensionAliasesFiles as $fileName ) {
603 $data = $this->readPHPFile( $fileName, 'aliases' );
605 if ( !isset( $data['aliases'] ) ) {
609 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
610 $allData['specialPageAliases'], $data['aliases'] );
613 $deps[] = new FileDependency( $fileName );
617 # Merge core data into extension data
618 foreach ( $coreData as $key => $item ) {
619 $this->mergeItem( $key, $allData[$key], $item );
622 # Add cache dependencies for any referenced globals
623 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
624 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
625 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
627 # Add dependencies to the cache entry
628 $allData['deps'] = $deps;
630 # Replace spaces with underscores in namespace names
631 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
633 # And do the same for special page aliases. $page is an array.
634 foreach ( $allData['specialPageAliases'] as &$page ) {
635 $page = str_replace( ' ', '_', $page );
637 # Decouple the reference to prevent accidental damage
641 $allData['list'] = array();
642 foreach ( self
::$splitKeys as $key ) {
643 $allData['list'][$key] = array_keys( $allData[$key] );
647 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
649 if ( is_null( $allData['namespaceNames'] ) ) {
650 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
651 'Check that your languages/messages/MessagesEn.php file is intact.' );
654 # Set the preload key
655 $allData['preload'] = $this->buildPreload( $allData );
657 # Save to the process cache and register the items loaded
658 $this->data
[$code] = $allData;
659 foreach ( $allData as $key => $item ) {
660 $this->loadedItems
[$code][$key] = true;
663 # Save to the persistent cache
664 $this->store
->startWrite( $code );
665 foreach ( $allData as $key => $value ) {
666 if ( in_array( $key, self
::$splitKeys ) ) {
667 foreach ( $value as $subkey => $subvalue ) {
668 $this->store
->set( "$key:$subkey", $subvalue );
671 $this->store
->set( $key, $value );
674 $this->store
->finishWrite();
676 # Clear out the MessageBlobStore
677 # HACK: If using a null (i.e. disabled) storage backend, we
678 # can't write to the MessageBlobStore either
679 if ( !$this->store
instanceof LCStore_Null
) {
680 MessageBlobStore
::clear();
683 wfProfileOut( __METHOD__
);
687 * Build the preload item from the given pre-cache data.
689 * The preload item will be loaded automatically, improving performance
690 * for the commonly-requested items it contains.
692 protected function buildPreload( $data ) {
693 $preload = array( 'messages' => array() );
694 foreach ( self
::$preloadedKeys as $key ) {
695 $preload[$key] = $data[$key];
698 foreach ( $data['preloadedMessages'] as $subkey ) {
699 if ( isset( $data['messages'][$subkey] ) ) {
700 $subitem = $data['messages'][$subkey];
704 $preload['messages'][$subkey] = $subitem;
711 * Unload the data for a given language from the object cache.
712 * Reduces memory usage.
714 public function unload( $code ) {
715 unset( $this->data
[$code] );
716 unset( $this->loadedItems
[$code] );
717 unset( $this->loadedSubitems
[$code] );
718 unset( $this->initialisedLangs
[$code] );
720 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
721 if ( $fbCode === $code ) {
722 $this->unload( $shallowCode );
730 public function unloadAll() {
731 foreach ( $this->initialisedLangs
as $lang => $unused ) {
732 $this->unload( $lang );
737 * Disable the storage backend
739 public function disableBackend() {
740 $this->store
= new LCStore_Null
;
741 $this->manualRecache
= false;
746 * Interface for the persistence layer of LocalisationCache.
748 * The persistence layer is two-level hierarchical cache. The first level
749 * is the language, the second level is the item or subitem.
751 * Since the data for a whole language is rebuilt in one operation, it needs
752 * to have a fast and atomic method for deleting or replacing all of the
753 * current data for a given language. The interface reflects this bulk update
754 * operation. Callers writing to the cache must first call startWrite(), then
755 * will call set() a couple of thousand times, then will call finishWrite()
756 * to commit the operation. When finishWrite() is called, the cache is
757 * expected to delete all data previously stored for that language.
759 * The values stored are PHP variables suitable for serialize(). Implementations
760 * of LCStore are responsible for serializing and unserializing.
765 * @param $code Language code
766 * @param $key Cache key
768 function get( $code, $key );
771 * Start a write transaction.
772 * @param $code Language code
774 function startWrite( $code );
777 * Finish a write transaction.
779 function finishWrite();
782 * Set a key to a given value. startWrite() must be called before this
783 * is called, and finishWrite() must be called afterwards.
785 function set( $key, $value );
789 * LCStore implementation which uses the standard DB functions to store data.
790 * This will work on any MediaWiki installation.
792 class LCStore_DB
implements LCStore
{
794 var $writesDone = false;
796 var $readOnly = false;
798 public function get( $code, $key ) {
799 if ( $this->writesDone
) {
800 $db = wfGetDB( DB_MASTER
);
802 $db = wfGetDB( DB_SLAVE
);
804 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
805 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
807 return unserialize( $row->lc_value
);
813 public function startWrite( $code ) {
814 if ( $this->readOnly
) {
819 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
822 $this->dbw
= wfGetDB( DB_MASTER
);
825 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
826 } catch ( DBQueryError
$e ) {
827 if ( $this->dbw
->wasReadOnlyError() ) {
828 $this->readOnly
= true;
829 $this->dbw
->rollback();
830 $this->dbw
->ignoreErrors( false );
837 $this->currentLang
= $code;
838 $this->batch
= array();
841 public function finishWrite() {
842 if ( $this->readOnly
) {
846 if ( $this->batch
) {
847 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
850 $this->dbw
->commit();
851 $this->currentLang
= null;
853 $this->batch
= array();
854 $this->writesDone
= true;
857 public function set( $key, $value ) {
858 if ( $this->readOnly
) {
862 if ( is_null( $this->currentLang
) ) {
863 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
866 $this->batch
[] = array(
867 'lc_lang' => $this->currentLang
,
869 'lc_value' => serialize( $value ) );
871 if ( count( $this->batch
) >= 100 ) {
872 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
873 $this->batch
= array();
879 * LCStore implementation which stores data as a collection of CDB files in the
880 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
881 * will throw an exception.
883 * Profiling indicates that on Linux, this implementation outperforms MySQL if
884 * the directory is on a local filesystem and there is ample kernel cache
885 * space. The performance advantage is greater when the DBA extension is
886 * available than it is with the PHP port.
888 * See Cdb.php and http://cr.yp.to/cdb.html
890 class LCStore_CDB
implements LCStore
{
891 var $readers, $writer, $currentLang, $directory;
893 function __construct( $conf = array() ) {
894 global $wgCacheDirectory;
896 if ( isset( $conf['directory'] ) ) {
897 $this->directory
= $conf['directory'];
899 $this->directory
= $wgCacheDirectory;
903 public function get( $code, $key ) {
904 if ( !isset( $this->readers
[$code] ) ) {
905 $fileName = $this->getFileName( $code );
907 if ( !file_exists( $fileName ) ) {
908 $this->readers
[$code] = false;
910 $this->readers
[$code] = CdbReader
::open( $fileName );
914 if ( !$this->readers
[$code] ) {
917 $value = $this->readers
[$code]->get( $key );
919 if ( $value === false ) {
922 return unserialize( $value );
926 public function startWrite( $code ) {
927 if ( !file_exists( $this->directory
) ) {
928 if ( !wfMkdirParents( $this->directory
, null, __METHOD__
) ) {
929 throw new MWException( "Unable to create the localisation store " .
930 "directory \"{$this->directory}\"" );
934 // Close reader to stop permission errors on write
935 if( !empty($this->readers
[$code]) ) {
936 $this->readers
[$code]->close();
939 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
940 $this->currentLang
= $code;
943 public function finishWrite() {
945 $this->writer
->close();
946 $this->writer
= null;
947 unset( $this->readers
[$this->currentLang
] );
948 $this->currentLang
= null;
951 public function set( $key, $value ) {
952 if ( is_null( $this->writer
) ) {
953 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
955 $this->writer
->set( $key, serialize( $value ) );
958 protected function getFileName( $code ) {
959 if ( !$code ||
strpos( $code, '/' ) !== false ) {
960 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
962 return "{$this->directory}/l10n_cache-$code.cdb";
967 * Null store backend, used to avoid DB errors during install
969 class LCStore_Null
implements LCStore
{
970 public function get( $code, $key ) {
974 public function startWrite( $code ) {}
975 public function finishWrite() {}
976 public function set( $key, $value ) {}
980 * A localisation cache optimised for loading large amounts of data for many
981 * languages. Used by rebuildLocalisationCache.php.
983 class LocalisationCache_BulkLoad
extends LocalisationCache
{
985 * A cache of the contents of data files.
986 * Core files are serialized to avoid using ~1GB of RAM during a recache.
988 var $fileCache = array();
991 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
992 * to keep the most recently used language codes at the end of the array, and
993 * the language codes that are ready to be deleted at the beginning.
995 var $mruLangs = array();
998 * Maximum number of languages that may be loaded into $this->data
1000 var $maxLoadedLangs = 10;
1002 protected function readPHPFile( $fileName, $fileType ) {
1003 $serialize = $fileType === 'core';
1004 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
1005 $data = parent
::readPHPFile( $fileName, $fileType );
1008 $encData = serialize( $data );
1013 $this->fileCache
[$fileName][$fileType] = $encData;
1016 } elseif ( $serialize ) {
1017 return unserialize( $this->fileCache
[$fileName][$fileType] );
1019 return $this->fileCache
[$fileName][$fileType];
1023 public function getItem( $code, $key ) {
1024 unset( $this->mruLangs
[$code] );
1025 $this->mruLangs
[$code] = true;
1026 return parent
::getItem( $code, $key );
1029 public function getSubitem( $code, $key, $subkey ) {
1030 unset( $this->mruLangs
[$code] );
1031 $this->mruLangs
[$code] = true;
1032 return parent
::getSubitem( $code, $key, $subkey );
1035 public function recache( $code ) {
1036 parent
::recache( $code );
1037 unset( $this->mruLangs
[$code] );
1038 $this->mruLangs
[$code] = true;
1042 public function unload( $code ) {
1043 unset( $this->mruLangs
[$code] );
1044 parent
::unload( $code );
1048 * Unload cached languages until there are less than $this->maxLoadedLangs
1050 protected function trimCache() {
1051 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1052 reset( $this->mruLangs
);
1053 $code = key( $this->mruLangs
);
1054 wfDebug( __METHOD__
.": unloading $code\n" );
1055 $this->unload( $code );