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 = null;
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] ) ) {
236 wfProfileIn( __METHOD__
.'-load' );
237 $this->loadSubitem( $code, $key, $subkey );
238 wfProfileOut( __METHOD__
.'-load' );
241 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
242 return $this->data
[$code][$key][$subkey];
249 * Get the list of subitem keys for a given item.
251 * This is faster than array_keys($lc->getItem(...)) for the items listed in
254 * Will return null if the item is not found, or false if the item is not an
258 * @return bool|null|string
260 public function getSubitemList( $code, $key ) {
261 if ( in_array( $key, self
::$splitKeys ) ) {
262 return $this->getSubitem( $code, 'list', $key );
264 $item = $this->getItem( $code, $key );
265 if ( is_array( $item ) ) {
266 return array_keys( $item );
274 * Load an item into the cache.
278 protected function loadItem( $code, $key ) {
279 if ( !isset( $this->initialisedLangs
[$code] ) ) {
280 $this->initLanguage( $code );
283 // Check to see if initLanguage() loaded it for us
284 if ( isset( $this->loadedItems
[$code][$key] ) ) {
288 if ( isset( $this->shallowFallbacks
[$code] ) ) {
289 $this->loadItem( $this->shallowFallbacks
[$code], $key );
293 if ( in_array( $key, self
::$splitKeys ) ) {
294 $subkeyList = $this->getSubitem( $code, 'list', $key );
295 foreach ( $subkeyList as $subkey ) {
296 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
299 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
302 $this->data
[$code][$key] = $this->store
->get( $code, $key );
305 $this->loadedItems
[$code][$key] = true;
309 * Load a subitem into the cache
315 protected function loadSubitem( $code, $key, $subkey ) {
316 if ( !in_array( $key, self
::$splitKeys ) ) {
317 $this->loadItem( $code, $key );
321 if ( !isset( $this->initialisedLangs
[$code] ) ) {
322 $this->initLanguage( $code );
325 // Check to see if initLanguage() loaded it for us
326 if ( isset( $this->loadedItems
[$code][$key] ) ||
327 isset( $this->loadedSubitems
[$code][$key][$subkey] ) ) {
331 if ( isset( $this->shallowFallbacks
[$code] ) ) {
332 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
336 $value = $this->store
->get( $code, "$key:$subkey" );
337 $this->data
[$code][$key][$subkey] = $value;
338 $this->loadedSubitems
[$code][$key][$subkey] = true;
342 * Returns true if the cache identified by $code is missing or expired.
344 public function isExpired( $code ) {
345 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
346 wfDebug( __METHOD__
."($code): forced reload\n" );
350 $deps = $this->store
->get( $code, 'deps' );
351 if ( $deps === null ) {
352 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
356 foreach ( $deps as $dep ) {
357 // Because we're unserializing stuff from cache, we
358 // could receive objects of classes that don't exist
359 // anymore (e.g. uninstalled extensions)
360 // When this happens, always expire the cache
361 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
362 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
363 get_class( $dep ) . "\n" );
372 * Initialise a language in this object. Rebuild the cache if necessary.
375 protected function initLanguage( $code ) {
376 if ( isset( $this->initialisedLangs
[$code] ) ) {
380 $this->initialisedLangs
[$code] = true;
382 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
383 if ( !Language
::isValidBuiltInCode( $code ) ) {
384 $this->initShallowFallback( $code, 'en' );
388 # Recache the data if necessary
389 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
390 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
391 $this->recache( $code );
392 } elseif ( $code === 'en' ) {
393 throw new MWException( 'MessagesEn.php is missing.' );
395 $this->initShallowFallback( $code, 'en' );
401 $preload = $this->getItem( $code, 'preload' );
402 if ( $preload === null ) {
403 if ( $this->manualRecache
) {
404 // No Messages*.php file. Do shallow fallback to en.
405 if ( $code === 'en' ) {
406 throw new MWException( 'No localisation cache found for English. ' .
407 'Please run maintenance/rebuildLocalisationCache.php.' );
409 $this->initShallowFallback( $code, 'en' );
412 throw new MWException( 'Invalid or missing localisation cache.' );
415 $this->data
[$code] = $preload;
416 foreach ( $preload as $key => $item ) {
417 if ( in_array( $key, self
::$splitKeys ) ) {
418 foreach ( $item as $subkey => $subitem ) {
419 $this->loadedSubitems
[$code][$key][$subkey] = true;
422 $this->loadedItems
[$code][$key] = true;
428 * Create a fallback from one language to another, without creating a
429 * complete persistent cache.
430 * @param $primaryCode
431 * @param $fallbackCode
433 public function initShallowFallback( $primaryCode, $fallbackCode ) {
434 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
435 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
436 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
437 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
441 * Read a PHP file containing localisation data.
446 protected function readPHPFile( $_fileName, $_fileType ) {
447 // Disable APC caching
448 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
449 include( $_fileName );
450 ini_set( 'apc.cache_by_default', $_apcEnabled );
452 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
453 $data = compact( self
::$allKeys );
454 } elseif ( $_fileType == 'aliases' ) {
455 $data = compact( 'aliases' );
457 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
464 * Merge two localisation values, a primary and a fallback, overwriting the
465 * primary value in place.
468 * @param $fallbackValue
470 protected function mergeItem( $key, &$value, $fallbackValue ) {
471 if ( !is_null( $value ) ) {
472 if ( !is_null( $fallbackValue ) ) {
473 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
474 $value = $value +
$fallbackValue;
475 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
476 $value = array_unique( array_merge( $fallbackValue, $value ) );
477 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
478 $value = array_merge_recursive( $value, $fallbackValue );
479 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
480 if ( !empty( $value['inherit'] ) ) {
481 $value = array_merge( $fallbackValue, $value );
484 if ( isset( $value['inherit'] ) ) {
485 unset( $value['inherit'] );
487 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
488 $this->mergeMagicWords( $value, $fallbackValue );
492 $value = $fallbackValue;
498 * @param $fallbackValue
500 protected function mergeMagicWords( &$value, $fallbackValue ) {
501 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
502 if ( !isset( $value[$magicName] ) ) {
503 $value[$magicName] = $fallbackInfo;
505 $oldSynonyms = array_slice( $fallbackInfo, 1 );
506 $newSynonyms = array_slice( $value[$magicName], 1 );
507 $synonyms = array_values( array_unique( array_merge(
508 $newSynonyms, $oldSynonyms ) ) );
509 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
515 * Given an array mapping language code to localisation value, such as is
516 * found in extension *.i18n.php files, iterate through a fallback sequence
517 * to merge the given data with an existing primary value.
519 * Returns true if any data from the extension array was used, false
521 * @param $codeSequence
524 * @param $fallbackValue
527 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
529 foreach ( $codeSequence as $code ) {
530 if ( isset( $fallbackValue[$code] ) ) {
531 $this->mergeItem( $key, $value, $fallbackValue[$code] );
540 * Load localisation data for a given language for both core and extensions
541 * and save it to the persistent cache store and the process cache
544 public function recache( $code ) {
545 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
546 wfProfileIn( __METHOD__
);
549 throw new MWException( "Invalid language code requested" );
551 $this->recachedLangs
[$code] = true;
554 $initialData = array_combine(
556 array_fill( 0, count( self
::$allKeys ), null ) );
557 $coreData = $initialData;
560 # Load the primary localisation from the source file
561 $fileName = Language
::getMessagesFileName( $code );
562 if ( !file_exists( $fileName ) ) {
563 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
564 $coreData['fallback'] = 'en';
566 $deps[] = new FileDependency( $fileName );
567 $data = $this->readPHPFile( $fileName, 'core' );
568 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
570 # Merge primary localisation
571 foreach ( $data as $key => $value ) {
572 $this->mergeItem( $key, $coreData[$key], $value );
577 # Fill in the fallback if it's not there already
578 if ( is_null( $coreData['fallback'] ) ) {
579 $coreData['fallback'] = $code === 'en' ?
false : 'en';
582 if ( $coreData['fallback'] === false ) {
583 $coreData['fallbackSequence'] = array();
585 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
586 $len = count( $coreData['fallbackSequence'] );
588 # Ensure that the sequence ends at en
589 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
590 $coreData['fallbackSequence'][] = 'en';
593 # Load the fallback localisation item by item and merge it
594 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
595 # Load the secondary localisation from the source file to
596 # avoid infinite cycles on cyclic fallbacks
597 $fbFilename = Language
::getMessagesFileName( $fbCode );
599 if ( !file_exists( $fbFilename ) ) {
603 $deps[] = new FileDependency( $fbFilename );
604 $fbData = $this->readPHPFile( $fbFilename, 'core' );
606 foreach ( self
::$allKeys as $key ) {
607 if ( !isset( $fbData[$key] ) ) {
611 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
612 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
618 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
620 # Load the extension localisations
621 # This is done after the core because we know the fallback sequence now.
622 # But it has a higher precedence for merging so that we can support things
623 # like site-specific message overrides.
624 $allData = $initialData;
625 foreach ( $wgExtensionMessagesFiles as $fileName ) {
626 $data = $this->readPHPFile( $fileName, 'extension' );
629 foreach ( $data as $key => $item ) {
630 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
636 $deps[] = new FileDependency( $fileName );
640 # Load deprecated $wgExtensionAliasesFiles
641 foreach ( $wgExtensionAliasesFiles as $fileName ) {
642 $data = $this->readPHPFile( $fileName, 'aliases' );
644 if ( !isset( $data['aliases'] ) ) {
648 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
649 $allData['specialPageAliases'], $data['aliases'] );
652 $deps[] = new FileDependency( $fileName );
656 # Merge core data into extension data
657 foreach ( $coreData as $key => $item ) {
658 $this->mergeItem( $key, $allData[$key], $item );
661 # Add cache dependencies for any referenced globals
662 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
663 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
664 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
666 # Add dependencies to the cache entry
667 $allData['deps'] = $deps;
669 # Replace spaces with underscores in namespace names
670 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
672 # And do the same for special page aliases. $page is an array.
673 foreach ( $allData['specialPageAliases'] as &$page ) {
674 $page = str_replace( ' ', '_', $page );
676 # Decouple the reference to prevent accidental damage
680 $allData['list'] = array();
681 foreach ( self
::$splitKeys as $key ) {
682 $allData['list'][$key] = array_keys( $allData[$key] );
686 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
688 if ( is_null( $allData['namespaceNames'] ) ) {
689 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
690 'Check that your languages/messages/MessagesEn.php file is intact.' );
693 # Set the preload key
694 $allData['preload'] = $this->buildPreload( $allData );
696 # Save to the process cache and register the items loaded
697 $this->data
[$code] = $allData;
698 foreach ( $allData as $key => $item ) {
699 $this->loadedItems
[$code][$key] = true;
702 # Save to the persistent cache
703 $this->store
->startWrite( $code );
704 foreach ( $allData as $key => $value ) {
705 if ( in_array( $key, self
::$splitKeys ) ) {
706 foreach ( $value as $subkey => $subvalue ) {
707 $this->store
->set( "$key:$subkey", $subvalue );
710 $this->store
->set( $key, $value );
713 $this->store
->finishWrite();
715 # Clear out the MessageBlobStore
716 # HACK: If using a null (i.e. disabled) storage backend, we
717 # can't write to the MessageBlobStore either
718 if ( !$this->store
instanceof LCStore_Null
) {
719 MessageBlobStore
::clear();
722 wfProfileOut( __METHOD__
);
726 * Build the preload item from the given pre-cache data.
728 * The preload item will be loaded automatically, improving performance
729 * for the commonly-requested items it contains.
733 protected function buildPreload( $data ) {
734 $preload = array( 'messages' => array() );
735 foreach ( self
::$preloadedKeys as $key ) {
736 $preload[$key] = $data[$key];
739 foreach ( $data['preloadedMessages'] as $subkey ) {
740 if ( isset( $data['messages'][$subkey] ) ) {
741 $subitem = $data['messages'][$subkey];
745 $preload['messages'][$subkey] = $subitem;
752 * Unload the data for a given language from the object cache.
753 * Reduces memory usage.
756 public function unload( $code ) {
757 unset( $this->data
[$code] );
758 unset( $this->loadedItems
[$code] );
759 unset( $this->loadedSubitems
[$code] );
760 unset( $this->initialisedLangs
[$code] );
762 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
763 if ( $fbCode === $code ) {
764 $this->unload( $shallowCode );
772 public function unloadAll() {
773 foreach ( $this->initialisedLangs
as $lang => $unused ) {
774 $this->unload( $lang );
779 * Disable the storage backend
781 public function disableBackend() {
782 $this->store
= new LCStore_Null
;
783 $this->manualRecache
= false;
788 * Interface for the persistence layer of LocalisationCache.
790 * The persistence layer is two-level hierarchical cache. The first level
791 * is the language, the second level is the item or subitem.
793 * Since the data for a whole language is rebuilt in one operation, it needs
794 * to have a fast and atomic method for deleting or replacing all of the
795 * current data for a given language. The interface reflects this bulk update
796 * operation. Callers writing to the cache must first call startWrite(), then
797 * will call set() a couple of thousand times, then will call finishWrite()
798 * to commit the operation. When finishWrite() is called, the cache is
799 * expected to delete all data previously stored for that language.
801 * The values stored are PHP variables suitable for serialize(). Implementations
802 * of LCStore are responsible for serializing and unserializing.
807 * @param $code Language code
808 * @param $key Cache key
810 function get( $code, $key );
813 * Start a write transaction.
814 * @param $code Language code
816 function startWrite( $code );
819 * Finish a write transaction.
821 function finishWrite();
824 * Set a key to a given value. startWrite() must be called before this
825 * is called, and finishWrite() must be called afterwards.
829 function set( $key, $value );
833 * LCStore implementation which uses the standard DB functions to store data.
834 * This will work on any MediaWiki installation.
836 class LCStore_DB
implements LCStore
{
838 var $writesDone = false;
845 var $readOnly = false;
847 public function get( $code, $key ) {
848 if ( $this->writesDone
) {
849 $db = wfGetDB( DB_MASTER
);
851 $db = wfGetDB( DB_SLAVE
);
853 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
854 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
856 return unserialize( $row->lc_value
);
862 public function startWrite( $code ) {
863 if ( $this->readOnly
) {
868 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
871 $this->dbw
= wfGetDB( DB_MASTER
);
874 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
875 } catch ( DBQueryError
$e ) {
876 if ( $this->dbw
->wasReadOnlyError() ) {
877 $this->readOnly
= true;
878 $this->dbw
->rollback();
879 $this->dbw
->ignoreErrors( false );
886 $this->currentLang
= $code;
887 $this->batch
= array();
890 public function finishWrite() {
891 if ( $this->readOnly
) {
895 if ( $this->batch
) {
896 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
899 $this->dbw
->commit();
900 $this->currentLang
= null;
902 $this->batch
= array();
903 $this->writesDone
= true;
906 public function set( $key, $value ) {
907 if ( $this->readOnly
) {
911 if ( is_null( $this->currentLang
) ) {
912 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
915 $this->batch
[] = array(
916 'lc_lang' => $this->currentLang
,
918 'lc_value' => serialize( $value ) );
920 if ( count( $this->batch
) >= 100 ) {
921 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
922 $this->batch
= array();
928 * LCStore implementation which stores data as a collection of CDB files in the
929 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
930 * will throw an exception.
932 * Profiling indicates that on Linux, this implementation outperforms MySQL if
933 * the directory is on a local filesystem and there is ample kernel cache
934 * space. The performance advantage is greater when the DBA extension is
935 * available than it is with the PHP port.
937 * See Cdb.php and http://cr.yp.to/cdb.html
939 class LCStore_CDB
implements LCStore
{
940 var $readers, $writer, $currentLang, $directory;
942 function __construct( $conf = array() ) {
943 global $wgCacheDirectory;
945 if ( isset( $conf['directory'] ) ) {
946 $this->directory
= $conf['directory'];
948 $this->directory
= $wgCacheDirectory;
952 public function get( $code, $key ) {
953 if ( !isset( $this->readers
[$code] ) ) {
954 $fileName = $this->getFileName( $code );
956 if ( !file_exists( $fileName ) ) {
957 $this->readers
[$code] = false;
959 $this->readers
[$code] = CdbReader
::open( $fileName );
963 if ( !$this->readers
[$code] ) {
966 $value = $this->readers
[$code]->get( $key );
968 if ( $value === false ) {
971 return unserialize( $value );
975 public function startWrite( $code ) {
976 if ( !file_exists( $this->directory
) ) {
977 if ( !wfMkdirParents( $this->directory
, null, __METHOD__
) ) {
978 throw new MWException( "Unable to create the localisation store " .
979 "directory \"{$this->directory}\"" );
983 // Close reader to stop permission errors on write
984 if( !empty($this->readers
[$code]) ) {
985 $this->readers
[$code]->close();
988 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
989 $this->currentLang
= $code;
992 public function finishWrite() {
994 $this->writer
->close();
995 $this->writer
= null;
996 unset( $this->readers
[$this->currentLang
] );
997 $this->currentLang
= null;
1000 public function set( $key, $value ) {
1001 if ( is_null( $this->writer
) ) {
1002 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
1004 $this->writer
->set( $key, serialize( $value ) );
1007 protected function getFileName( $code ) {
1008 if ( !$code ||
strpos( $code, '/' ) !== false ) {
1009 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
1011 return "{$this->directory}/l10n_cache-$code.cdb";
1016 * Null store backend, used to avoid DB errors during install
1018 class LCStore_Null
implements LCStore
{
1019 public function get( $code, $key ) {
1023 public function startWrite( $code ) {}
1024 public function finishWrite() {}
1025 public function set( $key, $value ) {}
1029 * A localisation cache optimised for loading large amounts of data for many
1030 * languages. Used by rebuildLocalisationCache.php.
1032 class LocalisationCache_BulkLoad
extends LocalisationCache
{
1034 * A cache of the contents of data files.
1035 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1037 var $fileCache = array();
1040 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1041 * to keep the most recently used language codes at the end of the array, and
1042 * the language codes that are ready to be deleted at the beginning.
1044 var $mruLangs = array();
1047 * Maximum number of languages that may be loaded into $this->data
1049 var $maxLoadedLangs = 10;
1054 * @return array|mixed
1056 protected function readPHPFile( $fileName, $fileType ) {
1057 $serialize = $fileType === 'core';
1058 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
1059 $data = parent
::readPHPFile( $fileName, $fileType );
1062 $encData = serialize( $data );
1067 $this->fileCache
[$fileName][$fileType] = $encData;
1070 } elseif ( $serialize ) {
1071 return unserialize( $this->fileCache
[$fileName][$fileType] );
1073 return $this->fileCache
[$fileName][$fileType];
1082 public function getItem( $code, $key ) {
1083 unset( $this->mruLangs
[$code] );
1084 $this->mruLangs
[$code] = true;
1085 return parent
::getItem( $code, $key );
1094 public function getSubitem( $code, $key, $subkey ) {
1095 unset( $this->mruLangs
[$code] );
1096 $this->mruLangs
[$code] = true;
1097 return parent
::getSubitem( $code, $key, $subkey );
1103 public function recache( $code ) {
1104 parent
::recache( $code );
1105 unset( $this->mruLangs
[$code] );
1106 $this->mruLangs
[$code] = true;
1113 public function unload( $code ) {
1114 unset( $this->mruLangs
[$code] );
1115 parent
::unload( $code );
1119 * Unload cached languages until there are less than $this->maxLoadedLangs
1121 protected function trimCache() {
1122 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1123 reset( $this->mruLangs
);
1124 $code = key( $this->mruLangs
);
1125 wfDebug( __METHOD__
.": unloading $code\n" );
1126 $this->unload( $code );