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.
49 * A 2-d associative array, code/key, where presence indicates that the item
50 * is loaded. Value arbitrary.
52 * For split items, if set, this indicates that all of the subitems have been
55 var $loadedItems = array();
58 * A 3-d associative array, code/key/subkey, where presence indicates that
59 * the subitem is loaded. Only used for the split items, i.e. messages.
61 var $loadedSubitems = array();
64 * An array where presence of a key indicates that that language has been
65 * initialised. Initialisation includes checking for cache expiry and doing
66 * any necessary updates.
68 var $initialisedLangs = array();
71 * An array mapping non-existent pseudo-languages to fallback languages. This
72 * is filled by initShallowFallback() when data is requested from a language
73 * that lacks a Messages*.php file.
75 var $shallowFallbacks = array();
78 * An array where the keys are codes that have been recached by this instance.
80 var $recachedLangs = array();
85 static public $allKeys = array(
86 'fallback', 'namespaceNames', 'bookstoreList',
87 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
88 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
89 'linkTrail', 'namespaceAliases',
90 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
91 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
92 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
93 'digitGroupingPattern'
97 * Keys for items which consist of associative arrays, which may be merged
98 * by a fallback sequence.
100 static public $mergeableMapKeys = array( 'messages', 'namespaceNames',
101 'dateFormats', 'imageFiles', 'preloadedMessages',
105 * Keys for items which are a numbered array.
107 static public $mergeableListKeys = array( 'extraUserToggles' );
110 * Keys for items which contain an array of arrays of equivalent aliases
111 * for each subitem. The aliases may be merged by a fallback sequence.
113 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
116 * Keys for items which contain an associative array, and may be merged if
117 * the primary value contains the special array key "inherit". That array
118 * key is removed after the first merge.
120 static public $optionalMergeKeys = array( 'bookstoreList' );
123 * Keys for items that are formatted like $magicWords
125 static public $magicWordKeys = array( 'magicWords' );
128 * Keys for items where the subitems are stored in the backend separately.
130 static public $splitKeys = array( 'messages' );
133 * Keys which are loaded automatically by initLanguage()
135 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames' );
137 var $mergeableKeys = array();
141 * For constructor parameters, see the documentation in DefaultSettings.php
142 * for $wgLocalisationCacheConf.
146 function __construct( $conf ) {
147 global $wgCacheDirectory;
150 $storeConf = array();
151 if ( !empty( $conf['storeClass'] ) ) {
152 $storeClass = $conf['storeClass'];
154 switch ( $conf['store'] ) {
157 $storeClass = 'LCStore_CDB';
160 $storeClass = 'LCStore_DB';
163 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
166 throw new MWException(
167 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
171 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
172 if ( !empty( $conf['storeDirectory'] ) ) {
173 $storeConf['directory'] = $conf['storeDirectory'];
176 $this->store
= new $storeClass( $storeConf );
177 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
178 if ( isset( $conf[$var] ) ) {
179 $this->$var = $conf[$var];
185 * Returns true if the given key is mergeable, that is, if it is an associative
186 * array which can be merged through a fallback sequence.
190 public function isMergeableKey( $key ) {
191 if ( !isset( $this->mergeableKeys
) ) {
192 $this->mergeableKeys
= array_flip( array_merge(
193 self
::$mergeableMapKeys,
194 self
::$mergeableListKeys,
195 self
::$mergeableAliasListKeys,
196 self
::$optionalMergeKeys,
200 return isset( $this->mergeableKeys
[$key] );
206 * Warning: this may be slow for split items (messages), since it will
207 * need to fetch all of the subitems from the cache individually.
212 public function getItem( $code, $key ) {
213 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
214 wfProfileIn( __METHOD__
.'-load' );
215 $this->loadItem( $code, $key );
216 wfProfileOut( __METHOD__
.'-load' );
219 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
220 return $this->shallowFallbacks
[$code];
223 return $this->data
[$code][$key];
227 * Get a subitem, for instance a single message for a given language.
233 public function getSubitem( $code, $key, $subkey ) {
234 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] )
235 && !isset( $this->loadedItems
[$code][$key] ) )
237 wfProfileIn( __METHOD__
.'-load' );
238 $this->loadSubitem( $code, $key, $subkey );
239 wfProfileOut( __METHOD__
.'-load' );
242 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
243 return $this->data
[$code][$key][$subkey];
250 * Get the list of subitem keys for a given item.
252 * This is faster than array_keys($lc->getItem(...)) for the items listed in
255 * Will return null if the item is not found, or false if the item is not an
259 * @return bool|null|string
261 public function getSubitemList( $code, $key ) {
262 if ( in_array( $key, self
::$splitKeys ) ) {
263 return $this->getSubitem( $code, 'list', $key );
265 $item = $this->getItem( $code, $key );
266 if ( is_array( $item ) ) {
267 return array_keys( $item );
275 * Load an item into the cache.
279 protected function loadItem( $code, $key ) {
280 if ( !isset( $this->initialisedLangs
[$code] ) ) {
281 $this->initLanguage( $code );
284 // Check to see if initLanguage() loaded it for us
285 if ( isset( $this->loadedItems
[$code][$key] ) ) {
289 if ( isset( $this->shallowFallbacks
[$code] ) ) {
290 $this->loadItem( $this->shallowFallbacks
[$code], $key );
294 if ( in_array( $key, self
::$splitKeys ) ) {
295 $subkeyList = $this->getSubitem( $code, 'list', $key );
296 foreach ( $subkeyList as $subkey ) {
297 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
300 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
303 $this->data
[$code][$key] = $this->store
->get( $code, $key );
306 $this->loadedItems
[$code][$key] = true;
310 * Load a subitem into the cache
316 protected function loadSubitem( $code, $key, $subkey ) {
317 if ( !in_array( $key, self
::$splitKeys ) ) {
318 $this->loadItem( $code, $key );
322 if ( !isset( $this->initialisedLangs
[$code] ) ) {
323 $this->initLanguage( $code );
326 // Check to see if initLanguage() loaded it for us
327 if ( isset( $this->loadedItems
[$code][$key] )
328 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
333 if ( isset( $this->shallowFallbacks
[$code] ) ) {
334 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
338 $value = $this->store
->get( $code, "$key:$subkey" );
339 $this->data
[$code][$key][$subkey] = $value;
340 $this->loadedSubitems
[$code][$key][$subkey] = true;
344 * Returns true if the cache identified by $code is missing or expired.
346 public function isExpired( $code ) {
347 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
348 wfDebug( __METHOD__
."($code): forced reload\n" );
352 $deps = $this->store
->get( $code, 'deps' );
353 if ( $deps === null ) {
354 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
358 foreach ( $deps as $dep ) {
359 // Because we're unserializing stuff from cache, we
360 // could receive objects of classes that don't exist
361 // anymore (e.g. uninstalled extensions)
362 // When this happens, always expire the cache
363 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
364 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
365 get_class( $dep ) . "\n" );
374 * Initialise a language in this object. Rebuild the cache if necessary.
377 protected function initLanguage( $code ) {
378 if ( isset( $this->initialisedLangs
[$code] ) ) {
382 $this->initialisedLangs
[$code] = true;
384 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
385 if ( !Language
::isValidBuiltInCode( $code ) ) {
386 $this->initShallowFallback( $code, 'en' );
390 # Recache the data if necessary
391 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
392 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
393 $this->recache( $code );
394 } elseif ( $code === 'en' ) {
395 throw new MWException( 'MessagesEn.php is missing.' );
397 $this->initShallowFallback( $code, 'en' );
403 $preload = $this->getItem( $code, 'preload' );
404 if ( $preload === null ) {
405 if ( $this->manualRecache
) {
406 // No Messages*.php file. Do shallow fallback to en.
407 if ( $code === 'en' ) {
408 throw new MWException( 'No localisation cache found for English. ' .
409 'Please run maintenance/rebuildLocalisationCache.php.' );
411 $this->initShallowFallback( $code, 'en' );
414 throw new MWException( 'Invalid or missing localisation cache.' );
417 $this->data
[$code] = $preload;
418 foreach ( $preload as $key => $item ) {
419 if ( in_array( $key, self
::$splitKeys ) ) {
420 foreach ( $item as $subkey => $subitem ) {
421 $this->loadedSubitems
[$code][$key][$subkey] = true;
424 $this->loadedItems
[$code][$key] = true;
430 * Create a fallback from one language to another, without creating a
431 * complete persistent cache.
432 * @param $primaryCode
433 * @param $fallbackCode
435 public function initShallowFallback( $primaryCode, $fallbackCode ) {
436 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
437 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
438 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
439 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
443 * Read a PHP file containing localisation data.
448 protected function readPHPFile( $_fileName, $_fileType ) {
449 // Disable APC caching
450 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
451 include( $_fileName );
452 ini_set( 'apc.cache_by_default', $_apcEnabled );
454 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
455 $data = compact( self
::$allKeys );
456 } elseif ( $_fileType == 'aliases' ) {
457 $data = compact( 'aliases' );
459 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
466 * Merge two localisation values, a primary and a fallback, overwriting the
467 * primary value in place.
470 * @param $fallbackValue
472 protected function mergeItem( $key, &$value, $fallbackValue ) {
473 if ( !is_null( $value ) ) {
474 if ( !is_null( $fallbackValue ) ) {
475 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
476 $value = $value +
$fallbackValue;
477 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
478 $value = array_unique( array_merge( $fallbackValue, $value ) );
479 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
480 $value = array_merge_recursive( $value, $fallbackValue );
481 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
482 if ( !empty( $value['inherit'] ) ) {
483 $value = array_merge( $fallbackValue, $value );
486 if ( isset( $value['inherit'] ) ) {
487 unset( $value['inherit'] );
489 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
490 $this->mergeMagicWords( $value, $fallbackValue );
494 $value = $fallbackValue;
500 * @param $fallbackValue
502 protected function mergeMagicWords( &$value, $fallbackValue ) {
503 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
504 if ( !isset( $value[$magicName] ) ) {
505 $value[$magicName] = $fallbackInfo;
507 $oldSynonyms = array_slice( $fallbackInfo, 1 );
508 $newSynonyms = array_slice( $value[$magicName], 1 );
509 $synonyms = array_values( array_unique( array_merge(
510 $newSynonyms, $oldSynonyms ) ) );
511 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
517 * Given an array mapping language code to localisation value, such as is
518 * found in extension *.i18n.php files, iterate through a fallback sequence
519 * to merge the given data with an existing primary value.
521 * Returns true if any data from the extension array was used, false
523 * @param $codeSequence
526 * @param $fallbackValue
529 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
531 foreach ( $codeSequence as $code ) {
532 if ( isset( $fallbackValue[$code] ) ) {
533 $this->mergeItem( $key, $value, $fallbackValue[$code] );
542 * Load localisation data for a given language for both core and extensions
543 * and save it to the persistent cache store and the process cache
546 public function recache( $code ) {
547 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
548 wfProfileIn( __METHOD__
);
551 throw new MWException( "Invalid language code requested" );
553 $this->recachedLangs
[$code] = true;
556 $initialData = array_combine(
558 array_fill( 0, count( self
::$allKeys ), null ) );
559 $coreData = $initialData;
562 # Load the primary localisation from the source file
563 $fileName = Language
::getMessagesFileName( $code );
564 if ( !file_exists( $fileName ) ) {
565 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
566 $coreData['fallback'] = 'en';
568 $deps[] = new FileDependency( $fileName );
569 $data = $this->readPHPFile( $fileName, 'core' );
570 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
572 # Merge primary localisation
573 foreach ( $data as $key => $value ) {
574 $this->mergeItem( $key, $coreData[$key], $value );
579 # Fill in the fallback if it's not there already
580 if ( is_null( $coreData['fallback'] ) ) {
581 $coreData['fallback'] = $code === 'en' ?
false : 'en';
584 if ( $coreData['fallback'] === false ) {
585 $coreData['fallbackSequence'] = array();
587 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
588 $len = count( $coreData['fallbackSequence'] );
590 # Ensure that the sequence ends at en
591 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
592 $coreData['fallbackSequence'][] = 'en';
595 # Load the fallback localisation item by item and merge it
596 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
597 # Load the secondary localisation from the source file to
598 # avoid infinite cycles on cyclic fallbacks
599 $fbFilename = Language
::getMessagesFileName( $fbCode );
601 if ( !file_exists( $fbFilename ) ) {
605 $deps[] = new FileDependency( $fbFilename );
606 $fbData = $this->readPHPFile( $fbFilename, 'core' );
608 foreach ( self
::$allKeys as $key ) {
609 if ( !isset( $fbData[$key] ) ) {
613 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
614 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
620 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
622 # Load the extension localisations
623 # This is done after the core because we know the fallback sequence now.
624 # But it has a higher precedence for merging so that we can support things
625 # like site-specific message overrides.
626 $allData = $initialData;
627 foreach ( $wgExtensionMessagesFiles as $fileName ) {
628 $data = $this->readPHPFile( $fileName, 'extension' );
631 foreach ( $data as $key => $item ) {
632 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
638 $deps[] = new FileDependency( $fileName );
642 # Load deprecated $wgExtensionAliasesFiles
643 foreach ( $wgExtensionAliasesFiles as $fileName ) {
644 $data = $this->readPHPFile( $fileName, 'aliases' );
646 if ( !isset( $data['aliases'] ) ) {
650 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
651 $allData['specialPageAliases'], $data['aliases'] );
654 $deps[] = new FileDependency( $fileName );
658 # Merge core data into extension data
659 foreach ( $coreData as $key => $item ) {
660 $this->mergeItem( $key, $allData[$key], $item );
663 # Add cache dependencies for any referenced globals
664 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
665 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
666 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
668 # Add dependencies to the cache entry
669 $allData['deps'] = $deps;
671 # Replace spaces with underscores in namespace names
672 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
674 # And do the same for special page aliases. $page is an array.
675 foreach ( $allData['specialPageAliases'] as &$page ) {
676 $page = str_replace( ' ', '_', $page );
678 # Decouple the reference to prevent accidental damage
682 $allData['list'] = array();
683 foreach ( self
::$splitKeys as $key ) {
684 $allData['list'][$key] = array_keys( $allData[$key] );
688 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
690 if ( is_null( $allData['namespaceNames'] ) ) {
691 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
692 'Check that your languages/messages/MessagesEn.php file is intact.' );
695 # Set the preload key
696 $allData['preload'] = $this->buildPreload( $allData );
698 # Save to the process cache and register the items loaded
699 $this->data
[$code] = $allData;
700 foreach ( $allData as $key => $item ) {
701 $this->loadedItems
[$code][$key] = true;
704 # Save to the persistent cache
705 $this->store
->startWrite( $code );
706 foreach ( $allData as $key => $value ) {
707 if ( in_array( $key, self
::$splitKeys ) ) {
708 foreach ( $value as $subkey => $subvalue ) {
709 $this->store
->set( "$key:$subkey", $subvalue );
712 $this->store
->set( $key, $value );
715 $this->store
->finishWrite();
717 # Clear out the MessageBlobStore
718 # HACK: If using a null (i.e. disabled) storage backend, we
719 # can't write to the MessageBlobStore either
720 if ( !$this->store
instanceof LCStore_Null
) {
721 MessageBlobStore
::clear();
724 wfProfileOut( __METHOD__
);
728 * Build the preload item from the given pre-cache data.
730 * The preload item will be loaded automatically, improving performance
731 * for the commonly-requested items it contains.
735 protected function buildPreload( $data ) {
736 $preload = array( 'messages' => array() );
737 foreach ( self
::$preloadedKeys as $key ) {
738 $preload[$key] = $data[$key];
741 foreach ( $data['preloadedMessages'] as $subkey ) {
742 if ( isset( $data['messages'][$subkey] ) ) {
743 $subitem = $data['messages'][$subkey];
747 $preload['messages'][$subkey] = $subitem;
754 * Unload the data for a given language from the object cache.
755 * Reduces memory usage.
758 public function unload( $code ) {
759 unset( $this->data
[$code] );
760 unset( $this->loadedItems
[$code] );
761 unset( $this->loadedSubitems
[$code] );
762 unset( $this->initialisedLangs
[$code] );
764 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
765 if ( $fbCode === $code ) {
766 $this->unload( $shallowCode );
774 public function unloadAll() {
775 foreach ( $this->initialisedLangs
as $lang => $unused ) {
776 $this->unload( $lang );
781 * Disable the storage backend
783 public function disableBackend() {
784 $this->store
= new LCStore_Null
;
785 $this->manualRecache
= false;
790 * Interface for the persistence layer of LocalisationCache.
792 * The persistence layer is two-level hierarchical cache. The first level
793 * is the language, the second level is the item or subitem.
795 * Since the data for a whole language is rebuilt in one operation, it needs
796 * to have a fast and atomic method for deleting or replacing all of the
797 * current data for a given language. The interface reflects this bulk update
798 * operation. Callers writing to the cache must first call startWrite(), then
799 * will call set() a couple of thousand times, then will call finishWrite()
800 * to commit the operation. When finishWrite() is called, the cache is
801 * expected to delete all data previously stored for that language.
803 * The values stored are PHP variables suitable for serialize(). Implementations
804 * of LCStore are responsible for serializing and unserializing.
809 * @param $code Language code
810 * @param $key Cache key
812 function get( $code, $key );
815 * Start a write transaction.
816 * @param $code Language code
818 function startWrite( $code );
821 * Finish a write transaction.
823 function finishWrite();
826 * Set a key to a given value. startWrite() must be called before this
827 * is called, and finishWrite() must be called afterwards.
831 function set( $key, $value );
835 * LCStore implementation which uses the standard DB functions to store data.
836 * This will work on any MediaWiki installation.
838 class LCStore_DB
implements LCStore
{
840 var $writesDone = false;
847 var $readOnly = false;
849 public function get( $code, $key ) {
850 if ( $this->writesDone
) {
851 $db = wfGetDB( DB_MASTER
);
853 $db = wfGetDB( DB_SLAVE
);
855 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
856 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
858 return unserialize( $row->lc_value
);
864 public function startWrite( $code ) {
865 if ( $this->readOnly
) {
870 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
873 $this->dbw
= wfGetDB( DB_MASTER
);
876 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
877 } catch ( DBQueryError
$e ) {
878 if ( $this->dbw
->wasReadOnlyError() ) {
879 $this->readOnly
= true;
880 $this->dbw
->rollback();
881 $this->dbw
->ignoreErrors( false );
888 $this->currentLang
= $code;
889 $this->batch
= array();
892 public function finishWrite() {
893 if ( $this->readOnly
) {
897 if ( $this->batch
) {
898 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
901 $this->dbw
->commit();
902 $this->currentLang
= null;
904 $this->batch
= array();
905 $this->writesDone
= true;
908 public function set( $key, $value ) {
909 if ( $this->readOnly
) {
913 if ( is_null( $this->currentLang
) ) {
914 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
917 $this->batch
[] = array(
918 'lc_lang' => $this->currentLang
,
920 'lc_value' => serialize( $value ) );
922 if ( count( $this->batch
) >= 100 ) {
923 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
924 $this->batch
= array();
930 * LCStore implementation which stores data as a collection of CDB files in the
931 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
932 * will throw an exception.
934 * Profiling indicates that on Linux, this implementation outperforms MySQL if
935 * the directory is on a local filesystem and there is ample kernel cache
936 * space. The performance advantage is greater when the DBA extension is
937 * available than it is with the PHP port.
939 * See Cdb.php and http://cr.yp.to/cdb.html
941 class LCStore_CDB
implements LCStore
{
942 var $readers, $writer, $currentLang, $directory;
944 function __construct( $conf = array() ) {
945 global $wgCacheDirectory;
947 if ( isset( $conf['directory'] ) ) {
948 $this->directory
= $conf['directory'];
950 $this->directory
= $wgCacheDirectory;
954 public function get( $code, $key ) {
955 if ( !isset( $this->readers
[$code] ) ) {
956 $fileName = $this->getFileName( $code );
958 if ( !file_exists( $fileName ) ) {
959 $this->readers
[$code] = false;
961 $this->readers
[$code] = CdbReader
::open( $fileName );
965 if ( !$this->readers
[$code] ) {
968 $value = $this->readers
[$code]->get( $key );
970 if ( $value === false ) {
973 return unserialize( $value );
977 public function startWrite( $code ) {
978 if ( !file_exists( $this->directory
) ) {
979 if ( !wfMkdirParents( $this->directory
, null, __METHOD__
) ) {
980 throw new MWException( "Unable to create the localisation store " .
981 "directory \"{$this->directory}\"" );
985 // Close reader to stop permission errors on write
986 if( !empty($this->readers
[$code]) ) {
987 $this->readers
[$code]->close();
990 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
991 $this->currentLang
= $code;
994 public function finishWrite() {
996 $this->writer
->close();
997 $this->writer
= null;
998 unset( $this->readers
[$this->currentLang
] );
999 $this->currentLang
= null;
1002 public function set( $key, $value ) {
1003 if ( is_null( $this->writer
) ) {
1004 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
1006 $this->writer
->set( $key, serialize( $value ) );
1009 protected function getFileName( $code ) {
1010 if ( !$code ||
strpos( $code, '/' ) !== false ) {
1011 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
1013 return "{$this->directory}/l10n_cache-$code.cdb";
1018 * Null store backend, used to avoid DB errors during install
1020 class LCStore_Null
implements LCStore
{
1021 public function get( $code, $key ) {
1025 public function startWrite( $code ) {}
1026 public function finishWrite() {}
1027 public function set( $key, $value ) {}
1031 * A localisation cache optimised for loading large amounts of data for many
1032 * languages. Used by rebuildLocalisationCache.php.
1034 class LocalisationCache_BulkLoad
extends LocalisationCache
{
1036 * A cache of the contents of data files.
1037 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1039 var $fileCache = array();
1042 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1043 * to keep the most recently used language codes at the end of the array, and
1044 * the language codes that are ready to be deleted at the beginning.
1046 var $mruLangs = array();
1049 * Maximum number of languages that may be loaded into $this->data
1051 var $maxLoadedLangs = 10;
1056 * @return array|mixed
1058 protected function readPHPFile( $fileName, $fileType ) {
1059 $serialize = $fileType === 'core';
1060 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
1061 $data = parent
::readPHPFile( $fileName, $fileType );
1064 $encData = serialize( $data );
1069 $this->fileCache
[$fileName][$fileType] = $encData;
1072 } elseif ( $serialize ) {
1073 return unserialize( $this->fileCache
[$fileName][$fileType] );
1075 return $this->fileCache
[$fileName][$fileType];
1084 public function getItem( $code, $key ) {
1085 unset( $this->mruLangs
[$code] );
1086 $this->mruLangs
[$code] = true;
1087 return parent
::getItem( $code, $key );
1096 public function getSubitem( $code, $key, $subkey ) {
1097 unset( $this->mruLangs
[$code] );
1098 $this->mruLangs
[$code] = true;
1099 return parent
::getSubitem( $code, $key, $subkey );
1105 public function recache( $code ) {
1106 parent
::recache( $code );
1107 unset( $this->mruLangs
[$code] );
1108 $this->mruLangs
[$code] = true;
1115 public function unload( $code ) {
1116 unset( $this->mruLangs
[$code] );
1117 parent
::unload( $code );
1121 * Unload cached languages until there are less than $this->maxLoadedLangs
1123 protected function trimCache() {
1124 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1125 reset( $this->mruLangs
);
1126 $code = key( $this->mruLangs
);
1127 wfDebug( __METHOD__
.": unloading $code\n" );
1128 $this->unload( $code );