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 = 'LCStore_Accel';
167 $c = wfGetCache( CACHE_ACCEL
);
168 $storeClass = 'LCStore_Accel';
169 } catch( Exception
$c ) {
170 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
174 throw new MWException(
175 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
179 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
180 if ( !empty( $conf['storeDirectory'] ) ) {
181 $storeConf['directory'] = $conf['storeDirectory'];
184 $this->store
= new $storeClass( $storeConf );
185 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
186 if ( isset( $conf[$var] ) ) {
187 $this->$var = $conf[$var];
193 * Returns true if the given key is mergeable, that is, if it is an associative
194 * array which can be merged through a fallback sequence.
198 public function isMergeableKey( $key ) {
199 if ( !isset( $this->mergeableKeys
) ) {
200 $this->mergeableKeys
= array_flip( array_merge(
201 self
::$mergeableMapKeys,
202 self
::$mergeableListKeys,
203 self
::$mergeableAliasListKeys,
204 self
::$optionalMergeKeys,
208 return isset( $this->mergeableKeys
[$key] );
214 * Warning: this may be slow for split items (messages), since it will
215 * need to fetch all of the subitems from the cache individually.
220 public function getItem( $code, $key ) {
221 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
222 wfProfileIn( __METHOD__
.'-load' );
223 $this->loadItem( $code, $key );
224 wfProfileOut( __METHOD__
.'-load' );
227 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
228 return $this->shallowFallbacks
[$code];
231 return $this->data
[$code][$key];
235 * Get a subitem, for instance a single message for a given language.
241 public function getSubitem( $code, $key, $subkey ) {
242 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
243 !isset( $this->loadedItems
[$code][$key] ) ) {
244 wfProfileIn( __METHOD__
.'-load' );
245 $this->loadSubitem( $code, $key, $subkey );
246 wfProfileOut( __METHOD__
.'-load' );
249 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
250 return $this->data
[$code][$key][$subkey];
257 * Get the list of subitem keys for a given item.
259 * This is faster than array_keys($lc->getItem(...)) for the items listed in
262 * Will return null if the item is not found, or false if the item is not an
266 * @return bool|null|string
268 public function getSubitemList( $code, $key ) {
269 if ( in_array( $key, self
::$splitKeys ) ) {
270 return $this->getSubitem( $code, 'list', $key );
272 $item = $this->getItem( $code, $key );
273 if ( is_array( $item ) ) {
274 return array_keys( $item );
282 * Load an item into the cache.
286 protected function loadItem( $code, $key ) {
287 if ( !isset( $this->initialisedLangs
[$code] ) ) {
288 $this->initLanguage( $code );
291 // Check to see if initLanguage() loaded it for us
292 if ( isset( $this->loadedItems
[$code][$key] ) ) {
296 if ( isset( $this->shallowFallbacks
[$code] ) ) {
297 $this->loadItem( $this->shallowFallbacks
[$code], $key );
301 if ( in_array( $key, self
::$splitKeys ) ) {
302 $subkeyList = $this->getSubitem( $code, 'list', $key );
303 foreach ( $subkeyList as $subkey ) {
304 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
307 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
310 $this->data
[$code][$key] = $this->store
->get( $code, $key );
313 $this->loadedItems
[$code][$key] = true;
317 * Load a subitem into the cache
323 protected function loadSubitem( $code, $key, $subkey ) {
324 if ( !in_array( $key, self
::$splitKeys ) ) {
325 $this->loadItem( $code, $key );
329 if ( !isset( $this->initialisedLangs
[$code] ) ) {
330 $this->initLanguage( $code );
333 // Check to see if initLanguage() loaded it for us
334 if ( isset( $this->loadedItems
[$code][$key] ) ||
335 isset( $this->loadedSubitems
[$code][$key][$subkey] ) ) {
339 if ( isset( $this->shallowFallbacks
[$code] ) ) {
340 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
344 $value = $this->store
->get( $code, "$key:$subkey" );
345 $this->data
[$code][$key][$subkey] = $value;
346 $this->loadedSubitems
[$code][$key][$subkey] = true;
350 * Returns true if the cache identified by $code is missing or expired.
352 public function isExpired( $code ) {
353 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
354 wfDebug( __METHOD__
."($code): forced reload\n" );
358 $deps = $this->store
->get( $code, 'deps' );
359 $keys = $this->store
->get( $code, 'list', 'messages' );
360 // 'list:messages' sometimes expires separately of 'deps' in LCStore_Accel
361 if ( $deps === null ||
$keys === null ) {
362 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
366 foreach ( $deps as $dep ) {
367 // Because we're unserializing stuff from cache, we
368 // could receive objects of classes that don't exist
369 // anymore (e.g. uninstalled extensions)
370 // When this happens, always expire the cache
371 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
372 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
373 get_class( $dep ) . "\n" );
382 * Initialise a language in this object. Rebuild the cache if necessary.
385 protected function initLanguage( $code ) {
386 if ( isset( $this->initialisedLangs
[$code] ) ) {
390 $this->initialisedLangs
[$code] = true;
392 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
393 if ( !Language
::isValidBuiltInCode( $code ) ) {
394 $this->initShallowFallback( $code, 'en' );
398 # Recache the data if necessary
399 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
400 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
401 $this->recache( $code );
402 } elseif ( $code === 'en' ) {
403 throw new MWException( 'MessagesEn.php is missing.' );
405 $this->initShallowFallback( $code, 'en' );
411 $preload = $this->getItem( $code, 'preload' );
412 if ( $preload === null ) {
413 if ( $this->manualRecache
) {
414 // No Messages*.php file. Do shallow fallback to en.
415 if ( $code === 'en' ) {
416 throw new MWException( 'No localisation cache found for English. ' .
417 'Please run maintenance/rebuildLocalisationCache.php.' );
419 $this->initShallowFallback( $code, 'en' );
422 throw new MWException( 'Invalid or missing localisation cache.' );
425 $this->data
[$code] = $preload;
426 foreach ( $preload as $key => $item ) {
427 if ( in_array( $key, self
::$splitKeys ) ) {
428 foreach ( $item as $subkey => $subitem ) {
429 $this->loadedSubitems
[$code][$key][$subkey] = true;
432 $this->loadedItems
[$code][$key] = true;
438 * Create a fallback from one language to another, without creating a
439 * complete persistent cache.
440 * @param $primaryCode
441 * @param $fallbackCode
443 public function initShallowFallback( $primaryCode, $fallbackCode ) {
444 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
445 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
446 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
447 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
451 * Read a PHP file containing localisation data.
456 protected function readPHPFile( $_fileName, $_fileType ) {
457 // Disable APC caching
458 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
459 include( $_fileName );
460 ini_set( 'apc.cache_by_default', $_apcEnabled );
462 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
463 $data = compact( self
::$allKeys );
464 } elseif ( $_fileType == 'aliases' ) {
465 $data = compact( 'aliases' );
467 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
474 * Merge two localisation values, a primary and a fallback, overwriting the
475 * primary value in place.
478 * @param $fallbackValue
480 protected function mergeItem( $key, &$value, $fallbackValue ) {
481 if ( !is_null( $value ) ) {
482 if ( !is_null( $fallbackValue ) ) {
483 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
484 $value = $value +
$fallbackValue;
485 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
486 $value = array_unique( array_merge( $fallbackValue, $value ) );
487 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
488 $value = array_merge_recursive( $value, $fallbackValue );
489 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
490 if ( !empty( $value['inherit'] ) ) {
491 $value = array_merge( $fallbackValue, $value );
494 if ( isset( $value['inherit'] ) ) {
495 unset( $value['inherit'] );
497 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
498 $this->mergeMagicWords( $value, $fallbackValue );
502 $value = $fallbackValue;
508 * @param $fallbackValue
510 protected function mergeMagicWords( &$value, $fallbackValue ) {
511 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
512 if ( !isset( $value[$magicName] ) ) {
513 $value[$magicName] = $fallbackInfo;
515 $oldSynonyms = array_slice( $fallbackInfo, 1 );
516 $newSynonyms = array_slice( $value[$magicName], 1 );
517 $synonyms = array_values( array_unique( array_merge(
518 $newSynonyms, $oldSynonyms ) ) );
519 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
525 * Given an array mapping language code to localisation value, such as is
526 * found in extension *.i18n.php files, iterate through a fallback sequence
527 * to merge the given data with an existing primary value.
529 * Returns true if any data from the extension array was used, false
531 * @param $codeSequence
534 * @param $fallbackValue
537 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
539 foreach ( $codeSequence as $code ) {
540 if ( isset( $fallbackValue[$code] ) ) {
541 $this->mergeItem( $key, $value, $fallbackValue[$code] );
550 * Load localisation data for a given language for both core and extensions
551 * and save it to the persistent cache store and the process cache
554 public function recache( $code ) {
555 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
556 wfProfileIn( __METHOD__
);
559 throw new MWException( "Invalid language code requested" );
561 $this->recachedLangs
[$code] = true;
564 $initialData = array_combine(
566 array_fill( 0, count( self
::$allKeys ), null ) );
567 $coreData = $initialData;
570 # Load the primary localisation from the source file
571 $fileName = Language
::getMessagesFileName( $code );
572 if ( !file_exists( $fileName ) ) {
573 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
574 $coreData['fallback'] = 'en';
576 $deps[] = new FileDependency( $fileName );
577 $data = $this->readPHPFile( $fileName, 'core' );
578 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
580 # Merge primary localisation
581 foreach ( $data as $key => $value ) {
582 $this->mergeItem( $key, $coreData[$key], $value );
587 # Fill in the fallback if it's not there already
588 if ( is_null( $coreData['fallback'] ) ) {
589 $coreData['fallback'] = $code === 'en' ?
false : 'en';
592 if ( $coreData['fallback'] === false ) {
593 $coreData['fallbackSequence'] = array();
595 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
596 $len = count( $coreData['fallbackSequence'] );
598 # Ensure that the sequence ends at en
599 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
600 $coreData['fallbackSequence'][] = 'en';
603 # Load the fallback localisation item by item and merge it
604 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
605 # Load the secondary localisation from the source file to
606 # avoid infinite cycles on cyclic fallbacks
607 $fbFilename = Language
::getMessagesFileName( $fbCode );
609 if ( !file_exists( $fbFilename ) ) {
613 $deps[] = new FileDependency( $fbFilename );
614 $fbData = $this->readPHPFile( $fbFilename, 'core' );
616 foreach ( self
::$allKeys as $key ) {
617 if ( !isset( $fbData[$key] ) ) {
621 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
622 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
628 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
630 # Load the extension localisations
631 # This is done after the core because we know the fallback sequence now.
632 # But it has a higher precedence for merging so that we can support things
633 # like site-specific message overrides.
634 $allData = $initialData;
635 foreach ( $wgExtensionMessagesFiles as $fileName ) {
636 $data = $this->readPHPFile( $fileName, 'extension' );
639 foreach ( $data as $key => $item ) {
640 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
646 $deps[] = new FileDependency( $fileName );
650 # Load deprecated $wgExtensionAliasesFiles
651 foreach ( $wgExtensionAliasesFiles as $fileName ) {
652 $data = $this->readPHPFile( $fileName, 'aliases' );
654 if ( !isset( $data['aliases'] ) ) {
658 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
659 $allData['specialPageAliases'], $data['aliases'] );
662 $deps[] = new FileDependency( $fileName );
666 # Merge core data into extension data
667 foreach ( $coreData as $key => $item ) {
668 $this->mergeItem( $key, $allData[$key], $item );
671 # Add cache dependencies for any referenced globals
672 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
673 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
674 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
676 # Add dependencies to the cache entry
677 $allData['deps'] = $deps;
679 # Replace spaces with underscores in namespace names
680 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
682 # And do the same for special page aliases. $page is an array.
683 foreach ( $allData['specialPageAliases'] as &$page ) {
684 $page = str_replace( ' ', '_', $page );
686 # Decouple the reference to prevent accidental damage
690 $allData['list'] = array();
691 foreach ( self
::$splitKeys as $key ) {
692 $allData['list'][$key] = array_keys( $allData[$key] );
696 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
698 if ( is_null( $allData['namespaceNames'] ) ) {
699 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
700 'Check that your languages/messages/MessagesEn.php file is intact.' );
703 # Set the preload key
704 $allData['preload'] = $this->buildPreload( $allData );
706 # Save to the process cache and register the items loaded
707 $this->data
[$code] = $allData;
708 foreach ( $allData as $key => $item ) {
709 $this->loadedItems
[$code][$key] = true;
712 # Save to the persistent cache
713 $this->store
->startWrite( $code );
714 foreach ( $allData as $key => $value ) {
715 if ( in_array( $key, self
::$splitKeys ) ) {
716 foreach ( $value as $subkey => $subvalue ) {
717 $this->store
->set( "$key:$subkey", $subvalue );
720 $this->store
->set( $key, $value );
723 $this->store
->finishWrite();
725 # Clear out the MessageBlobStore
726 # HACK: If using a null (i.e. disabled) storage backend, we
727 # can't write to the MessageBlobStore either
728 if ( !$this->store
instanceof LCStore_Null
) {
729 MessageBlobStore
::clear();
732 wfProfileOut( __METHOD__
);
736 * Build the preload item from the given pre-cache data.
738 * The preload item will be loaded automatically, improving performance
739 * for the commonly-requested items it contains.
743 protected function buildPreload( $data ) {
744 $preload = array( 'messages' => array() );
745 foreach ( self
::$preloadedKeys as $key ) {
746 $preload[$key] = $data[$key];
749 foreach ( $data['preloadedMessages'] as $subkey ) {
750 if ( isset( $data['messages'][$subkey] ) ) {
751 $subitem = $data['messages'][$subkey];
755 $preload['messages'][$subkey] = $subitem;
762 * Unload the data for a given language from the object cache.
763 * Reduces memory usage.
766 public function unload( $code ) {
767 unset( $this->data
[$code] );
768 unset( $this->loadedItems
[$code] );
769 unset( $this->loadedSubitems
[$code] );
770 unset( $this->initialisedLangs
[$code] );
772 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
773 if ( $fbCode === $code ) {
774 $this->unload( $shallowCode );
782 public function unloadAll() {
783 foreach ( $this->initialisedLangs
as $lang => $unused ) {
784 $this->unload( $lang );
789 * Disable the storage backend
791 public function disableBackend() {
792 $this->store
= new LCStore_Null
;
793 $this->manualRecache
= false;
798 * Interface for the persistence layer of LocalisationCache.
800 * The persistence layer is two-level hierarchical cache. The first level
801 * is the language, the second level is the item or subitem.
803 * Since the data for a whole language is rebuilt in one operation, it needs
804 * to have a fast and atomic method for deleting or replacing all of the
805 * current data for a given language. The interface reflects this bulk update
806 * operation. Callers writing to the cache must first call startWrite(), then
807 * will call set() a couple of thousand times, then will call finishWrite()
808 * to commit the operation. When finishWrite() is called, the cache is
809 * expected to delete all data previously stored for that language.
811 * The values stored are PHP variables suitable for serialize(). Implementations
812 * of LCStore are responsible for serializing and unserializing.
817 * @param $code Language code
818 * @param $key Cache key
820 function get( $code, $key );
823 * Start a write transaction.
824 * @param $code Language code
826 function startWrite( $code );
829 * Finish a write transaction.
831 function finishWrite();
834 * Set a key to a given value. startWrite() must be called before this
835 * is called, and finishWrite() must be called afterwards.
839 function set( $key, $value );
843 * LCStore implementation which uses PHP accelerator to store data.
844 * This will work if one of XCache, eAccelerator, or APC cacher is configured.
845 * (See ObjectCache.php)
847 class LCStore_Accel
implements LCStore
{
851 public function __construct() {
852 $this->cache
= wfGetCache( CACHE_ACCEL
);
855 public function get( $code, $key ) {
856 $k = wfMemcKey( 'l10n', $code, 'k', $key );
857 $r = $this->cache
->get( $k );
858 if ( $r === false ) return null;
862 public function startWrite( $code ) {
863 $k = wfMemcKey( 'l10n', $code, 'l' );
864 $keys = $this->cache
->get( $k );
866 foreach ( $keys as $k ) {
867 $this->cache
->delete( $k );
870 $this->currentLang
= $code;
871 $this->keys
= array();
874 public function finishWrite() {
875 if ( $this->currentLang
) {
876 $k = wfMemcKey( 'l10n', $this->currentLang
, 'l' );
877 $this->cache
->set( $k, array_keys( $this->keys
) );
879 $this->currentLang
= null;
880 $this->keys
= array();
883 public function set( $key, $value ) {
884 if ( $this->currentLang
) {
885 $k = wfMemcKey( 'l10n', $this->currentLang
, 'k', $key );
886 $this->keys
[$k] = true;
887 $this->cache
->set( $k, $value );
893 * LCStore implementation which uses the standard DB functions to store data.
894 * This will work on any MediaWiki installation.
896 class LCStore_DB
implements LCStore
{
898 var $writesDone = false;
905 var $readOnly = false;
907 public function get( $code, $key ) {
908 if ( $this->writesDone
) {
909 $db = wfGetDB( DB_MASTER
);
911 $db = wfGetDB( DB_SLAVE
);
913 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
914 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
916 return unserialize( $row->lc_value
);
922 public function startWrite( $code ) {
923 if ( $this->readOnly
) {
928 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
931 $this->dbw
= wfGetDB( DB_MASTER
);
934 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
935 } catch ( DBQueryError
$e ) {
936 if ( $this->dbw
->wasReadOnlyError() ) {
937 $this->readOnly
= true;
938 $this->dbw
->rollback();
939 $this->dbw
->ignoreErrors( false );
946 $this->currentLang
= $code;
947 $this->batch
= array();
950 public function finishWrite() {
951 if ( $this->readOnly
) {
955 if ( $this->batch
) {
956 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
959 $this->dbw
->commit();
960 $this->currentLang
= null;
962 $this->batch
= array();
963 $this->writesDone
= true;
966 public function set( $key, $value ) {
967 if ( $this->readOnly
) {
971 if ( is_null( $this->currentLang
) ) {
972 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
975 $this->batch
[] = array(
976 'lc_lang' => $this->currentLang
,
978 'lc_value' => serialize( $value ) );
980 if ( count( $this->batch
) >= 100 ) {
981 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
982 $this->batch
= array();
988 * LCStore implementation which stores data as a collection of CDB files in the
989 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
990 * will throw an exception.
992 * Profiling indicates that on Linux, this implementation outperforms MySQL if
993 * the directory is on a local filesystem and there is ample kernel cache
994 * space. The performance advantage is greater when the DBA extension is
995 * available than it is with the PHP port.
997 * See Cdb.php and http://cr.yp.to/cdb.html
999 class LCStore_CDB
implements LCStore
{
1000 var $readers, $writer, $currentLang, $directory;
1002 function __construct( $conf = array() ) {
1003 global $wgCacheDirectory;
1005 if ( isset( $conf['directory'] ) ) {
1006 $this->directory
= $conf['directory'];
1008 $this->directory
= $wgCacheDirectory;
1012 public function get( $code, $key ) {
1013 if ( !isset( $this->readers
[$code] ) ) {
1014 $fileName = $this->getFileName( $code );
1016 if ( !file_exists( $fileName ) ) {
1017 $this->readers
[$code] = false;
1019 $this->readers
[$code] = CdbReader
::open( $fileName );
1023 if ( !$this->readers
[$code] ) {
1026 $value = $this->readers
[$code]->get( $key );
1028 if ( $value === false ) {
1031 return unserialize( $value );
1035 public function startWrite( $code ) {
1036 if ( !file_exists( $this->directory
) ) {
1037 if ( !wfMkdirParents( $this->directory
, null, __METHOD__
) ) {
1038 throw new MWException( "Unable to create the localisation store " .
1039 "directory \"{$this->directory}\"" );
1043 // Close reader to stop permission errors on write
1044 if( !empty($this->readers
[$code]) ) {
1045 $this->readers
[$code]->close();
1048 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
1049 $this->currentLang
= $code;
1052 public function finishWrite() {
1054 $this->writer
->close();
1055 $this->writer
= null;
1056 unset( $this->readers
[$this->currentLang
] );
1057 $this->currentLang
= null;
1060 public function set( $key, $value ) {
1061 if ( is_null( $this->writer
) ) {
1062 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
1064 $this->writer
->set( $key, serialize( $value ) );
1067 protected function getFileName( $code ) {
1068 if ( !$code ||
strpos( $code, '/' ) !== false ) {
1069 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
1071 return "{$this->directory}/l10n_cache-$code.cdb";
1076 * Null store backend, used to avoid DB errors during install
1078 class LCStore_Null
implements LCStore
{
1079 public function get( $code, $key ) {
1083 public function startWrite( $code ) {}
1084 public function finishWrite() {}
1085 public function set( $key, $value ) {}
1089 * A localisation cache optimised for loading large amounts of data for many
1090 * languages. Used by rebuildLocalisationCache.php.
1092 class LocalisationCache_BulkLoad
extends LocalisationCache
{
1094 * A cache of the contents of data files.
1095 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1097 var $fileCache = array();
1100 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1101 * to keep the most recently used language codes at the end of the array, and
1102 * the language codes that are ready to be deleted at the beginning.
1104 var $mruLangs = array();
1107 * Maximum number of languages that may be loaded into $this->data
1109 var $maxLoadedLangs = 10;
1114 * @return array|mixed
1116 protected function readPHPFile( $fileName, $fileType ) {
1117 $serialize = $fileType === 'core';
1118 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
1119 $data = parent
::readPHPFile( $fileName, $fileType );
1122 $encData = serialize( $data );
1127 $this->fileCache
[$fileName][$fileType] = $encData;
1130 } elseif ( $serialize ) {
1131 return unserialize( $this->fileCache
[$fileName][$fileType] );
1133 return $this->fileCache
[$fileName][$fileType];
1142 public function getItem( $code, $key ) {
1143 unset( $this->mruLangs
[$code] );
1144 $this->mruLangs
[$code] = true;
1145 return parent
::getItem( $code, $key );
1154 public function getSubitem( $code, $key, $subkey ) {
1155 unset( $this->mruLangs
[$code] );
1156 $this->mruLangs
[$code] = true;
1157 return parent
::getSubitem( $code, $key, $subkey );
1163 public function recache( $code ) {
1164 parent
::recache( $code );
1165 unset( $this->mruLangs
[$code] );
1166 $this->mruLangs
[$code] = true;
1173 public function unload( $code ) {
1174 unset( $this->mruLangs
[$code] );
1175 parent
::unload( $code );
1179 * Unload cached languages until there are less than $this->maxLoadedLangs
1181 protected function trimCache() {
1182 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1183 reset( $this->mruLangs
);
1184 $code = key( $this->mruLangs
);
1185 wfDebug( __METHOD__
.": unloading $code\n" );
1186 $this->unload( $code );