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.
348 public function isExpired( $code ) {
349 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
350 wfDebug( __METHOD__
."($code): forced reload\n" );
354 $deps = $this->store
->get( $code, 'deps' );
355 $keys = $this->store
->get( $code, 'list', 'messages' );
356 $preload = $this->store
->get( $code, 'preload' );
357 // Different keys may expire separately, at least in LCStore_Accel
358 if ( $deps === null ||
$keys === null ||
$preload === null ) {
359 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
363 foreach ( $deps as $dep ) {
364 // Because we're unserializing stuff from cache, we
365 // could receive objects of classes that don't exist
366 // anymore (e.g. uninstalled extensions)
367 // When this happens, always expire the cache
368 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
369 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
370 get_class( $dep ) . "\n" );
379 * Initialise a language in this object. Rebuild the cache if necessary.
382 protected function initLanguage( $code ) {
383 if ( isset( $this->initialisedLangs
[$code] ) ) {
387 $this->initialisedLangs
[$code] = true;
389 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
390 if ( !Language
::isValidBuiltInCode( $code ) ) {
391 $this->initShallowFallback( $code, 'en' );
395 # Recache the data if necessary
396 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
397 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
398 $this->recache( $code );
399 } elseif ( $code === 'en' ) {
400 throw new MWException( 'MessagesEn.php is missing.' );
402 $this->initShallowFallback( $code, 'en' );
408 $preload = $this->getItem( $code, 'preload' );
409 if ( $preload === null ) {
410 if ( $this->manualRecache
) {
411 // No Messages*.php file. Do shallow fallback to en.
412 if ( $code === 'en' ) {
413 throw new MWException( 'No localisation cache found for English. ' .
414 'Please run maintenance/rebuildLocalisationCache.php.' );
416 $this->initShallowFallback( $code, 'en' );
419 throw new MWException( 'Invalid or missing localisation cache.' );
422 $this->data
[$code] = $preload;
423 foreach ( $preload as $key => $item ) {
424 if ( in_array( $key, self
::$splitKeys ) ) {
425 foreach ( $item as $subkey => $subitem ) {
426 $this->loadedSubitems
[$code][$key][$subkey] = true;
429 $this->loadedItems
[$code][$key] = true;
435 * Create a fallback from one language to another, without creating a
436 * complete persistent cache.
437 * @param $primaryCode
438 * @param $fallbackCode
440 public function initShallowFallback( $primaryCode, $fallbackCode ) {
441 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
442 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
443 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
444 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
448 * Read a PHP file containing localisation data.
453 protected function readPHPFile( $_fileName, $_fileType ) {
454 // Disable APC caching
455 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
456 include( $_fileName );
457 ini_set( 'apc.cache_by_default', $_apcEnabled );
459 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
460 $data = compact( self
::$allKeys );
461 } elseif ( $_fileType == 'aliases' ) {
462 $data = compact( 'aliases' );
464 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
471 * Merge two localisation values, a primary and a fallback, overwriting the
472 * primary value in place.
475 * @param $fallbackValue
477 protected function mergeItem( $key, &$value, $fallbackValue ) {
478 if ( !is_null( $value ) ) {
479 if ( !is_null( $fallbackValue ) ) {
480 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
481 $value = $value +
$fallbackValue;
482 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
483 $value = array_unique( array_merge( $fallbackValue, $value ) );
484 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
485 $value = array_merge_recursive( $value, $fallbackValue );
486 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
487 if ( !empty( $value['inherit'] ) ) {
488 $value = array_merge( $fallbackValue, $value );
491 if ( isset( $value['inherit'] ) ) {
492 unset( $value['inherit'] );
494 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
495 $this->mergeMagicWords( $value, $fallbackValue );
499 $value = $fallbackValue;
505 * @param $fallbackValue
507 protected function mergeMagicWords( &$value, $fallbackValue ) {
508 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
509 if ( !isset( $value[$magicName] ) ) {
510 $value[$magicName] = $fallbackInfo;
512 $oldSynonyms = array_slice( $fallbackInfo, 1 );
513 $newSynonyms = array_slice( $value[$magicName], 1 );
514 $synonyms = array_values( array_unique( array_merge(
515 $newSynonyms, $oldSynonyms ) ) );
516 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
522 * Given an array mapping language code to localisation value, such as is
523 * found in extension *.i18n.php files, iterate through a fallback sequence
524 * to merge the given data with an existing primary value.
526 * Returns true if any data from the extension array was used, false
528 * @param $codeSequence
531 * @param $fallbackValue
534 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
536 foreach ( $codeSequence as $code ) {
537 if ( isset( $fallbackValue[$code] ) ) {
538 $this->mergeItem( $key, $value, $fallbackValue[$code] );
547 * Load localisation data for a given language for both core and extensions
548 * and save it to the persistent cache store and the process cache
551 public function recache( $code ) {
552 global $wgExtensionMessagesFiles;
553 wfProfileIn( __METHOD__
);
556 throw new MWException( "Invalid language code requested" );
558 $this->recachedLangs
[$code] = true;
561 $initialData = array_combine(
563 array_fill( 0, count( self
::$allKeys ), null ) );
564 $coreData = $initialData;
567 # Load the primary localisation from the source file
568 $fileName = Language
::getMessagesFileName( $code );
569 if ( !file_exists( $fileName ) ) {
570 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
571 $coreData['fallback'] = 'en';
573 $deps[] = new FileDependency( $fileName );
574 $data = $this->readPHPFile( $fileName, 'core' );
575 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
577 # Merge primary localisation
578 foreach ( $data as $key => $value ) {
579 $this->mergeItem( $key, $coreData[$key], $value );
584 # Fill in the fallback if it's not there already
585 if ( is_null( $coreData['fallback'] ) ) {
586 $coreData['fallback'] = $code === 'en' ?
false : 'en';
589 if ( $coreData['fallback'] === false ) {
590 $coreData['fallbackSequence'] = array();
592 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
593 $len = count( $coreData['fallbackSequence'] );
595 # Ensure that the sequence ends at en
596 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
597 $coreData['fallbackSequence'][] = 'en';
600 # Load the fallback localisation item by item and merge it
601 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
602 # Load the secondary localisation from the source file to
603 # avoid infinite cycles on cyclic fallbacks
604 $fbFilename = Language
::getMessagesFileName( $fbCode );
606 if ( !file_exists( $fbFilename ) ) {
610 $deps[] = new FileDependency( $fbFilename );
611 $fbData = $this->readPHPFile( $fbFilename, 'core' );
613 foreach ( self
::$allKeys as $key ) {
614 if ( !isset( $fbData[$key] ) ) {
618 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
619 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
625 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
627 # Load the extension localisations
628 # This is done after the core because we know the fallback sequence now.
629 # But it has a higher precedence for merging so that we can support things
630 # like site-specific message overrides.
631 $allData = $initialData;
632 foreach ( $wgExtensionMessagesFiles as $fileName ) {
633 $data = $this->readPHPFile( $fileName, 'extension' );
636 foreach ( $data as $key => $item ) {
637 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
643 $deps[] = new FileDependency( $fileName );
647 # Merge core data into extension data
648 foreach ( $coreData as $key => $item ) {
649 $this->mergeItem( $key, $allData[$key], $item );
652 # Add cache dependencies for any referenced globals
653 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
654 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
656 # Add dependencies to the cache entry
657 $allData['deps'] = $deps;
659 # Replace spaces with underscores in namespace names
660 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
662 # And do the same for special page aliases. $page is an array.
663 foreach ( $allData['specialPageAliases'] as &$page ) {
664 $page = str_replace( ' ', '_', $page );
666 # Decouple the reference to prevent accidental damage
670 $allData['list'] = array();
671 foreach ( self
::$splitKeys as $key ) {
672 $allData['list'][$key] = array_keys( $allData[$key] );
676 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
678 if ( is_null( $allData['namespaceNames'] ) ) {
679 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
680 'Check that your languages/messages/MessagesEn.php file is intact.' );
683 # Set the preload key
684 $allData['preload'] = $this->buildPreload( $allData );
686 # Save to the process cache and register the items loaded
687 $this->data
[$code] = $allData;
688 foreach ( $allData as $key => $item ) {
689 $this->loadedItems
[$code][$key] = true;
692 # Save to the persistent cache
693 $this->store
->startWrite( $code );
694 foreach ( $allData as $key => $value ) {
695 if ( in_array( $key, self
::$splitKeys ) ) {
696 foreach ( $value as $subkey => $subvalue ) {
697 $this->store
->set( "$key:$subkey", $subvalue );
700 $this->store
->set( $key, $value );
703 $this->store
->finishWrite();
705 # Clear out the MessageBlobStore
706 # HACK: If using a null (i.e. disabled) storage backend, we
707 # can't write to the MessageBlobStore either
708 if ( !$this->store
instanceof LCStore_Null
) {
709 MessageBlobStore
::clear();
712 wfProfileOut( __METHOD__
);
716 * Build the preload item from the given pre-cache data.
718 * The preload item will be loaded automatically, improving performance
719 * for the commonly-requested items it contains.
723 protected function buildPreload( $data ) {
724 $preload = array( 'messages' => array() );
725 foreach ( self
::$preloadedKeys as $key ) {
726 $preload[$key] = $data[$key];
729 foreach ( $data['preloadedMessages'] as $subkey ) {
730 if ( isset( $data['messages'][$subkey] ) ) {
731 $subitem = $data['messages'][$subkey];
735 $preload['messages'][$subkey] = $subitem;
742 * Unload the data for a given language from the object cache.
743 * Reduces memory usage.
746 public function unload( $code ) {
747 unset( $this->data
[$code] );
748 unset( $this->loadedItems
[$code] );
749 unset( $this->loadedSubitems
[$code] );
750 unset( $this->initialisedLangs
[$code] );
752 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
753 if ( $fbCode === $code ) {
754 $this->unload( $shallowCode );
762 public function unloadAll() {
763 foreach ( $this->initialisedLangs
as $lang => $unused ) {
764 $this->unload( $lang );
769 * Disable the storage backend
771 public function disableBackend() {
772 $this->store
= new LCStore_Null
;
773 $this->manualRecache
= false;
778 * Interface for the persistence layer of LocalisationCache.
780 * The persistence layer is two-level hierarchical cache. The first level
781 * is the language, the second level is the item or subitem.
783 * Since the data for a whole language is rebuilt in one operation, it needs
784 * to have a fast and atomic method for deleting or replacing all of the
785 * current data for a given language. The interface reflects this bulk update
786 * operation. Callers writing to the cache must first call startWrite(), then
787 * will call set() a couple of thousand times, then will call finishWrite()
788 * to commit the operation. When finishWrite() is called, the cache is
789 * expected to delete all data previously stored for that language.
791 * The values stored are PHP variables suitable for serialize(). Implementations
792 * of LCStore are responsible for serializing and unserializing.
797 * @param $code string Language code
798 * @param $key string Cache key
800 function get( $code, $key );
803 * Start a write transaction.
804 * @param $code Language code
806 function startWrite( $code );
809 * Finish a write transaction.
811 function finishWrite();
814 * Set a key to a given value. startWrite() must be called before this
815 * is called, and finishWrite() must be called afterwards.
819 function set( $key, $value );
823 * LCStore implementation which uses PHP accelerator to store data.
824 * This will work if one of XCache, WinCache or APC cacher is configured.
825 * (See ObjectCache.php)
827 class LCStore_Accel
implements LCStore
{
831 public function __construct() {
832 $this->cache
= wfGetCache( CACHE_ACCEL
);
835 public function get( $code, $key ) {
836 $k = wfMemcKey( 'l10n', $code, 'k', $key );
837 $r = $this->cache
->get( $k );
838 return $r === false ?
null : $r;
841 public function startWrite( $code ) {
842 $k = wfMemcKey( 'l10n', $code, 'l' );
843 $keys = $this->cache
->get( $k );
845 foreach ( $keys as $k ) {
846 $this->cache
->delete( $k );
849 $this->currentLang
= $code;
850 $this->keys
= array();
853 public function finishWrite() {
854 if ( $this->currentLang
) {
855 $k = wfMemcKey( 'l10n', $this->currentLang
, 'l' );
856 $this->cache
->set( $k, array_keys( $this->keys
) );
858 $this->currentLang
= null;
859 $this->keys
= array();
862 public function set( $key, $value ) {
863 if ( $this->currentLang
) {
864 $k = wfMemcKey( 'l10n', $this->currentLang
, 'k', $key );
865 $this->keys
[$k] = true;
866 $this->cache
->set( $k, $value );
872 * LCStore implementation which uses the standard DB functions to store data.
873 * This will work on any MediaWiki installation.
875 class LCStore_DB
implements LCStore
{
877 var $writesDone = false;
884 var $readOnly = false;
886 public function get( $code, $key ) {
887 if ( $this->writesDone
) {
888 $db = wfGetDB( DB_MASTER
);
890 $db = wfGetDB( DB_SLAVE
);
892 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
893 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
895 return unserialize( $row->lc_value
);
901 public function startWrite( $code ) {
902 if ( $this->readOnly
) {
907 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
910 $this->dbw
= wfGetDB( DB_MASTER
);
912 $this->dbw
->begin( __METHOD__
);
913 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
914 } catch ( DBQueryError
$e ) {
915 if ( $this->dbw
->wasReadOnlyError() ) {
916 $this->readOnly
= true;
917 $this->dbw
->rollback( __METHOD__
);
918 $this->dbw
->ignoreErrors( false );
925 $this->currentLang
= $code;
926 $this->batch
= array();
929 public function finishWrite() {
930 if ( $this->readOnly
) {
934 if ( $this->batch
) {
935 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
938 $this->dbw
->commit( __METHOD__
);
939 $this->currentLang
= null;
941 $this->batch
= array();
942 $this->writesDone
= true;
945 public function set( $key, $value ) {
946 if ( $this->readOnly
) {
950 if ( is_null( $this->currentLang
) ) {
951 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
954 $this->batch
[] = array(
955 'lc_lang' => $this->currentLang
,
957 'lc_value' => serialize( $value ) );
959 if ( count( $this->batch
) >= 100 ) {
960 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
961 $this->batch
= array();
967 * LCStore implementation which stores data as a collection of CDB files in the
968 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
969 * will throw an exception.
971 * Profiling indicates that on Linux, this implementation outperforms MySQL if
972 * the directory is on a local filesystem and there is ample kernel cache
973 * space. The performance advantage is greater when the DBA extension is
974 * available than it is with the PHP port.
976 * See Cdb.php and http://cr.yp.to/cdb.html
978 class LCStore_CDB
implements LCStore
{
979 var $readers, $writer, $currentLang, $directory;
981 function __construct( $conf = array() ) {
982 global $wgCacheDirectory;
984 if ( isset( $conf['directory'] ) ) {
985 $this->directory
= $conf['directory'];
987 $this->directory
= $wgCacheDirectory;
991 public function get( $code, $key ) {
992 if ( !isset( $this->readers
[$code] ) ) {
993 $fileName = $this->getFileName( $code );
995 if ( !file_exists( $fileName ) ) {
996 $this->readers
[$code] = false;
998 $this->readers
[$code] = CdbReader
::open( $fileName );
1002 if ( !$this->readers
[$code] ) {
1005 $value = $this->readers
[$code]->get( $key );
1007 if ( $value === false ) {
1010 return unserialize( $value );
1014 public function startWrite( $code ) {
1015 if ( !file_exists( $this->directory
) ) {
1016 if ( !wfMkdirParents( $this->directory
, null, __METHOD__
) ) {
1017 throw new MWException( "Unable to create the localisation store " .
1018 "directory \"{$this->directory}\"" );
1022 // Close reader to stop permission errors on write
1023 if( !empty($this->readers
[$code]) ) {
1024 $this->readers
[$code]->close();
1027 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
1028 $this->currentLang
= $code;
1031 public function finishWrite() {
1033 $this->writer
->close();
1034 $this->writer
= null;
1035 unset( $this->readers
[$this->currentLang
] );
1036 $this->currentLang
= null;
1039 public function set( $key, $value ) {
1040 if ( is_null( $this->writer
) ) {
1041 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
1043 $this->writer
->set( $key, serialize( $value ) );
1046 protected function getFileName( $code ) {
1047 if ( !$code ||
strpos( $code, '/' ) !== false ) {
1048 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
1050 return "{$this->directory}/l10n_cache-$code.cdb";
1055 * Null store backend, used to avoid DB errors during install
1057 class LCStore_Null
implements LCStore
{
1058 public function get( $code, $key ) {
1062 public function startWrite( $code ) {}
1063 public function finishWrite() {}
1064 public function set( $key, $value ) {}
1068 * A localisation cache optimised for loading large amounts of data for many
1069 * languages. Used by rebuildLocalisationCache.php.
1071 class LocalisationCache_BulkLoad
extends LocalisationCache
{
1073 * A cache of the contents of data files.
1074 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1076 var $fileCache = array();
1079 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1080 * to keep the most recently used language codes at the end of the array, and
1081 * the language codes that are ready to be deleted at the beginning.
1083 var $mruLangs = array();
1086 * Maximum number of languages that may be loaded into $this->data
1088 var $maxLoadedLangs = 10;
1093 * @return array|mixed
1095 protected function readPHPFile( $fileName, $fileType ) {
1096 $serialize = $fileType === 'core';
1097 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
1098 $data = parent
::readPHPFile( $fileName, $fileType );
1101 $encData = serialize( $data );
1106 $this->fileCache
[$fileName][$fileType] = $encData;
1109 } elseif ( $serialize ) {
1110 return unserialize( $this->fileCache
[$fileName][$fileType] );
1112 return $this->fileCache
[$fileName][$fileType];
1121 public function getItem( $code, $key ) {
1122 unset( $this->mruLangs
[$code] );
1123 $this->mruLangs
[$code] = true;
1124 return parent
::getItem( $code, $key );
1133 public function getSubitem( $code, $key, $subkey ) {
1134 unset( $this->mruLangs
[$code] );
1135 $this->mruLangs
[$code] = true;
1136 return parent
::getSubitem( $code, $key, $subkey );
1142 public function recache( $code ) {
1143 parent
::recache( $code );
1144 unset( $this->mruLangs
[$code] );
1145 $this->mruLangs
[$code] = true;
1152 public function unload( $code ) {
1153 unset( $this->mruLangs
[$code] );
1154 parent
::unload( $code );
1158 * Unload cached languages until there are less than $this->maxLoadedLangs
1160 protected function trimCache() {
1161 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
1162 reset( $this->mruLangs
);
1163 $code = key( $this->mruLangs
);
1164 wfDebug( __METHOD__
.": unloading $code\n" );
1165 $this->unload( $code );