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', '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', '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', 'defaultUserOptionOverrides', '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 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',
134 'defaultUserOptionOverrides' );
138 * For constructor parameters, see the documentation in DefaultSettings.php
139 * for $wgLocalisationCacheConf.
143 function __construct( $conf ) {
144 global $wgCacheDirectory;
147 $storeConf = array();
148 if ( !empty( $conf['storeClass'] ) ) {
149 $storeClass = $conf['storeClass'];
151 switch ( $conf['store'] ) {
154 $storeClass = 'LCStore_CDB';
157 $storeClass = 'LCStore_DB';
160 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
163 throw new MWException(
164 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
168 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
169 if ( !empty( $conf['storeDirectory'] ) ) {
170 $storeConf['directory'] = $conf['storeDirectory'];
173 $this->store
= new $storeClass( $storeConf );
174 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
175 if ( isset( $conf[$var] ) ) {
176 $this->$var = $conf[$var];
182 * Returns true if the given key is mergeable, that is, if it is an associative
183 * array which can be merged through a fallback sequence.
185 public function isMergeableKey( $key ) {
186 if ( !isset( $this->mergeableKeys
) ) {
187 $this->mergeableKeys
= array_flip( array_merge(
188 self
::$mergeableMapKeys,
189 self
::$mergeableListKeys,
190 self
::$mergeableAliasListKeys,
191 self
::$optionalMergeKeys,
195 return isset( $this->mergeableKeys
[$key] );
201 * Warning: this may be slow for split items (messages), since it will
202 * need to fetch all of the subitems from the cache individually.
204 public function getItem( $code, $key ) {
205 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
206 wfProfileIn( __METHOD__
.'-load' );
207 $this->loadItem( $code, $key );
208 wfProfileOut( __METHOD__
.'-load' );
210 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
211 return $this->shallowFallbacks
[$code];
213 return $this->data
[$code][$key];
217 * Get a subitem, for instance a single message for a given language.
219 public function getSubitem( $code, $key, $subkey ) {
220 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] )
221 && !isset( $this->loadedItems
[$code][$key] ) )
223 wfProfileIn( __METHOD__
.'-load' );
224 $this->loadSubitem( $code, $key, $subkey );
225 wfProfileOut( __METHOD__
.'-load' );
227 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
228 return $this->data
[$code][$key][$subkey];
235 * Get the list of subitem keys for a given item.
237 * This is faster than array_keys($lc->getItem(...)) for the items listed in
240 * Will return null if the item is not found, or false if the item is not an
243 public function getSubitemList( $code, $key ) {
244 if ( in_array( $key, self
::$splitKeys ) ) {
245 return $this->getSubitem( $code, 'list', $key );
247 $item = $this->getItem( $code, $key );
248 if ( is_array( $item ) ) {
249 return array_keys( $item );
257 * Load an item into the cache.
259 protected function loadItem( $code, $key ) {
260 if ( !isset( $this->initialisedLangs
[$code] ) ) {
261 $this->initLanguage( $code );
263 // Check to see if initLanguage() loaded it for us
264 if ( isset( $this->loadedItems
[$code][$key] ) ) {
267 if ( isset( $this->shallowFallbacks
[$code] ) ) {
268 $this->loadItem( $this->shallowFallbacks
[$code], $key );
271 if ( in_array( $key, self
::$splitKeys ) ) {
272 $subkeyList = $this->getSubitem( $code, 'list', $key );
273 foreach ( $subkeyList as $subkey ) {
274 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
277 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
280 $this->data
[$code][$key] = $this->store
->get( $code, $key );
282 $this->loadedItems
[$code][$key] = true;
286 * Load a subitem into the cache
288 protected function loadSubitem( $code, $key, $subkey ) {
289 if ( !in_array( $key, self
::$splitKeys ) ) {
290 $this->loadItem( $code, $key );
293 if ( !isset( $this->initialisedLangs
[$code] ) ) {
294 $this->initLanguage( $code );
296 // Check to see if initLanguage() loaded it for us
297 if ( isset( $this->loadedItems
[$code][$key] )
298 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
302 if ( isset( $this->shallowFallbacks
[$code] ) ) {
303 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
306 $value = $this->store
->get( $code, "$key:$subkey" );
307 $this->data
[$code][$key][$subkey] = $value;
308 $this->loadedSubitems
[$code][$key][$subkey] = true;
312 * Returns true if the cache identified by $code is missing or expired.
314 public function isExpired( $code ) {
315 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
316 wfDebug( __METHOD__
."($code): forced reload\n" );
320 $deps = $this->store
->get( $code, 'deps' );
321 if ( $deps === null ) {
322 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
325 foreach ( $deps as $dep ) {
326 // Because we're unserializing stuff from cache, we
327 // could receive objects of classes that don't exist
328 // anymore (e.g. uninstalled extensions)
329 // When this happens, always expire the cache
330 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
331 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
332 get_class( $dep ) . "\n" );
340 * Initialise a language in this object. Rebuild the cache if necessary.
342 protected function initLanguage( $code ) {
343 if ( isset( $this->initialisedLangs
[$code] ) ) {
346 $this->initialisedLangs
[$code] = true;
348 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
349 if ( !Language
::isValidBuiltInCode( $code ) ) {
350 $this->initShallowFallback( $code, 'en' );
354 # Recache the data if necessary
355 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
356 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
357 $this->recache( $code );
358 } elseif ( $code === 'en' ) {
359 throw new MWException( 'MessagesEn.php is missing.' );
361 $this->initShallowFallback( $code, 'en' );
367 $preload = $this->getItem( $code, 'preload' );
368 if ( $preload === null ) {
369 if ( $this->manualRecache
) {
370 // No Messages*.php file. Do shallow fallback to en.
371 if ( $code === 'en' ) {
372 throw new MWException( 'No localisation cache found for English. ' .
373 'Please run maintenance/rebuildLocalisationCache.php.' );
375 $this->initShallowFallback( $code, 'en' );
378 throw new MWException( 'Invalid or missing localisation cache.' );
381 $this->data
[$code] = $preload;
382 foreach ( $preload as $key => $item ) {
383 if ( in_array( $key, self
::$splitKeys ) ) {
384 foreach ( $item as $subkey => $subitem ) {
385 $this->loadedSubitems
[$code][$key][$subkey] = true;
388 $this->loadedItems
[$code][$key] = true;
394 * Create a fallback from one language to another, without creating a
395 * complete persistent cache.
397 public function initShallowFallback( $primaryCode, $fallbackCode ) {
398 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
399 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
400 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
401 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
405 * Read a PHP file containing localisation data.
407 protected function readPHPFile( $_fileName, $_fileType ) {
408 // Disable APC caching
409 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
410 include( $_fileName );
411 ini_set( 'apc.cache_by_default', $_apcEnabled );
413 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
414 $data = compact( self
::$allKeys );
415 } elseif ( $_fileType == 'aliases' ) {
416 $data = compact( 'aliases' );
418 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
424 * Merge two localisation values, a primary and a fallback, overwriting the
425 * primary value in place.
427 protected function mergeItem( $key, &$value, $fallbackValue ) {
428 if ( !is_null( $value ) ) {
429 if ( !is_null( $fallbackValue ) ) {
430 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
431 $value = $value +
$fallbackValue;
432 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
433 $value = array_unique( array_merge( $fallbackValue, $value ) );
434 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
435 $value = array_merge_recursive( $value, $fallbackValue );
436 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
437 if ( !empty( $value['inherit'] ) ) {
438 $value = array_merge( $fallbackValue, $value );
440 if ( isset( $value['inherit'] ) ) {
441 unset( $value['inherit'] );
443 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
444 $this->mergeMagicWords( $value, $fallbackValue );
448 $value = $fallbackValue;
452 protected function mergeMagicWords( &$value, $fallbackValue ) {
453 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
454 if ( !isset( $value[$magicName] ) ) {
455 $value[$magicName] = $fallbackInfo;
457 $oldSynonyms = array_slice( $fallbackInfo, 1 );
458 $newSynonyms = array_slice( $value[$magicName], 1 );
459 $synonyms = array_values( array_unique( array_merge(
460 $newSynonyms, $oldSynonyms ) ) );
461 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
467 * Given an array mapping language code to localisation value, such as is
468 * found in extension *.i18n.php files, iterate through a fallback sequence
469 * to merge the given data with an existing primary value.
471 * Returns true if any data from the extension array was used, false
474 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
476 foreach ( $codeSequence as $code ) {
477 if ( isset( $fallbackValue[$code] ) ) {
478 $this->mergeItem( $key, $value, $fallbackValue[$code] );
486 * Load localisation data for a given language for both core and extensions
487 * and save it to the persistent cache store and the process cache
489 public function recache( $code ) {
490 static $recursionGuard = array();
491 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
492 wfProfileIn( __METHOD__
);
495 throw new MWException( "Invalid language code requested" );
497 $this->recachedLangs
[$code] = true;
500 $initialData = array_combine(
502 array_fill( 0, count( self
::$allKeys ), null ) );
503 $coreData = $initialData;
506 # Load the primary localisation from the source file
507 $fileName = Language
::getMessagesFileName( $code );
508 if ( !file_exists( $fileName ) ) {
509 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
510 $coreData['fallback'] = 'en';
512 $deps[] = new FileDependency( $fileName );
513 $data = $this->readPHPFile( $fileName, 'core' );
514 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
516 # Merge primary localisation
517 foreach ( $data as $key => $value ) {
518 $this->mergeItem( $key, $coreData[$key], $value );
522 # Fill in the fallback if it's not there already
523 if ( is_null( $coreData['fallback'] ) ) {
524 $coreData['fallback'] = $code === 'en' ?
false : 'en';
527 if ( $coreData['fallback'] !== false ) {
528 # Guard against circular references
529 if ( isset( $recursionGuard[$code] ) ) {
530 throw new MWException( "Error: Circular fallback reference in language code $code" );
532 $recursionGuard[$code] = true;
534 # Load the fallback localisation item by item and merge it
535 $deps = array_merge( $deps, $this->getItem( $coreData['fallback'], 'deps' ) );
536 foreach ( self
::$allKeys as $key ) {
537 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
538 $fallbackValue = $this->getItem( $coreData['fallback'], $key );
539 $this->mergeItem( $key, $coreData[$key], $fallbackValue );
542 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
543 array_unshift( $fallbackSequence, $coreData['fallback'] );
544 $coreData['fallbackSequence'] = $fallbackSequence;
545 unset( $recursionGuard[$code] );
547 $coreData['fallbackSequence'] = array();
549 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
551 # Load the extension localisations
552 # This is done after the core because we know the fallback sequence now.
553 # But it has a higher precedence for merging so that we can support things
554 # like site-specific message overrides.
555 $allData = $initialData;
556 foreach ( $wgExtensionMessagesFiles as $fileName ) {
557 $data = $this->readPHPFile( $fileName, 'extension' );
559 foreach ( $data as $key => $item ) {
560 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
565 $deps[] = new FileDependency( $fileName );
569 # Load deprecated $wgExtensionAliasesFiles
570 foreach ( $wgExtensionAliasesFiles as $fileName ) {
571 $data = $this->readPHPFile( $fileName, 'aliases' );
572 if ( !isset( $data['aliases'] ) ) {
575 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
576 $allData['specialPageAliases'], $data['aliases'] );
578 $deps[] = new FileDependency( $fileName );
582 # Merge core data into extension data
583 foreach ( $coreData as $key => $item ) {
584 $this->mergeItem( $key, $allData[$key], $item );
587 # Add cache dependencies for any referenced globals
588 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
589 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
590 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
592 # Add dependencies to the cache entry
593 $allData['deps'] = $deps;
595 # Replace spaces with underscores in namespace names
596 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
598 # And do the same for special page aliases. $page is an array.
599 foreach ( $allData['specialPageAliases'] as &$page ) {
600 $page = str_replace( ' ', '_', $page );
602 # Decouple the reference to prevent accidental damage
605 # Fix broken defaultUserOptionOverrides
606 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
607 $allData['defaultUserOptionOverrides'] = array();
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 if ( is_null( $allData['defaultUserOptionOverrides'] ) ) {
620 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
621 'Check that your languages/messages/MessagesEn.php file is intact.' );
624 # Set the preload key
625 $allData['preload'] = $this->buildPreload( $allData );
627 # Save to the process cache and register the items loaded
628 $this->data
[$code] = $allData;
629 foreach ( $allData as $key => $item ) {
630 $this->loadedItems
[$code][$key] = true;
633 # Save to the persistent cache
634 $this->store
->startWrite( $code );
635 foreach ( $allData as $key => $value ) {
636 if ( in_array( $key, self
::$splitKeys ) ) {
637 foreach ( $value as $subkey => $subvalue ) {
638 $this->store
->set( "$key:$subkey", $subvalue );
641 $this->store
->set( $key, $value );
644 $this->store
->finishWrite();
646 # Clear out the MessageBlobStore
647 # HACK: If using a null (i.e. disabled) storage backend, we
648 # can't write to the MessageBlobStore either
649 if ( !$this->store
instanceof LCStore_Null
) {
650 MessageBlobStore
::clear();
653 wfProfileOut( __METHOD__
);
657 * Build the preload item from the given pre-cache data.
659 * The preload item will be loaded automatically, improving performance
660 * for the commonly-requested items it contains.
662 protected function buildPreload( $data ) {
663 $preload = array( 'messages' => array() );
664 foreach ( self
::$preloadedKeys as $key ) {
665 $preload[$key] = $data[$key];
667 foreach ( $data['preloadedMessages'] as $subkey ) {
668 if ( isset( $data['messages'][$subkey] ) ) {
669 $subitem = $data['messages'][$subkey];
673 $preload['messages'][$subkey] = $subitem;
679 * Unload the data for a given language from the object cache.
680 * Reduces memory usage.
682 public function unload( $code ) {
683 unset( $this->data
[$code] );
684 unset( $this->loadedItems
[$code] );
685 unset( $this->loadedSubitems
[$code] );
686 unset( $this->initialisedLangs
[$code] );
687 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
688 if ( $fbCode === $code ) {
689 $this->unload( $shallowCode );
697 public function unloadAll() {
698 foreach ( $this->initialisedLangs
as $lang => $unused ) {
699 $this->unload( $lang );
704 * Disable the storage backend
706 public function disableBackend() {
707 $this->store
= new LCStore_Null
;
708 $this->manualRecache
= false;
713 * Interface for the persistence layer of LocalisationCache.
715 * The persistence layer is two-level hierarchical cache. The first level
716 * is the language, the second level is the item or subitem.
718 * Since the data for a whole language is rebuilt in one operation, it needs
719 * to have a fast and atomic method for deleting or replacing all of the
720 * current data for a given language. The interface reflects this bulk update
721 * operation. Callers writing to the cache must first call startWrite(), then
722 * will call set() a couple of thousand times, then will call finishWrite()
723 * to commit the operation. When finishWrite() is called, the cache is
724 * expected to delete all data previously stored for that language.
726 * The values stored are PHP variables suitable for serialize(). Implementations
727 * of LCStore are responsible for serializing and unserializing.
732 * @param $code Language code
733 * @param $key Cache key
735 function get( $code, $key );
738 * Start a write transaction.
739 * @param $code Language code
741 function startWrite( $code );
744 * Finish a write transaction.
746 function finishWrite();
749 * Set a key to a given value. startWrite() must be called before this
750 * is called, and finishWrite() must be called afterwards.
752 function set( $key, $value );
757 * LCStore implementation which uses the standard DB functions to store data.
758 * This will work on any MediaWiki installation.
760 class LCStore_DB
implements LCStore
{
762 var $writesDone = false;
764 var $readOnly = false;
766 public function get( $code, $key ) {
767 if ( $this->writesDone
) {
768 $db = wfGetDB( DB_MASTER
);
770 $db = wfGetDB( DB_SLAVE
);
772 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
773 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
775 return unserialize( $row->lc_value
);
781 public function startWrite( $code ) {
782 if ( $this->readOnly
) {
786 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
788 $this->dbw
= wfGetDB( DB_MASTER
);
791 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
792 } catch ( DBQueryError
$e ) {
793 if ( $this->dbw
->wasReadOnlyError() ) {
794 $this->readOnly
= true;
795 $this->dbw
->rollback();
796 $this->dbw
->ignoreErrors( false );
802 $this->currentLang
= $code;
803 $this->batch
= array();
806 public function finishWrite() {
807 if ( $this->readOnly
) {
810 if ( $this->batch
) {
811 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
813 $this->dbw
->commit();
814 $this->currentLang
= null;
816 $this->batch
= array();
817 $this->writesDone
= true;
820 public function set( $key, $value ) {
821 if ( $this->readOnly
) {
824 if ( is_null( $this->currentLang
) ) {
825 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
827 $this->batch
[] = array(
828 'lc_lang' => $this->currentLang
,
830 'lc_value' => serialize( $value ) );
831 if ( count( $this->batch
) >= 100 ) {
832 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
833 $this->batch
= array();
839 * LCStore implementation which stores data as a collection of CDB files in the
840 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
841 * will throw an exception.
843 * Profiling indicates that on Linux, this implementation outperforms MySQL if
844 * the directory is on a local filesystem and there is ample kernel cache
845 * space. The performance advantage is greater when the DBA extension is
846 * available than it is with the PHP port.
848 * See Cdb.php and http://cr.yp.to/cdb.html
850 class LCStore_CDB
implements LCStore
{
851 var $readers, $writer, $currentLang, $directory;
853 function __construct( $conf = array() ) {
854 global $wgCacheDirectory;
855 if ( isset( $conf['directory'] ) ) {
856 $this->directory
= $conf['directory'];
858 $this->directory
= $wgCacheDirectory;
862 public function get( $code, $key ) {
863 if ( !isset( $this->readers
[$code] ) ) {
864 $fileName = $this->getFileName( $code );
865 if ( !file_exists( $fileName ) ) {
866 $this->readers
[$code] = false;
868 $this->readers
[$code] = CdbReader
::open( $fileName );
871 if ( !$this->readers
[$code] ) {
874 $value = $this->readers
[$code]->get( $key );
875 if ( $value === false ) {
878 return unserialize( $value );
882 public function startWrite( $code ) {
883 if ( !file_exists( $this->directory
) ) {
884 if ( !wfMkdirParents( $this->directory
) ) {
885 throw new MWException( "Unable to create the localisation store " .
886 "directory \"{$this->directory}\"" );
889 // Close reader to stop permission errors on write
890 if( !empty($this->readers
[$code]) ) {
891 $this->readers
[$code]->close();
893 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
894 $this->currentLang
= $code;
897 public function finishWrite() {
899 $this->writer
->close();
900 $this->writer
= null;
901 unset( $this->readers
[$this->currentLang
] );
902 $this->currentLang
= null;
905 public function set( $key, $value ) {
906 if ( is_null( $this->writer
) ) {
907 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
909 $this->writer
->set( $key, serialize( $value ) );
912 protected function getFileName( $code ) {
913 if ( !$code ||
strpos( $code, '/' ) !== false ) {
914 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
916 return "{$this->directory}/l10n_cache-$code.cdb";
921 * Null store backend, used to avoid DB errors during install
923 class LCStore_Null
implements LCStore
{
924 public function get( $code, $key ) {
928 public function startWrite( $code ) {}
929 public function finishWrite() {}
930 public function set( $key, $value ) {}
934 * A localisation cache optimised for loading large amounts of data for many
935 * languages. Used by rebuildLocalisationCache.php.
937 class LocalisationCache_BulkLoad
extends LocalisationCache
{
939 * A cache of the contents of data files.
940 * Core files are serialized to avoid using ~1GB of RAM during a recache.
942 var $fileCache = array();
945 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
946 * to keep the most recently used language codes at the end of the array, and
947 * the language codes that are ready to be deleted at the beginning.
949 var $mruLangs = array();
952 * Maximum number of languages that may be loaded into $this->data
954 var $maxLoadedLangs = 10;
956 protected function readPHPFile( $fileName, $fileType ) {
957 $serialize = $fileType === 'core';
958 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
959 $data = parent
::readPHPFile( $fileName, $fileType );
961 $encData = serialize( $data );
965 $this->fileCache
[$fileName][$fileType] = $encData;
967 } elseif ( $serialize ) {
968 return unserialize( $this->fileCache
[$fileName][$fileType] );
970 return $this->fileCache
[$fileName][$fileType];
974 public function getItem( $code, $key ) {
975 unset( $this->mruLangs
[$code] );
976 $this->mruLangs
[$code] = true;
977 return parent
::getItem( $code, $key );
980 public function getSubitem( $code, $key, $subkey ) {
981 unset( $this->mruLangs
[$code] );
982 $this->mruLangs
[$code] = true;
983 return parent
::getSubitem( $code, $key, $subkey );
986 public function recache( $code ) {
987 parent
::recache( $code );
988 unset( $this->mruLangs
[$code] );
989 $this->mruLangs
[$code] = true;
993 public function unload( $code ) {
994 unset( $this->mruLangs
[$code] );
995 parent
::unload( $code );
999 * Unload cached languages until there are less than $this->maxLoadedLangs
1001 protected function trimCache() {
1002 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1003 reset( $this->mruLangs
);
1004 $code = key( $this->mruLangs
);
1005 wfDebug( __METHOD__
.": unloading $code\n" );
1006 $this->unload( $code );