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 $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
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 && !isset( $this->loadedItems
[$code][$key] ) )
224 wfProfileIn( __METHOD__
.'-load' );
225 $this->loadSubitem( $code, $key, $subkey );
226 wfProfileOut( __METHOD__
.'-load' );
228 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
229 return $this->data
[$code][$key][$subkey];
236 * Get the list of subitem keys for a given item.
238 * This is faster than array_keys($lc->getItem(...)) for the items listed in
241 * Will return null if the item is not found, or false if the item is not an
244 public function getSubitemList( $code, $key ) {
245 if ( in_array( $key, self
::$splitKeys ) ) {
246 return $this->getSubitem( $code, 'list', $key );
248 $item = $this->getItem( $code, $key );
249 if ( is_array( $item ) ) {
250 return array_keys( $item );
258 * Load an item into the cache.
260 protected function loadItem( $code, $key ) {
261 if ( !isset( $this->initialisedLangs
[$code] ) ) {
262 $this->initLanguage( $code );
264 // Check to see if initLanguage() loaded it for us
265 if ( isset( $this->loadedItems
[$code][$key] ) ) {
268 if ( isset( $this->shallowFallbacks
[$code] ) ) {
269 $this->loadItem( $this->shallowFallbacks
[$code], $key );
272 if ( in_array( $key, self
::$splitKeys ) ) {
273 $subkeyList = $this->getSubitem( $code, 'list', $key );
274 foreach ( $subkeyList as $subkey ) {
275 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
278 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
281 $this->data
[$code][$key] = $this->store
->get( $code, $key );
283 $this->loadedItems
[$code][$key] = true;
287 * Load a subitem into the cache
289 protected function loadSubitem( $code, $key, $subkey ) {
290 if ( !in_array( $key, self
::$splitKeys ) ) {
291 $this->loadItem( $code, $key );
294 if ( !isset( $this->initialisedLangs
[$code] ) ) {
295 $this->initLanguage( $code );
297 // Check to see if initLanguage() loaded it for us
298 if ( isset( $this->loadedItems
[$code][$key] )
299 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
303 if ( isset( $this->shallowFallbacks
[$code] ) ) {
304 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
307 $value = $this->store
->get( $code, "$key:$subkey" );
308 $this->data
[$code][$key][$subkey] = $value;
309 $this->loadedSubitems
[$code][$key][$subkey] = true;
313 * Returns true if the cache identified by $code is missing or expired.
315 public function isExpired( $code ) {
316 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
317 wfDebug( __METHOD__
."($code): forced reload\n" );
321 $deps = $this->store
->get( $code, 'deps' );
322 if ( $deps === null ) {
323 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
326 foreach ( $deps as $dep ) {
327 // Because we're unserializing stuff from cache, we
328 // could receive objects of classes that don't exist
329 // anymore (e.g. uninstalled extensions)
330 // When this happens, always expire the cache
331 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
332 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
333 get_class( $dep ) . "\n" );
341 * Initialise a language in this object. Rebuild the cache if necessary.
343 protected function initLanguage( $code ) {
344 if ( isset( $this->initialisedLangs
[$code] ) ) {
347 $this->initialisedLangs
[$code] = true;
349 # Recache the data if necessary
350 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
351 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
352 $this->recache( $code );
353 } elseif ( $code === 'en' ) {
354 throw new MWException( 'MessagesEn.php is missing.' );
356 $this->initShallowFallback( $code, 'en' );
362 $preload = $this->getItem( $code, 'preload' );
363 if ( $preload === null ) {
364 if ( $this->manualRecache
) {
365 // No Messages*.php file. Do shallow fallback to en.
366 if ( $code === 'en' ) {
367 throw new MWException( 'No localisation cache found for English. ' .
368 'Please run maintenance/rebuildLocalisationCache.php.' );
370 $this->initShallowFallback( $code, 'en' );
373 throw new MWException( 'Invalid or missing localisation cache.' );
376 $this->data
[$code] = $preload;
377 foreach ( $preload as $key => $item ) {
378 if ( in_array( $key, self
::$splitKeys ) ) {
379 foreach ( $item as $subkey => $subitem ) {
380 $this->loadedSubitems
[$code][$key][$subkey] = true;
383 $this->loadedItems
[$code][$key] = true;
389 * Create a fallback from one language to another, without creating a
390 * complete persistent cache.
392 public function initShallowFallback( $primaryCode, $fallbackCode ) {
393 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
394 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
395 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
396 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
400 * Read a PHP file containing localisation data.
402 protected function readPHPFile( $_fileName, $_fileType ) {
403 // Disable APC caching
404 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
405 include( $_fileName );
406 ini_set( 'apc.cache_by_default', $_apcEnabled );
408 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
409 $data = compact( self
::$allKeys );
410 } elseif ( $_fileType == 'aliases' ) {
411 $data = compact( 'aliases' );
413 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
419 * Merge two localisation values, a primary and a fallback, overwriting the
420 * primary value in place.
422 protected function mergeItem( $key, &$value, $fallbackValue ) {
423 if ( !is_null( $value ) ) {
424 if ( !is_null( $fallbackValue ) ) {
425 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
426 $value = $value +
$fallbackValue;
427 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
428 $value = array_unique( array_merge( $fallbackValue, $value ) );
429 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
430 $value = array_merge_recursive( $value, $fallbackValue );
431 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
432 if ( !empty( $value['inherit'] ) ) {
433 $value = array_merge( $fallbackValue, $value );
435 if ( isset( $value['inherit'] ) ) {
436 unset( $value['inherit'] );
441 $value = $fallbackValue;
446 * Given an array mapping language code to localisation value, such as is
447 * found in extension *.i18n.php files, iterate through a fallback sequence
448 * to merge the given data with an existing primary value.
450 * Returns true if any data from the extension array was used, false
453 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
455 foreach ( $codeSequence as $code ) {
456 if ( isset( $fallbackValue[$code] ) ) {
457 $this->mergeItem( $key, $value, $fallbackValue[$code] );
465 * Load localisation data for a given language for both core and extensions
466 * and save it to the persistent cache store and the process cache
468 public function recache( $code ) {
469 static $recursionGuard = array();
470 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
471 wfProfileIn( __METHOD__
);
474 throw new MWException( "Invalid language code requested" );
476 $this->recachedLangs
[$code] = true;
479 $initialData = array_combine(
481 array_fill( 0, count( self
::$allKeys ), null ) );
482 $coreData = $initialData;
485 # Load the primary localisation from the source file
486 $fileName = Language
::getMessagesFileName( $code );
487 if ( !file_exists( $fileName ) ) {
488 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
489 $coreData['fallback'] = 'en';
491 $deps[] = new FileDependency( $fileName );
492 $data = $this->readPHPFile( $fileName, 'core' );
493 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
495 # Merge primary localisation
496 foreach ( $data as $key => $value ) {
497 $this->mergeItem( $key, $coreData[$key], $value );
501 # Fill in the fallback if it's not there already
502 if ( is_null( $coreData['fallback'] ) ) {
503 $coreData['fallback'] = $code === 'en' ?
false : 'en';
506 if ( $coreData['fallback'] !== false ) {
507 # Guard against circular references
508 if ( isset( $recursionGuard[$code] ) ) {
509 throw new MWException( "Error: Circular fallback reference in language code $code" );
511 $recursionGuard[$code] = true;
513 # Load the fallback localisation item by item and merge it
514 $deps = array_merge( $deps, $this->getItem( $coreData['fallback'], 'deps' ) );
515 foreach ( self
::$allKeys as $key ) {
516 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
517 $fallbackValue = $this->getItem( $coreData['fallback'], $key );
518 $this->mergeItem( $key, $coreData[$key], $fallbackValue );
521 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
522 array_unshift( $fallbackSequence, $coreData['fallback'] );
523 $coreData['fallbackSequence'] = $fallbackSequence;
524 unset( $recursionGuard[$code] );
526 $coreData['fallbackSequence'] = array();
528 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
530 # Load the extension localisations
531 # This is done after the core because we know the fallback sequence now.
532 # But it has a higher precedence for merging so that we can support things
533 # like site-specific message overrides.
534 $allData = $initialData;
535 foreach ( $wgExtensionMessagesFiles as $fileName ) {
536 $data = $this->readPHPFile( $fileName, 'extension' );
538 foreach ( $data as $key => $item ) {
539 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
544 $deps[] = new FileDependency( $fileName );
548 # Load deprecated $wgExtensionAliasesFiles
549 foreach ( $wgExtensionAliasesFiles as $fileName ) {
550 $data = $this->readPHPFile( $fileName, 'aliases' );
551 if ( !isset( $data['aliases'] ) ) {
554 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
555 $allData['specialPageAliases'], $data['aliases'] );
557 $deps[] = new FileDependency( $fileName );
561 # Merge core data into extension data
562 foreach ( $coreData as $key => $item ) {
563 $this->mergeItem( $key, $allData[$key], $item );
566 # Add cache dependencies for any referenced globals
567 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
568 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
569 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
571 # Add dependencies to the cache entry
572 $allData['deps'] = $deps;
574 # Replace spaces with underscores in namespace names
575 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
577 # And do the same for special page aliases. $page is an array.
578 foreach ( $allData['specialPageAliases'] as &$page ) {
579 $page = str_replace( ' ', '_', $page );
581 # Decouple the reference to prevent accidental damage
584 # Fix broken defaultUserOptionOverrides
585 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
586 $allData['defaultUserOptionOverrides'] = array();
590 $allData['list'] = array();
591 foreach ( self
::$splitKeys as $key ) {
592 $allData['list'][$key] = array_keys( $allData[$key] );
596 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
598 if ( is_null( $allData['defaultUserOptionOverrides'] ) ) {
599 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
600 'Check that your languages/messages/MessagesEn.php file is intact.' );
603 # Set the preload key
604 $allData['preload'] = $this->buildPreload( $allData );
606 # Save to the process cache and register the items loaded
607 $this->data
[$code] = $allData;
608 foreach ( $allData as $key => $item ) {
609 $this->loadedItems
[$code][$key] = true;
612 # Save to the persistent cache
613 $this->store
->startWrite( $code );
614 foreach ( $allData as $key => $value ) {
615 if ( in_array( $key, self
::$splitKeys ) ) {
616 foreach ( $value as $subkey => $subvalue ) {
617 $this->store
->set( "$key:$subkey", $subvalue );
620 $this->store
->set( $key, $value );
623 $this->store
->finishWrite();
625 # Clear out the MessageBlobStore
626 # HACK: If using a null (i.e. disabled) storage backend, we
627 # can't write to the MessageBlobStore either
628 if ( !$this->store
instanceof LCStore_Null
) {
629 MessageBlobStore
::clear();
632 wfProfileOut( __METHOD__
);
636 * Build the preload item from the given pre-cache data.
638 * The preload item will be loaded automatically, improving performance
639 * for the commonly-requested items it contains.
641 protected function buildPreload( $data ) {
642 $preload = array( 'messages' => array() );
643 foreach ( self
::$preloadedKeys as $key ) {
644 $preload[$key] = $data[$key];
646 foreach ( $data['preloadedMessages'] as $subkey ) {
647 if ( isset( $data['messages'][$subkey] ) ) {
648 $subitem = $data['messages'][$subkey];
652 $preload['messages'][$subkey] = $subitem;
658 * Unload the data for a given language from the object cache.
659 * Reduces memory usage.
661 public function unload( $code ) {
662 unset( $this->data
[$code] );
663 unset( $this->loadedItems
[$code] );
664 unset( $this->loadedSubitems
[$code] );
665 unset( $this->initialisedLangs
[$code] );
666 // We don't unload legacyData because there's no way to get it back
667 // again, it's not really a cache
668 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
669 if ( $fbCode === $code ) {
670 $this->unload( $shallowCode );
678 public function unloadAll() {
679 foreach ( $this->initialisedLangs
as $lang => $unused ) {
680 $this->unload( $lang );
685 * Add messages to the cache, from an extension that has not yet been
686 * migrated to $wgExtensionMessages or the LocalisationCacheRecache hook.
687 * Called by deprecated function $wgMessageCache->addMessages().
689 public function addLegacyMessages( $messages ) {
690 foreach ( $messages as $lang => $langMessages ) {
691 if ( isset( $this->legacyData
[$lang]['messages'] ) ) {
692 $this->legacyData
[$lang]['messages'] =
693 $langMessages +
$this->legacyData
[$lang]['messages'];
695 $this->legacyData
[$lang]['messages'] = $langMessages;
701 * Disable the storage backend
703 public function disableBackend() {
704 $this->store
= new LCStore_Null
;
705 $this->manualRecache
= false;
710 * Interface for the persistence layer of LocalisationCache.
712 * The persistence layer is two-level hierarchical cache. The first level
713 * is the language, the second level is the item or subitem.
715 * Since the data for a whole language is rebuilt in one operation, it needs
716 * to have a fast and atomic method for deleting or replacing all of the
717 * current data for a given language. The interface reflects this bulk update
718 * operation. Callers writing to the cache must first call startWrite(), then
719 * will call set() a couple of thousand times, then will call finishWrite()
720 * to commit the operation. When finishWrite() is called, the cache is
721 * expected to delete all data previously stored for that language.
723 * The values stored are PHP variables suitable for serialize(). Implementations
724 * of LCStore are responsible for serializing and unserializing.
729 * @param $code Language code
730 * @param $key Cache key
732 public function get( $code, $key );
735 * Start a write transaction.
736 * @param $code Language code
738 public function startWrite( $code );
741 * Finish a write transaction.
743 public function finishWrite();
746 * Set a key to a given value. startWrite() must be called before this
747 * is called, and finishWrite() must be called afterwards.
749 public function set( $key, $value );
754 * LCStore implementation which uses the standard DB functions to store data.
755 * This will work on any MediaWiki installation.
757 class LCStore_DB
implements LCStore
{
759 var $writesDone = false;
761 var $readOnly = false;
763 public function get( $code, $key ) {
764 if ( $this->writesDone
) {
765 $db = wfGetDB( DB_MASTER
);
767 $db = wfGetDB( DB_SLAVE
);
769 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
770 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
772 return unserialize( $row->lc_value
);
778 public function startWrite( $code ) {
779 if ( $this->readOnly
) {
783 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
785 $this->dbw
= wfGetDB( DB_MASTER
);
788 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
789 } catch ( DBQueryError
$e ) {
790 if ( $this->dbw
->wasReadOnlyError() ) {
791 $this->readOnly
= true;
792 $this->dbw
->rollback();
793 $this->dbw
->ignoreErrors( false );
799 $this->currentLang
= $code;
800 $this->batch
= array();
803 public function finishWrite() {
804 if ( $this->readOnly
) {
807 if ( $this->batch
) {
808 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
810 $this->dbw
->commit();
811 $this->currentLang
= null;
813 $this->batch
= array();
814 $this->writesDone
= true;
817 public function set( $key, $value ) {
818 if ( $this->readOnly
) {
821 if ( is_null( $this->currentLang
) ) {
822 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
824 $this->batch
[] = array(
825 'lc_lang' => $this->currentLang
,
827 'lc_value' => serialize( $value ) );
828 if ( count( $this->batch
) >= 100 ) {
829 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
830 $this->batch
= array();
836 * LCStore implementation which stores data as a collection of CDB files in the
837 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
838 * will throw an exception.
840 * Profiling indicates that on Linux, this implementation outperforms MySQL if
841 * the directory is on a local filesystem and there is ample kernel cache
842 * space. The performance advantage is greater when the DBA extension is
843 * available than it is with the PHP port.
845 * See Cdb.php and http://cr.yp.to/cdb.html
847 class LCStore_CDB
implements LCStore
{
848 var $readers, $writer, $currentLang, $directory;
850 function __construct( $conf = array() ) {
851 global $wgCacheDirectory;
852 if ( isset( $conf['directory'] ) ) {
853 $this->directory
= $conf['directory'];
855 $this->directory
= $wgCacheDirectory;
859 public function get( $code, $key ) {
860 if ( !isset( $this->readers
[$code] ) ) {
861 $fileName = $this->getFileName( $code );
862 if ( !file_exists( $fileName ) ) {
863 $this->readers
[$code] = false;
865 $this->readers
[$code] = CdbReader
::open( $fileName );
868 if ( !$this->readers
[$code] ) {
871 $value = $this->readers
[$code]->get( $key );
872 if ( $value === false ) {
875 return unserialize( $value );
879 public function startWrite( $code ) {
880 if ( !file_exists( $this->directory
) ) {
881 if ( !wfMkdirParents( $this->directory
) ) {
882 throw new MWException( "Unable to create the localisation store " .
883 "directory \"{$this->directory}\"" );
886 // Close reader to stop permission errors on write
887 if( !empty($this->readers
[$code]) ) {
888 $this->readers
[$code]->close();
890 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
891 $this->currentLang
= $code;
894 public function finishWrite() {
896 $this->writer
->close();
897 $this->writer
= null;
898 unset( $this->readers
[$this->currentLang
] );
899 $this->currentLang
= null;
902 public function set( $key, $value ) {
903 if ( is_null( $this->writer
) ) {
904 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
906 $this->writer
->set( $key, serialize( $value ) );
909 protected function getFileName( $code ) {
910 if ( !$code ||
strpos( $code, '/' ) !== false ) {
911 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
913 return "{$this->directory}/l10n_cache-$code.cdb";
918 * Null store backend, used to avoid DB errors during install
920 class LCStore_Null
implements LCStore
{
921 public function get( $code, $key ) {
925 public function startWrite( $code ) {}
926 public function finishWrite() {}
927 public function set( $key, $value ) {}
931 * A localisation cache optimised for loading large amounts of data for many
932 * languages. Used by rebuildLocalisationCache.php.
934 class LocalisationCache_BulkLoad
extends LocalisationCache
{
936 * A cache of the contents of data files.
937 * Core files are serialized to avoid using ~1GB of RAM during a recache.
939 var $fileCache = array();
942 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
943 * to keep the most recently used language codes at the end of the array, and
944 * the language codes that are ready to be deleted at the beginning.
946 var $mruLangs = array();
949 * Maximum number of languages that may be loaded into $this->data
951 var $maxLoadedLangs = 10;
953 protected function readPHPFile( $fileName, $fileType ) {
954 $serialize = $fileType === 'core';
955 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
956 $data = parent
::readPHPFile( $fileName, $fileType );
958 $encData = serialize( $data );
962 $this->fileCache
[$fileName][$fileType] = $encData;
964 } elseif ( $serialize ) {
965 return unserialize( $this->fileCache
[$fileName][$fileType] );
967 return $this->fileCache
[$fileName][$fileType];
971 public function getItem( $code, $key ) {
972 unset( $this->mruLangs
[$code] );
973 $this->mruLangs
[$code] = true;
974 return parent
::getItem( $code, $key );
977 public function getSubitem( $code, $key, $subkey ) {
978 unset( $this->mruLangs
[$code] );
979 $this->mruLangs
[$code] = true;
980 return parent
::getSubitem( $code, $key, $subkey );
983 public function recache( $code ) {
984 parent
::recache( $code );
985 unset( $this->mruLangs
[$code] );
986 $this->mruLangs
[$code] = true;
990 public function unload( $code ) {
991 unset( $this->mruLangs
[$code] );
992 parent
::unload( $code );
996 * Unload cached languages until there are less than $this->maxLoadedLangs
998 protected function trimCache() {
999 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1000 reset( $this->mruLangs
);
1001 $code = key( $this->mruLangs
);
1002 wfDebug( __METHOD__
.": unloading $code\n" );
1003 $this->unload( $code );