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';
166 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
169 throw new MWException(
170 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
174 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
175 if ( !empty( $conf['storeDirectory'] ) ) {
176 $storeConf['directory'] = $conf['storeDirectory'];
179 $this->store
= new $storeClass( $storeConf );
180 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
181 if ( isset( $conf[$var] ) ) {
182 $this->$var = $conf[$var];
188 * Returns true if the given key is mergeable, that is, if it is an associative
189 * array which can be merged through a fallback sequence.
193 public function isMergeableKey( $key ) {
194 if ( $this->mergeableKeys
=== null ) {
195 $this->mergeableKeys
= array_flip( array_merge(
196 self
::$mergeableMapKeys,
197 self
::$mergeableListKeys,
198 self
::$mergeableAliasListKeys,
199 self
::$optionalMergeKeys,
203 return isset( $this->mergeableKeys
[$key] );
209 * Warning: this may be slow for split items (messages), since it will
210 * need to fetch all of the subitems from the cache individually.
215 public function getItem( $code, $key ) {
216 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
217 wfProfileIn( __METHOD__
.'-load' );
218 $this->loadItem( $code, $key );
219 wfProfileOut( __METHOD__
.'-load' );
222 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
223 return $this->shallowFallbacks
[$code];
226 return $this->data
[$code][$key];
230 * Get a subitem, for instance a single message for a given language.
236 public function getSubitem( $code, $key, $subkey ) {
237 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
238 !isset( $this->loadedItems
[$code][$key] ) ) {
239 wfProfileIn( __METHOD__
.'-load' );
240 $this->loadSubitem( $code, $key, $subkey );
241 wfProfileOut( __METHOD__
.'-load' );
244 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
245 return $this->data
[$code][$key][$subkey];
252 * Get the list of subitem keys for a given item.
254 * This is faster than array_keys($lc->getItem(...)) for the items listed in
257 * Will return null if the item is not found, or false if the item is not an
261 * @return bool|null|string
263 public function getSubitemList( $code, $key ) {
264 if ( in_array( $key, self
::$splitKeys ) ) {
265 return $this->getSubitem( $code, 'list', $key );
267 $item = $this->getItem( $code, $key );
268 if ( is_array( $item ) ) {
269 return array_keys( $item );
277 * Load an item into the cache.
281 protected function loadItem( $code, $key ) {
282 if ( !isset( $this->initialisedLangs
[$code] ) ) {
283 $this->initLanguage( $code );
286 // Check to see if initLanguage() loaded it for us
287 if ( isset( $this->loadedItems
[$code][$key] ) ) {
291 if ( isset( $this->shallowFallbacks
[$code] ) ) {
292 $this->loadItem( $this->shallowFallbacks
[$code], $key );
296 if ( in_array( $key, self
::$splitKeys ) ) {
297 $subkeyList = $this->getSubitem( $code, 'list', $key );
298 foreach ( $subkeyList as $subkey ) {
299 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
302 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
305 $this->data
[$code][$key] = $this->store
->get( $code, $key );
308 $this->loadedItems
[$code][$key] = true;
312 * Load a subitem into the cache
318 protected function loadSubitem( $code, $key, $subkey ) {
319 if ( !in_array( $key, self
::$splitKeys ) ) {
320 $this->loadItem( $code, $key );
324 if ( !isset( $this->initialisedLangs
[$code] ) ) {
325 $this->initLanguage( $code );
328 // Check to see if initLanguage() loaded it for us
329 if ( isset( $this->loadedItems
[$code][$key] ) ||
330 isset( $this->loadedSubitems
[$code][$key][$subkey] ) ) {
334 if ( isset( $this->shallowFallbacks
[$code] ) ) {
335 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
339 $value = $this->store
->get( $code, "$key:$subkey" );
340 $this->data
[$code][$key][$subkey] = $value;
341 $this->loadedSubitems
[$code][$key][$subkey] = true;
345 * Returns true if the cache identified by $code is missing or expired.
347 public function isExpired( $code ) {
348 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
349 wfDebug( __METHOD__
."($code): forced reload\n" );
353 $deps = $this->store
->get( $code, 'deps' );
354 $keys = $this->store
->get( $code, 'list', 'messages' );
355 $preload = $this->store
->get( $code, 'preload' );
356 // Different keys may expire separately, at least in LCStore_Accel
357 if ( $deps === null ||
$keys === null ||
$preload === null ) {
358 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
362 foreach ( $deps as $dep ) {
363 // Because we're unserializing stuff from cache, we
364 // could receive objects of classes that don't exist
365 // anymore (e.g. uninstalled extensions)
366 // When this happens, always expire the cache
367 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
368 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
369 get_class( $dep ) . "\n" );
378 * Initialise a language in this object. Rebuild the cache if necessary.
381 protected function initLanguage( $code ) {
382 if ( isset( $this->initialisedLangs
[$code] ) ) {
386 $this->initialisedLangs
[$code] = true;
388 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
389 if ( !Language
::isValidBuiltInCode( $code ) ) {
390 $this->initShallowFallback( $code, 'en' );
394 # Recache the data if necessary
395 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
396 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
397 $this->recache( $code );
398 } elseif ( $code === 'en' ) {
399 throw new MWException( 'MessagesEn.php is missing.' );
401 $this->initShallowFallback( $code, 'en' );
407 $preload = $this->getItem( $code, 'preload' );
408 if ( $preload === null ) {
409 if ( $this->manualRecache
) {
410 // No Messages*.php file. Do shallow fallback to en.
411 if ( $code === 'en' ) {
412 throw new MWException( 'No localisation cache found for English. ' .
413 'Please run maintenance/rebuildLocalisationCache.php.' );
415 $this->initShallowFallback( $code, 'en' );
418 throw new MWException( 'Invalid or missing localisation cache.' );
421 $this->data
[$code] = $preload;
422 foreach ( $preload as $key => $item ) {
423 if ( in_array( $key, self
::$splitKeys ) ) {
424 foreach ( $item as $subkey => $subitem ) {
425 $this->loadedSubitems
[$code][$key][$subkey] = true;
428 $this->loadedItems
[$code][$key] = true;
434 * Create a fallback from one language to another, without creating a
435 * complete persistent cache.
436 * @param $primaryCode
437 * @param $fallbackCode
439 public function initShallowFallback( $primaryCode, $fallbackCode ) {
440 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
441 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
442 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
443 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
447 * Read a PHP file containing localisation data.
452 protected function readPHPFile( $_fileName, $_fileType ) {
453 // Disable APC caching
454 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
455 include( $_fileName );
456 ini_set( 'apc.cache_by_default', $_apcEnabled );
458 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
459 $data = compact( self
::$allKeys );
460 } elseif ( $_fileType == 'aliases' ) {
461 $data = compact( 'aliases' );
463 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
470 * Merge two localisation values, a primary and a fallback, overwriting the
471 * primary value in place.
474 * @param $fallbackValue
476 protected function mergeItem( $key, &$value, $fallbackValue ) {
477 if ( !is_null( $value ) ) {
478 if ( !is_null( $fallbackValue ) ) {
479 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
480 $value = $value +
$fallbackValue;
481 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
482 $value = array_unique( array_merge( $fallbackValue, $value ) );
483 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
484 $value = array_merge_recursive( $value, $fallbackValue );
485 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
486 if ( !empty( $value['inherit'] ) ) {
487 $value = array_merge( $fallbackValue, $value );
490 if ( isset( $value['inherit'] ) ) {
491 unset( $value['inherit'] );
493 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
494 $this->mergeMagicWords( $value, $fallbackValue );
498 $value = $fallbackValue;
504 * @param $fallbackValue
506 protected function mergeMagicWords( &$value, $fallbackValue ) {
507 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
508 if ( !isset( $value[$magicName] ) ) {
509 $value[$magicName] = $fallbackInfo;
511 $oldSynonyms = array_slice( $fallbackInfo, 1 );
512 $newSynonyms = array_slice( $value[$magicName], 1 );
513 $synonyms = array_values( array_unique( array_merge(
514 $newSynonyms, $oldSynonyms ) ) );
515 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
521 * Given an array mapping language code to localisation value, such as is
522 * found in extension *.i18n.php files, iterate through a fallback sequence
523 * to merge the given data with an existing primary value.
525 * Returns true if any data from the extension array was used, false
527 * @param $codeSequence
530 * @param $fallbackValue
533 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
535 foreach ( $codeSequence as $code ) {
536 if ( isset( $fallbackValue[$code] ) ) {
537 $this->mergeItem( $key, $value, $fallbackValue[$code] );
546 * Load localisation data for a given language for both core and extensions
547 * and save it to the persistent cache store and the process cache
550 public function recache( $code ) {
551 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
552 wfProfileIn( __METHOD__
);
555 throw new MWException( "Invalid language code requested" );
557 $this->recachedLangs
[$code] = true;
560 $initialData = array_combine(
562 array_fill( 0, count( self
::$allKeys ), null ) );
563 $coreData = $initialData;
566 # Load the primary localisation from the source file
567 $fileName = Language
::getMessagesFileName( $code );
568 if ( !file_exists( $fileName ) ) {
569 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
570 $coreData['fallback'] = 'en';
572 $deps[] = new FileDependency( $fileName );
573 $data = $this->readPHPFile( $fileName, 'core' );
574 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
576 # Merge primary localisation
577 foreach ( $data as $key => $value ) {
578 $this->mergeItem( $key, $coreData[$key], $value );
583 # Fill in the fallback if it's not there already
584 if ( is_null( $coreData['fallback'] ) ) {
585 $coreData['fallback'] = $code === 'en' ?
false : 'en';
588 if ( $coreData['fallback'] === false ) {
589 $coreData['fallbackSequence'] = array();
591 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
592 $len = count( $coreData['fallbackSequence'] );
594 # Ensure that the sequence ends at en
595 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
596 $coreData['fallbackSequence'][] = 'en';
599 # Load the fallback localisation item by item and merge it
600 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
601 # Load the secondary localisation from the source file to
602 # avoid infinite cycles on cyclic fallbacks
603 $fbFilename = Language
::getMessagesFileName( $fbCode );
605 if ( !file_exists( $fbFilename ) ) {
609 $deps[] = new FileDependency( $fbFilename );
610 $fbData = $this->readPHPFile( $fbFilename, 'core' );
612 foreach ( self
::$allKeys as $key ) {
613 if ( !isset( $fbData[$key] ) ) {
617 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
618 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
624 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
626 # Load the extension localisations
627 # This is done after the core because we know the fallback sequence now.
628 # But it has a higher precedence for merging so that we can support things
629 # like site-specific message overrides.
630 $allData = $initialData;
631 foreach ( $wgExtensionMessagesFiles as $fileName ) {
632 $data = $this->readPHPFile( $fileName, 'extension' );
635 foreach ( $data as $key => $item ) {
636 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
642 $deps[] = new FileDependency( $fileName );
646 # Load deprecated $wgExtensionAliasesFiles
647 foreach ( $wgExtensionAliasesFiles as $fileName ) {
648 $data = $this->readPHPFile( $fileName, 'aliases' );
650 if ( !isset( $data['aliases'] ) ) {
654 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
655 $allData['specialPageAliases'], $data['aliases'] );
658 $deps[] = new FileDependency( $fileName );
662 # Merge core data into extension data
663 foreach ( $coreData as $key => $item ) {
664 $this->mergeItem( $key, $allData[$key], $item );
667 # Add cache dependencies for any referenced globals
668 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
669 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
670 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
672 # Add dependencies to the cache entry
673 $allData['deps'] = $deps;
675 # Replace spaces with underscores in namespace names
676 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
678 # And do the same for special page aliases. $page is an array.
679 foreach ( $allData['specialPageAliases'] as &$page ) {
680 $page = str_replace( ' ', '_', $page );
682 # Decouple the reference to prevent accidental damage
686 $allData['list'] = array();
687 foreach ( self
::$splitKeys as $key ) {
688 $allData['list'][$key] = array_keys( $allData[$key] );
692 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
694 if ( is_null( $allData['namespaceNames'] ) ) {
695 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
696 'Check that your languages/messages/MessagesEn.php file is intact.' );
699 # Set the preload key
700 $allData['preload'] = $this->buildPreload( $allData );
702 # Save to the process cache and register the items loaded
703 $this->data
[$code] = $allData;
704 foreach ( $allData as $key => $item ) {
705 $this->loadedItems
[$code][$key] = true;
708 # Save to the persistent cache
709 $this->store
->startWrite( $code );
710 foreach ( $allData as $key => $value ) {
711 if ( in_array( $key, self
::$splitKeys ) ) {
712 foreach ( $value as $subkey => $subvalue ) {
713 $this->store
->set( "$key:$subkey", $subvalue );
716 $this->store
->set( $key, $value );
719 $this->store
->finishWrite();
721 # Clear out the MessageBlobStore
722 # HACK: If using a null (i.e. disabled) storage backend, we
723 # can't write to the MessageBlobStore either
724 if ( !$this->store
instanceof LCStore_Null
) {
725 MessageBlobStore
::clear();
728 wfProfileOut( __METHOD__
);
732 * Build the preload item from the given pre-cache data.
734 * The preload item will be loaded automatically, improving performance
735 * for the commonly-requested items it contains.
739 protected function buildPreload( $data ) {
740 $preload = array( 'messages' => array() );
741 foreach ( self
::$preloadedKeys as $key ) {
742 $preload[$key] = $data[$key];
745 foreach ( $data['preloadedMessages'] as $subkey ) {
746 if ( isset( $data['messages'][$subkey] ) ) {
747 $subitem = $data['messages'][$subkey];
751 $preload['messages'][$subkey] = $subitem;
758 * Unload the data for a given language from the object cache.
759 * Reduces memory usage.
762 public function unload( $code ) {
763 unset( $this->data
[$code] );
764 unset( $this->loadedItems
[$code] );
765 unset( $this->loadedSubitems
[$code] );
766 unset( $this->initialisedLangs
[$code] );
768 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
769 if ( $fbCode === $code ) {
770 $this->unload( $shallowCode );
778 public function unloadAll() {
779 foreach ( $this->initialisedLangs
as $lang => $unused ) {
780 $this->unload( $lang );
785 * Disable the storage backend
787 public function disableBackend() {
788 $this->store
= new LCStore_Null
;
789 $this->manualRecache
= false;
794 * Interface for the persistence layer of LocalisationCache.
796 * The persistence layer is two-level hierarchical cache. The first level
797 * is the language, the second level is the item or subitem.
799 * Since the data for a whole language is rebuilt in one operation, it needs
800 * to have a fast and atomic method for deleting or replacing all of the
801 * current data for a given language. The interface reflects this bulk update
802 * operation. Callers writing to the cache must first call startWrite(), then
803 * will call set() a couple of thousand times, then will call finishWrite()
804 * to commit the operation. When finishWrite() is called, the cache is
805 * expected to delete all data previously stored for that language.
807 * The values stored are PHP variables suitable for serialize(). Implementations
808 * of LCStore are responsible for serializing and unserializing.
813 * @param $code Language code
814 * @param $key Cache key
816 function get( $code, $key );
819 * Start a write transaction.
820 * @param $code Language code
822 function startWrite( $code );
825 * Finish a write transaction.
827 function finishWrite();
830 * Set a key to a given value. startWrite() must be called before this
831 * is called, and finishWrite() must be called afterwards.
835 function set( $key, $value );
839 * LCStore implementation which uses PHP accelerator to store data.
840 * This will work if one of XCache, WinCache or APC cacher is configured.
841 * (See ObjectCache.php)
843 class LCStore_Accel
implements LCStore
{
847 public function __construct() {
848 $this->cache
= wfGetCache( CACHE_ACCEL
);
851 public function get( $code, $key ) {
852 $k = wfMemcKey( 'l10n', $code, 'k', $key );
853 $r = $this->cache
->get( $k );
854 return $r === false ?
null : $r;
857 public function startWrite( $code ) {
858 $k = wfMemcKey( 'l10n', $code, 'l' );
859 $keys = $this->cache
->get( $k );
861 foreach ( $keys as $k ) {
862 $this->cache
->delete( $k );
865 $this->currentLang
= $code;
866 $this->keys
= array();
869 public function finishWrite() {
870 if ( $this->currentLang
) {
871 $k = wfMemcKey( 'l10n', $this->currentLang
, 'l' );
872 $this->cache
->set( $k, array_keys( $this->keys
) );
874 $this->currentLang
= null;
875 $this->keys
= array();
878 public function set( $key, $value ) {
879 if ( $this->currentLang
) {
880 $k = wfMemcKey( 'l10n', $this->currentLang
, 'k', $key );
881 $this->keys
[$k] = true;
882 $this->cache
->set( $k, $value );
888 * LCStore implementation which uses the standard DB functions to store data.
889 * This will work on any MediaWiki installation.
891 class LCStore_DB
implements LCStore
{
893 var $writesDone = false;
900 var $readOnly = false;
902 public function get( $code, $key ) {
903 if ( $this->writesDone
) {
904 $db = wfGetDB( DB_MASTER
);
906 $db = wfGetDB( DB_SLAVE
);
908 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
909 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
911 return unserialize( $row->lc_value
);
917 public function startWrite( $code ) {
918 if ( $this->readOnly
) {
923 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
926 $this->dbw
= wfGetDB( DB_MASTER
);
929 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
930 } catch ( DBQueryError
$e ) {
931 if ( $this->dbw
->wasReadOnlyError() ) {
932 $this->readOnly
= true;
933 $this->dbw
->rollback();
934 $this->dbw
->ignoreErrors( false );
941 $this->currentLang
= $code;
942 $this->batch
= array();
945 public function finishWrite() {
946 if ( $this->readOnly
) {
950 if ( $this->batch
) {
951 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
954 $this->dbw
->commit();
955 $this->currentLang
= null;
957 $this->batch
= array();
958 $this->writesDone
= true;
961 public function set( $key, $value ) {
962 if ( $this->readOnly
) {
966 if ( is_null( $this->currentLang
) ) {
967 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
970 $this->batch
[] = array(
971 'lc_lang' => $this->currentLang
,
973 'lc_value' => serialize( $value ) );
975 if ( count( $this->batch
) >= 100 ) {
976 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
977 $this->batch
= array();
983 * LCStore implementation which stores data as a collection of CDB files in the
984 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
985 * will throw an exception.
987 * Profiling indicates that on Linux, this implementation outperforms MySQL if
988 * the directory is on a local filesystem and there is ample kernel cache
989 * space. The performance advantage is greater when the DBA extension is
990 * available than it is with the PHP port.
992 * See Cdb.php and http://cr.yp.to/cdb.html
994 class LCStore_CDB
implements LCStore
{
995 var $readers, $writer, $currentLang, $directory;
997 function __construct( $conf = array() ) {
998 global $wgCacheDirectory;
1000 if ( isset( $conf['directory'] ) ) {
1001 $this->directory
= $conf['directory'];
1003 $this->directory
= $wgCacheDirectory;
1007 public function get( $code, $key ) {
1008 if ( !isset( $this->readers
[$code] ) ) {
1009 $fileName = $this->getFileName( $code );
1011 if ( !file_exists( $fileName ) ) {
1012 $this->readers
[$code] = false;
1014 $this->readers
[$code] = CdbReader
::open( $fileName );
1018 if ( !$this->readers
[$code] ) {
1021 $value = $this->readers
[$code]->get( $key );
1023 if ( $value === false ) {
1026 return unserialize( $value );
1030 public function startWrite( $code ) {
1031 if ( !file_exists( $this->directory
) ) {
1032 if ( !wfMkdirParents( $this->directory
, null, __METHOD__
) ) {
1033 throw new MWException( "Unable to create the localisation store " .
1034 "directory \"{$this->directory}\"" );
1038 // Close reader to stop permission errors on write
1039 if( !empty($this->readers
[$code]) ) {
1040 $this->readers
[$code]->close();
1043 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
1044 $this->currentLang
= $code;
1047 public function finishWrite() {
1049 $this->writer
->close();
1050 $this->writer
= null;
1051 unset( $this->readers
[$this->currentLang
] );
1052 $this->currentLang
= null;
1055 public function set( $key, $value ) {
1056 if ( is_null( $this->writer
) ) {
1057 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
1059 $this->writer
->set( $key, serialize( $value ) );
1062 protected function getFileName( $code ) {
1063 if ( !$code ||
strpos( $code, '/' ) !== false ) {
1064 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
1066 return "{$this->directory}/l10n_cache-$code.cdb";
1071 * Null store backend, used to avoid DB errors during install
1073 class LCStore_Null
implements LCStore
{
1074 public function get( $code, $key ) {
1078 public function startWrite( $code ) {}
1079 public function finishWrite() {}
1080 public function set( $key, $value ) {}
1084 * A localisation cache optimised for loading large amounts of data for many
1085 * languages. Used by rebuildLocalisationCache.php.
1087 class LocalisationCache_BulkLoad
extends LocalisationCache
{
1089 * A cache of the contents of data files.
1090 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1092 var $fileCache = array();
1095 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1096 * to keep the most recently used language codes at the end of the array, and
1097 * the language codes that are ready to be deleted at the beginning.
1099 var $mruLangs = array();
1102 * Maximum number of languages that may be loaded into $this->data
1104 var $maxLoadedLangs = 10;
1109 * @return array|mixed
1111 protected function readPHPFile( $fileName, $fileType ) {
1112 $serialize = $fileType === 'core';
1113 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
1114 $data = parent
::readPHPFile( $fileName, $fileType );
1117 $encData = serialize( $data );
1122 $this->fileCache
[$fileName][$fileType] = $encData;
1125 } elseif ( $serialize ) {
1126 return unserialize( $this->fileCache
[$fileName][$fileType] );
1128 return $this->fileCache
[$fileName][$fileType];
1137 public function getItem( $code, $key ) {
1138 unset( $this->mruLangs
[$code] );
1139 $this->mruLangs
[$code] = true;
1140 return parent
::getItem( $code, $key );
1149 public function getSubitem( $code, $key, $subkey ) {
1150 unset( $this->mruLangs
[$code] );
1151 $this->mruLangs
[$code] = true;
1152 return parent
::getSubitem( $code, $key, $subkey );
1158 public function recache( $code ) {
1159 parent
::recache( $code );
1160 unset( $this->mruLangs
[$code] );
1161 $this->mruLangs
[$code] = true;
1168 public function unload( $code ) {
1169 unset( $this->mruLangs
[$code] );
1170 parent
::unload( $code );
1174 * Unload cached languages until there are less than $this->maxLoadedLangs
1176 protected function trimCache() {
1177 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1178 reset( $this->mruLangs
);
1179 $code = key( $this->mruLangs
);
1180 wfDebug( __METHOD__
.": unloading $code\n" );
1181 $this->unload( $code );