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', '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 that are formatted like $magicWords
129 static public $magicWordKeys = array( 'magicWords' );
132 * Keys for items where the subitems are stored in the backend separately.
134 static public $splitKeys = array( 'messages' );
137 * Keys which are loaded automatically by initLanguage()
139 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames',
140 'defaultUserOptionOverrides' );
144 * For constructor parameters, see the documentation in DefaultSettings.php
145 * for $wgLocalisationCacheConf.
147 function __construct( $conf ) {
148 global $wgCacheDirectory;
151 $storeConf = array();
152 if ( !empty( $conf['storeClass'] ) ) {
153 $storeClass = $conf['storeClass'];
155 switch ( $conf['store'] ) {
158 $storeClass = 'LCStore_CDB';
161 $storeClass = 'LCStore_DB';
164 $storeClass = $wgCacheDirectory ? 'LCStore_CDB' : 'LCStore_DB';
167 throw new MWException(
168 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
172 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
173 if ( !empty( $conf['storeDirectory'] ) ) {
174 $storeConf['directory'] = $conf['storeDirectory'];
177 $this->store = new $storeClass( $storeConf );
178 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
179 if ( isset( $conf[$var] ) ) {
180 $this->$var = $conf[$var];
186 * Returns true if the given key is mergeable, that is, if it is an associative
187 * array which can be merged through a fallback sequence.
189 public function isMergeableKey( $key ) {
190 if ( !isset( $this->mergeableKeys ) ) {
191 $this->mergeableKeys = array_flip( array_merge(
192 self::$mergeableMapKeys,
193 self::$mergeableListKeys,
194 self::$mergeableAliasListKeys,
195 self::$optionalMergeKeys,
199 return isset( $this->mergeableKeys[$key] );
205 * Warning: this may be slow for split items (messages), since it will
206 * need to fetch all of the subitems from the cache individually.
208 public function getItem( $code, $key ) {
209 if ( !isset( $this->loadedItems[$code][$key] ) ) {
210 wfProfileIn( __METHOD__.'-load' );
211 $this->loadItem( $code, $key );
212 wfProfileOut( __METHOD__.'-load' );
214 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
215 return $this->shallowFallbacks[$code];
217 return $this->data[$code][$key];
221 * Get a subitem, for instance a single message for a given language.
223 public function getSubitem( $code, $key, $subkey ) {
224 if ( isset( $this->legacyData[$code][$key][$subkey] ) ) {
225 return $this->legacyData[$code][$key][$subkey];
227 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] )
228 && !isset( $this->loadedItems[$code][$key] ) )
230 wfProfileIn( __METHOD__.'-load' );
231 $this->loadSubitem( $code, $key, $subkey );
232 wfProfileOut( __METHOD__.'-load' );
234 if ( isset( $this->data[$code][$key][$subkey] ) ) {
235 return $this->data[$code][$key][$subkey];
242 * Get the list of subitem keys for a given item.
244 * This is faster than array_keys($lc->getItem(...)) for the items listed in
247 * Will return null if the item is not found, or false if the item is not an
250 public function getSubitemList( $code, $key ) {
251 if ( in_array( $key, self::$splitKeys ) ) {
252 return $this->getSubitem( $code, 'list', $key );
254 $item = $this->getItem( $code, $key );
255 if ( is_array( $item ) ) {
256 return array_keys( $item );
264 * Load an item into the cache.
266 protected function loadItem( $code, $key ) {
267 if ( !isset( $this->initialisedLangs[$code] ) ) {
268 $this->initLanguage( $code );
270 // Check to see if initLanguage() loaded it for us
271 if ( isset( $this->loadedItems[$code][$key] ) ) {
274 if ( isset( $this->shallowFallbacks[$code] ) ) {
275 $this->loadItem( $this->shallowFallbacks[$code], $key );
278 if ( in_array( $key, self::$splitKeys ) ) {
279 $subkeyList = $this->getSubitem( $code, 'list', $key );
280 foreach ( $subkeyList as $subkey ) {
281 if ( isset( $this->data[$code][$key][$subkey] ) ) {
284 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
287 $this->data[$code][$key] = $this->store->get( $code, $key );
289 $this->loadedItems[$code][$key] = true;
293 * Load a subitem into the cache
295 protected function loadSubitem( $code, $key, $subkey ) {
296 if ( !in_array( $key, self::$splitKeys ) ) {
297 $this->loadItem( $code, $key );
300 if ( !isset( $this->initialisedLangs[$code] ) ) {
301 $this->initLanguage( $code );
303 // Check to see if initLanguage() loaded it for us
304 if ( isset( $this->loadedItems[$code][$key] )
305 || isset( $this->loadedSubitems[$code][$key][$subkey] ) )
309 if ( isset( $this->shallowFallbacks[$code] ) ) {
310 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
313 $value = $this->store->get( $code, "$key:$subkey" );
314 $this->data[$code][$key][$subkey] = $value;
315 $this->loadedSubitems[$code][$key][$subkey] = true;
319 * Returns true if the cache identified by $code is missing or expired.
321 public function isExpired( $code ) {
322 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
323 wfDebug( __METHOD__."($code): forced reload\n" );
327 $deps = $this->store->get( $code, 'deps' );
328 if ( $deps === null ) {
329 wfDebug( __METHOD__."($code): cache missing, need to make one\n" );
332 foreach ( $deps as $dep ) {
333 // Because we're unserializing stuff from cache, we
334 // could receive objects of classes that don't exist
335 // anymore (e.g. uninstalled extensions)
336 // When this happens, always expire the cache
337 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
338 wfDebug( __METHOD__."($code): cache for $code expired due to " .
339 get_class( $dep ) . "\n" );
347 * Initialise a language in this object. Rebuild the cache if necessary.
349 protected function initLanguage( $code ) {
350 if ( isset( $this->initialisedLangs[$code] ) ) {
353 $this->initialisedLangs[$code] = true;
355 # Recache the data if necessary
356 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
357 if ( file_exists( Language::getMessagesFileName( $code ) ) ) {
358 $this->recache( $code );
359 } elseif ( $code === 'en' ) {
360 throw new MWException( 'MessagesEn.php is missing.' );
362 $this->initShallowFallback( $code, 'en' );
368 $preload = $this->getItem( $code, 'preload' );
369 if ( $preload === null ) {
370 if ( $this->manualRecache ) {
371 // No Messages*.php file. Do shallow fallback to en.
372 if ( $code === 'en' ) {
373 throw new MWException( 'No localisation cache found for English. ' .
374 'Please run maintenance/rebuildLocalisationCache.php.' );
376 $this->initShallowFallback( $code, 'en' );
379 throw new MWException( 'Invalid or missing localisation cache.' );
382 $this->data[$code] = $preload;
383 foreach ( $preload as $key => $item ) {
384 if ( in_array( $key, self::$splitKeys ) ) {
385 foreach ( $item as $subkey => $subitem ) {
386 $this->loadedSubitems[$code][$key][$subkey] = true;
389 $this->loadedItems[$code][$key] = true;
395 * Create a fallback from one language to another, without creating a
396 * complete persistent cache.
398 public function initShallowFallback( $primaryCode, $fallbackCode ) {
399 $this->data[$primaryCode] =& $this->data[$fallbackCode];
400 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
401 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
402 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
406 * Read a PHP file containing localisation data.
408 protected function readPHPFile( $_fileName, $_fileType ) {
409 // Disable APC caching
410 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
411 include( $_fileName );
412 ini_set( 'apc.cache_by_default', $_apcEnabled );
414 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
415 $data = compact( self::$allKeys );
416 } elseif ( $_fileType == 'aliases' ) {
417 $data = compact( 'aliases' );
419 throw new MWException( __METHOD__.": Invalid file type: $_fileType" );
425 * Merge two localisation values, a primary and a fallback, overwriting the
426 * primary value in place.
428 protected function mergeItem( $key, &$value, $fallbackValue ) {
429 if ( !is_null( $value ) ) {
430 if ( !is_null( $fallbackValue ) ) {
431 if ( in_array( $key, self::$mergeableMapKeys ) ) {
432 $value = $value + $fallbackValue;
433 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
434 $value = array_unique( array_merge( $fallbackValue, $value ) );
435 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
436 $value = array_merge_recursive( $value, $fallbackValue );
437 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
438 if ( !empty( $value['inherit'] ) ) {
439 $value = array_merge( $fallbackValue, $value );
441 if ( isset( $value['inherit'] ) ) {
442 unset( $value['inherit'] );
444 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
445 $this->mergeMagicWords( $value, $fallbackValue );
449 $value = $fallbackValue;
453 protected function mergeMagicWords( &$value, $fallbackValue ) {
454 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
455 if ( !isset( $value[$magicName] ) ) {
456 $value[$magicName] = $fallbackInfo;
458 $oldSynonyms = array_slice( $fallbackInfo, 1 );
459 $newSynonyms = array_slice( $value[$magicName], 1 );
460 $synonyms = array_values( array_unique( array_merge(
461 $newSynonyms, $oldSynonyms ) ) );
462 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
468 * Given an array mapping language code to localisation value, such as is
469 * found in extension *.i18n.php files, iterate through a fallback sequence
470 * to merge the given data with an existing primary value.
472 * Returns true if any data from the extension array was used, false
475 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
477 foreach ( $codeSequence as $code ) {
478 if ( isset( $fallbackValue[$code] ) ) {
479 $this->mergeItem( $key, $value, $fallbackValue[$code] );
487 * Load localisation data for a given language for both core and extensions
488 * and save it to the persistent cache store and the process cache
490 public function recache( $code ) {
491 static $recursionGuard = array();
492 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
493 wfProfileIn( __METHOD__ );
496 throw new MWException( "Invalid language code requested" );
498 $this->recachedLangs[$code] = true;
501 $initialData = array_combine(
503 array_fill( 0, count( self::$allKeys ), null ) );
504 $coreData = $initialData;
507 # Load the primary localisation from the source file
508 $fileName = Language::getMessagesFileName( $code );
509 if ( !file_exists( $fileName ) ) {
510 wfDebug( __METHOD__.": no localisation file for $code, using fallback to en\n" );
511 $coreData['fallback'] = 'en';
513 $deps[] = new FileDependency( $fileName );
514 $data = $this->readPHPFile( $fileName, 'core' );
515 wfDebug( __METHOD__.": got localisation for $code from source\n" );
517 # Merge primary localisation
518 foreach ( $data as $key => $value ) {
519 $this->mergeItem( $key, $coreData[$key], $value );
523 # Fill in the fallback if it's not there already
524 if ( is_null( $coreData['fallback'] ) ) {
525 $coreData['fallback'] = $code === 'en' ? false : 'en';
528 if ( $coreData['fallback'] !== false ) {
529 # Guard against circular references
530 if ( isset( $recursionGuard[$code] ) ) {
531 throw new MWException( "Error: Circular fallback reference in language code $code" );
533 $recursionGuard[$code] = true;
535 # Load the fallback localisation item by item and merge it
536 $deps = array_merge( $deps, $this->getItem( $coreData['fallback'], 'deps' ) );
537 foreach ( self::$allKeys as $key ) {
538 if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) {
539 $fallbackValue = $this->getItem( $coreData['fallback'], $key );
540 $this->mergeItem( $key, $coreData[$key], $fallbackValue );
543 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
544 array_unshift( $fallbackSequence, $coreData['fallback'] );
545 $coreData['fallbackSequence'] = $fallbackSequence;
546 unset( $recursionGuard[$code] );
548 $coreData['fallbackSequence'] = array();
550 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
552 # Load the extension localisations
553 # This is done after the core because we know the fallback sequence now.
554 # But it has a higher precedence for merging so that we can support things
555 # like site-specific message overrides.
556 $allData = $initialData;
557 foreach ( $wgExtensionMessagesFiles as $fileName ) {
558 $data = $this->readPHPFile( $fileName, 'extension' );
560 foreach ( $data as $key => $item ) {
561 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
566 $deps[] = new FileDependency( $fileName );
570 # Load deprecated $wgExtensionAliasesFiles
571 foreach ( $wgExtensionAliasesFiles as $fileName ) {
572 $data = $this->readPHPFile( $fileName, 'aliases' );
573 if ( !isset( $data['aliases'] ) ) {
576 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
577 $allData['specialPageAliases'], $data['aliases'] );
579 $deps[] = new FileDependency( $fileName );
583 # Merge core data into extension data
584 foreach ( $coreData as $key => $item ) {
585 $this->mergeItem( $key, $allData[$key], $item );
588 # Add cache dependencies for any referenced globals
589 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
590 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
591 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
593 # Add dependencies to the cache entry
594 $allData['deps'] = $deps;
596 # Replace spaces with underscores in namespace names
597 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
599 # And do the same for special page aliases. $page is an array.
600 foreach ( $allData['specialPageAliases'] as &$page ) {
601 $page = str_replace( ' ', '_', $page );
603 # Decouple the reference to prevent accidental damage
606 # Fix broken defaultUserOptionOverrides
607 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
608 $allData['defaultUserOptionOverrides'] = array();
612 $allData['list'] = array();
613 foreach ( self::$splitKeys as $key ) {
614 $allData['list'][$key] = array_keys( $allData[$key] );
618 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
620 if ( is_null( $allData['defaultUserOptionOverrides'] ) ) {
621 throw new MWException( __METHOD__.': Localisation data failed sanity check! ' .
622 'Check that your languages/messages/MessagesEn.php file is intact.' );
625 # Set the preload key
626 $allData['preload'] = $this->buildPreload( $allData );
628 # Save to the process cache and register the items loaded
629 $this->data[$code] = $allData;
630 foreach ( $allData as $key => $item ) {
631 $this->loadedItems[$code][$key] = true;
634 # Save to the persistent cache
635 $this->store->startWrite( $code );
636 foreach ( $allData as $key => $value ) {
637 if ( in_array( $key, self::$splitKeys ) ) {
638 foreach ( $value as $subkey => $subvalue ) {
639 $this->store->set( "$key:$subkey", $subvalue );
642 $this->store->set( $key, $value );
645 $this->store->finishWrite();
647 # Clear out the MessageBlobStore
648 # HACK: If using a null (i.e. disabled) storage backend, we
649 # can't write to the MessageBlobStore either
650 if ( !$this->store instanceof LCStore_Null ) {
651 MessageBlobStore::clear();
654 wfProfileOut( __METHOD__ );
658 * Build the preload item from the given pre-cache data.
660 * The preload item will be loaded automatically, improving performance
661 * for the commonly-requested items it contains.
663 protected function buildPreload( $data ) {
664 $preload = array( 'messages' => array() );
665 foreach ( self::$preloadedKeys as $key ) {
666 $preload[$key] = $data[$key];
668 foreach ( $data['preloadedMessages'] as $subkey ) {
669 if ( isset( $data['messages'][$subkey] ) ) {
670 $subitem = $data['messages'][$subkey];
674 $preload['messages'][$subkey] = $subitem;
680 * Unload the data for a given language from the object cache.
681 * Reduces memory usage.
683 public function unload( $code ) {
684 unset( $this->data[$code] );
685 unset( $this->loadedItems[$code] );
686 unset( $this->loadedSubitems[$code] );
687 unset( $this->initialisedLangs[$code] );
688 // We don't unload legacyData because there's no way to get it back
689 // again, it's not really a cache
690 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
691 if ( $fbCode === $code ) {
692 $this->unload( $shallowCode );
700 public function unloadAll() {
701 foreach ( $this->initialisedLangs as $lang => $unused ) {
702 $this->unload( $lang );
707 * Add messages to the cache, from an extension that has not yet been
708 * migrated to $wgExtensionMessages or the LocalisationCacheRecache hook.
709 * Called by deprecated function $wgMessageCache->addMessages().
711 public function addLegacyMessages( $messages ) {
712 foreach ( $messages as $lang => $langMessages ) {
713 if ( isset( $this->legacyData[$lang]['messages'] ) ) {
714 $this->legacyData[$lang]['messages'] =
715 $langMessages + $this->legacyData[$lang]['messages'];
717 $this->legacyData[$lang]['messages'] = $langMessages;
723 * Disable the storage backend
725 public function disableBackend() {
726 $this->store = new LCStore_Null;
727 $this->manualRecache = false;
732 * Interface for the persistence layer of LocalisationCache.
734 * The persistence layer is two-level hierarchical cache. The first level
735 * is the language, the second level is the item or subitem.
737 * Since the data for a whole language is rebuilt in one operation, it needs
738 * to have a fast and atomic method for deleting or replacing all of the
739 * current data for a given language. The interface reflects this bulk update
740 * operation. Callers writing to the cache must first call startWrite(), then
741 * will call set() a couple of thousand times, then will call finishWrite()
742 * to commit the operation. When finishWrite() is called, the cache is
743 * expected to delete all data previously stored for that language.
745 * The values stored are PHP variables suitable for serialize(). Implementations
746 * of LCStore are responsible for serializing and unserializing.
751 * @param $code Language code
752 * @param $key Cache key
754 public function get( $code, $key );
757 * Start a write transaction.
758 * @param $code Language code
760 public function startWrite( $code );
763 * Finish a write transaction.
765 public function finishWrite();
768 * Set a key to a given value. startWrite() must be called before this
769 * is called, and finishWrite() must be called afterwards.
771 public function set( $key, $value );
776 * LCStore implementation which uses the standard DB functions to store data.
777 * This will work on any MediaWiki installation.
779 class LCStore_DB implements LCStore {
781 var $writesDone = false;
783 var $readOnly = false;
785 public function get( $code, $key ) {
786 if ( $this->writesDone ) {
787 $db = wfGetDB( DB_MASTER );
789 $db = wfGetDB( DB_SLAVE );
791 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
792 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ );
794 return unserialize( $row->lc_value );
800 public function startWrite( $code ) {
801 if ( $this->readOnly ) {
805 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
807 $this->dbw = wfGetDB( DB_MASTER );
810 $this->dbw->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__ );
811 } catch ( DBQueryError $e ) {
812 if ( $this->dbw->wasReadOnlyError() ) {
813 $this->readOnly = true;
814 $this->dbw->rollback();
815 $this->dbw->ignoreErrors( false );
821 $this->currentLang = $code;
822 $this->batch = array();
825 public function finishWrite() {
826 if ( $this->readOnly ) {
829 if ( $this->batch ) {
830 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
832 $this->dbw->commit();
833 $this->currentLang = null;
835 $this->batch = array();
836 $this->writesDone = true;
839 public function set( $key, $value ) {
840 if ( $this->readOnly ) {
843 if ( is_null( $this->currentLang ) ) {
844 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
846 $this->batch[] = array(
847 'lc_lang' => $this->currentLang,
849 'lc_value' => serialize( $value ) );
850 if ( count( $this->batch ) >= 100 ) {
851 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
852 $this->batch = array();
858 * LCStore implementation which stores data as a collection of CDB files in the
859 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
860 * will throw an exception.
862 * Profiling indicates that on Linux, this implementation outperforms MySQL if
863 * the directory is on a local filesystem and there is ample kernel cache
864 * space. The performance advantage is greater when the DBA extension is
865 * available than it is with the PHP port.
867 * See Cdb.php and http://cr.yp.to/cdb.html
869 class LCStore_CDB implements LCStore {
870 var $readers, $writer, $currentLang, $directory;
872 function __construct( $conf = array() ) {
873 global $wgCacheDirectory;
874 if ( isset( $conf['directory'] ) ) {
875 $this->directory = $conf['directory'];
877 $this->directory = $wgCacheDirectory;
881 public function get( $code, $key ) {
882 if ( !isset( $this->readers[$code] ) ) {
883 $fileName = $this->getFileName( $code );
884 if ( !file_exists( $fileName ) ) {
885 $this->readers[$code] = false;
887 $this->readers[$code] = CdbReader::open( $fileName );
890 if ( !$this->readers[$code] ) {
893 $value = $this->readers[$code]->get( $key );
894 if ( $value === false ) {
897 return unserialize( $value );
901 public function startWrite( $code ) {
902 if ( !file_exists( $this->directory ) ) {
903 if ( !wfMkdirParents( $this->directory ) ) {
904 throw new MWException( "Unable to create the localisation store " .
905 "directory \"{$this->directory}\"" );
908 // Close reader to stop permission errors on write
909 if( !empty($this->readers[$code]) ) {
910 $this->readers[$code]->close();
912 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
913 $this->currentLang = $code;
916 public function finishWrite() {
918 $this->writer->close();
919 $this->writer = null;
920 unset( $this->readers[$this->currentLang] );
921 $this->currentLang = null;
924 public function set( $key, $value ) {
925 if ( is_null( $this->writer ) ) {
926 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
928 $this->writer->set( $key, serialize( $value ) );
931 protected function getFileName( $code ) {
932 if ( !$code || strpos( $code, '/' ) !== false ) {
933 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
935 return "{$this->directory}/l10n_cache-$code.cdb";
940 * Null store backend, used to avoid DB errors during install
942 class LCStore_Null implements LCStore {
943 public function get( $code, $key ) {
947 public function startWrite( $code ) {}
948 public function finishWrite() {}
949 public function set( $key, $value ) {}
953 * A localisation cache optimised for loading large amounts of data for many
954 * languages. Used by rebuildLocalisationCache.php.
956 class LocalisationCache_BulkLoad extends LocalisationCache {
958 * A cache of the contents of data files.
959 * Core files are serialized to avoid using ~1GB of RAM during a recache.
961 var $fileCache = array();
964 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
965 * to keep the most recently used language codes at the end of the array, and
966 * the language codes that are ready to be deleted at the beginning.
968 var $mruLangs = array();
971 * Maximum number of languages that may be loaded into $this->data
973 var $maxLoadedLangs = 10;
975 protected function readPHPFile( $fileName, $fileType ) {
976 $serialize = $fileType === 'core';
977 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
978 $data = parent::readPHPFile( $fileName, $fileType );
980 $encData = serialize( $data );
984 $this->fileCache[$fileName][$fileType] = $encData;
986 } elseif ( $serialize ) {
987 return unserialize( $this->fileCache[$fileName][$fileType] );
989 return $this->fileCache[$fileName][$fileType];
993 public function getItem( $code, $key ) {
994 unset( $this->mruLangs[$code] );
995 $this->mruLangs[$code] = true;
996 return parent::getItem( $code, $key );
999 public function getSubitem( $code, $key, $subkey ) {
1000 unset( $this->mruLangs[$code] );
1001 $this->mruLangs[$code] = true;
1002 return parent::getSubitem( $code, $key, $subkey );
1005 public function recache( $code ) {
1006 parent::recache( $code );
1007 unset( $this->mruLangs[$code] );
1008 $this->mruLangs[$code] = true;
1012 public function unload( $code ) {
1013 unset( $this->mruLangs[$code] );
1014 parent::unload( $code );
1018 * Unload cached languages until there are less than $this->maxLoadedLangs
1020 protected function trimCache() {
1021 while ( count( $this->data ) > $this->maxLoadedLangs && count( $this->mruLangs ) ) {
1022 reset( $this->mruLangs );
1023 $code = key( $this->mruLangs );
1024 wfDebug( __METHOD__.": unloading $code\n" );
1025 $this->unload( $code );