3 define( 'MW_LC_VERSION', 1 );
6 * Class for caching the contents of localisation files, Messages*.php
9 * An instance of this class is available using Language::getLocalisationCache().
11 * The values retrieved from here are merged, containing items from extension
12 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
13 * zh-hans -> en ). Some common errors are corrected, for example namespace
14 * names with spaces instead of underscores, but heavyweight processing, such
15 * as grammatical transformation, is done by the caller.
17 class LocalisationCache
{
18 /** Configuration associative array */
22 * True if recaching should only be done on an explicit call to recache().
23 * Setting this reduces the overhead of cache freshness checking, which
24 * requires doing a stat() for every extension i18n file.
26 var $manualRecache = false;
29 * True to treat all files as expired until they are regenerated by this object.
31 var $forceRecache = false;
34 * The cache data. 3-d array, where the first key is the language code,
35 * the second key is the item key e.g. 'messages', and the third key is
36 * an item specific subkey index. Some items are not arrays and so for those
37 * items, there are no subkeys.
42 * The persistent store object. An instance of LCStore.
47 * A 2-d associative array, code/key, where presence indicates that the item
48 * is loaded. Value arbitrary.
50 * For split items, if set, this indicates that all of the subitems have been
53 var $loadedItems = array();
56 * A 3-d associative array, code/key/subkey, where presence indicates that
57 * the subitem is loaded. Only used for the split items, i.e. messages.
59 var $loadedSubitems = array();
62 * An array where presence of a key indicates that that language has been
63 * initialised. Initialisation includes checking for cache expiry and doing
64 * any necessary updates.
66 var $initialisedLangs = array();
69 * An array mapping non-existent pseudo-languages to fallback languages. This
70 * is filled by initShallowFallback() when data is requested from a language
71 * that lacks a Messages*.php file.
73 var $shallowFallbacks = array();
76 * An array where the keys are codes that have been recached by this instance.
78 var $recachedLangs = array();
81 * Data added by extensions using the deprecated $wgMessageCache->addMessages()
84 var $legacyData = array();
89 static public $allKeys = array(
90 'fallback', 'namespaceNames', 'mathNames', 'bookstoreList',
91 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
92 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
93 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
94 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
95 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
96 'imageFiles', 'preloadedMessages',
100 * Keys for items which consist of associative arrays, which may be merged
101 * by a fallback sequence.
103 static public $mergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
104 'dateFormats', 'defaultUserOptionOverrides', 'magicWords', 'imageFiles',
109 * Keys for items which are a numbered array.
111 static public $mergeableListKeys = array( 'extraUserToggles' );
114 * Keys for items which contain an array of arrays of equivalent aliases
115 * for each subitem. The aliases may be merged by a fallback sequence.
117 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
120 * Keys for items which contain an associative array, and may be merged if
121 * the primary value contains the special array key "inherit". That array
122 * key is removed after the first merge.
124 static public $optionalMergeKeys = array( 'bookstoreList' );
127 * Keys for items where the subitems are stored in the backend separately.
129 static public $splitKeys = array( 'messages' );
132 * Keys which are loaded automatically by initLanguage()
134 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames',
135 'defaultUserOptionOverrides' );
139 * For constructor parameters, see the documentation in DefaultSettings.php
140 * for $wgLocalisationCacheConf.
142 function __construct( $conf ) {
143 global $wgCacheDirectory;
146 $storeConf = array();
147 if ( !empty( $conf['storeClass'] ) ) {
148 $storeClass = $conf['storeClass'];
150 switch ( $conf['store'] ) {
153 $storeClass = 'LCStore_CDB';
156 $storeClass = 'LCStore_DB';
159 $storeClass = $wgCacheDirectory ?
'LCStore_CDB' : 'LCStore_DB';
162 throw new MWException(
163 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
167 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
168 if ( !empty( $conf['storeDirectory'] ) ) {
169 $storeConf['directory'] = $conf['storeDirectory'];
172 $this->store
= new $storeClass( $storeConf );
173 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
174 if ( isset( $conf[$var] ) ) {
175 $this->$var = $conf[$var];
181 * Returns true if the given key is mergeable, that is, if it is an associative
182 * array which can be merged through a fallback sequence.
184 public function isMergeableKey( $key ) {
185 if ( !isset( $this->mergeableKeys
) ) {
186 $this->mergeableKeys
= array_flip( array_merge(
187 self
::$mergeableMapKeys,
188 self
::$mergeableListKeys,
189 self
::$mergeableAliasListKeys,
190 self
::$optionalMergeKeys
193 return isset( $this->mergeableKeys
[$key] );
199 * Warning: this may be slow for split items (messages), since it will
200 * need to fetch all of the subitems from the cache individually.
202 public function getItem( $code, $key ) {
203 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
204 wfProfileIn( __METHOD__
.'-load' );
205 $this->loadItem( $code, $key );
206 wfProfileOut( __METHOD__
.'-load' );
208 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
209 return $this->shallowFallbacks
[$code];
211 return $this->data
[$code][$key];
215 * Get a subitem, for instance a single message for a given language.
217 public function getSubitem( $code, $key, $subkey ) {
218 if ( isset( $this->legacyData
[$code][$key][$subkey] ) ) {
219 return $this->legacyData
[$code][$key][$subkey];
221 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] )
222 && !isset( $this->loadedItems
[$code][$key] ) )
224 wfProfileIn( __METHOD__
.'-load' );
225 $this->loadSubitem( $code, $key, $subkey );
226 wfProfileOut( __METHOD__
.'-load' );
228 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
229 return $this->data
[$code][$key][$subkey];
236 * Load an item into the cache.
238 protected function loadItem( $code, $key ) {
239 if ( !isset( $this->initialisedLangs
[$code] ) ) {
240 $this->initLanguage( $code );
242 // Check to see if initLanguage() loaded it for us
243 if ( isset( $this->loadedItems
[$code][$key] ) ) {
246 if ( isset( $this->shallowFallbacks
[$code] ) ) {
247 $this->loadItem( $this->shallowFallbacks
[$code], $key );
250 if ( in_array( $key, self
::$splitKeys ) ) {
251 $subkeyList = $this->getSubitem( $code, 'list', $key );
252 foreach ( $subkeyList as $subkey ) {
253 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
256 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
259 $this->data
[$code][$key] = $this->store
->get( $code, $key );
261 $this->loadedItems
[$code][$key] = true;
265 * Load a subitem into the cache
267 protected function loadSubitem( $code, $key, $subkey ) {
268 if ( !in_array( $key, self
::$splitKeys ) ) {
269 $this->loadItem( $code, $key );
272 if ( !isset( $this->initialisedLangs
[$code] ) ) {
273 $this->initLanguage( $code );
275 // Check to see if initLanguage() loaded it for us
276 if ( isset( $this->loadedItems
[$code][$key] )
277 ||
isset( $this->loadedSubitems
[$code][$key][$subkey] ) )
281 if ( isset( $this->shallowFallbacks
[$code] ) ) {
282 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
285 $value = $this->store
->get( $code, "$key:$subkey" );
286 $this->data
[$code][$key][$subkey] = $value;
287 $this->loadedSubitems
[$code][$key][$subkey] = true;
291 * Returns true if the cache identified by $code is missing or expired.
293 public function isExpired( $code ) {
294 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
295 wfDebug( __METHOD__
."($code): forced reload\n" );
299 $deps = $this->store
->get( $code, 'deps' );
300 if ( $deps === null ) {
301 wfDebug( __METHOD__
."($code): cache missing, need to make one\n" );
304 foreach ( $deps as $dep ) {
305 // Because we're unserializing stuff from cache, we
306 // could receive objects of classes that don't exist
307 // anymore (e.g. uninstalled extensions)
308 // When this happens, always expire the cache
309 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
310 wfDebug( __METHOD__
."($code): cache for $code expired due to " .
311 get_class( $dep ) . "\n" );
319 * Initialise a language in this object. Rebuild the cache if necessary.
321 protected function initLanguage( $code ) {
322 if ( isset( $this->initialisedLangs
[$code] ) ) {
325 $this->initialisedLangs
[$code] = true;
327 # Recache the data if necessary
328 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
329 if ( file_exists( Language
::getMessagesFileName( $code ) ) ) {
330 $this->recache( $code );
331 } elseif ( $code === 'en' ) {
332 throw new MWException( 'MessagesEn.php is missing.' );
334 $this->initShallowFallback( $code, 'en' );
340 $preload = $this->getItem( $code, 'preload' );
341 if ( $preload === null ) {
342 if ( $this->manualRecache
) {
343 // No Messages*.php file. Do shallow fallback to en.
344 if ( $code === 'en' ) {
345 throw new MWException( 'No localisation cache found for English. ' .
346 'Please run maintenance/rebuildLocalisationCache.php.' );
348 $this->initShallowFallback( $code, 'en' );
351 throw new MWException( 'Invalid or missing localisation cache.' );
354 $this->data
[$code] = $preload;
355 foreach ( $preload as $key => $item ) {
356 if ( in_array( $key, self
::$splitKeys ) ) {
357 foreach ( $item as $subkey => $subitem ) {
358 $this->loadedSubitems
[$code][$key][$subkey] = true;
361 $this->loadedItems
[$code][$key] = true;
367 * Create a fallback from one language to another, without creating a
368 * complete persistent cache.
370 public function initShallowFallback( $primaryCode, $fallbackCode ) {
371 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
372 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
373 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
374 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
378 * Read a PHP file containing localisation data.
380 protected function readPHPFile( $_fileName, $_fileType ) {
381 // Disable APC caching
382 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
383 include( $_fileName );
384 ini_set( 'apc.cache_by_default', $_apcEnabled );
386 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
387 $data = compact( self
::$allKeys );
388 } elseif ( $_fileType == 'aliases' ) {
389 $data = compact( 'aliases' );
391 throw new MWException( __METHOD__
.": Invalid file type: $_fileType" );
397 * Merge two localisation values, a primary and a fallback, overwriting the
398 * primary value in place.
400 protected function mergeItem( $key, &$value, $fallbackValue ) {
401 if ( !is_null( $value ) ) {
402 if ( !is_null( $fallbackValue ) ) {
403 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
404 $value = $value +
$fallbackValue;
405 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
406 $value = array_unique( array_merge( $fallbackValue, $value ) );
407 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
408 $value = array_merge_recursive( $value, $fallbackValue );
409 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
410 if ( !empty( $value['inherit'] ) ) {
411 $value = array_merge( $fallbackValue, $value );
413 if ( isset( $value['inherit'] ) ) {
414 unset( $value['inherit'] );
419 $value = $fallbackValue;
424 * Given an array mapping language code to localisation value, such as is
425 * found in extension *.i18n.php files, iterate through a fallback sequence
426 * to merge the given data with an existing primary value.
428 * Returns true if any data from the extension array was used, false
431 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
433 foreach ( $codeSequence as $code ) {
434 if ( isset( $fallbackValue[$code] ) ) {
435 $this->mergeItem( $key, $value, $fallbackValue[$code] );
443 * Load localisation data for a given language for both core and extensions
444 * and save it to the persistent cache store and the process cache
446 public function recache( $code ) {
447 static $recursionGuard = array();
448 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
449 wfProfileIn( __METHOD__
);
452 throw new MWException( "Invalid language code requested" );
454 $this->recachedLangs
[$code] = true;
457 $initialData = array_combine(
459 array_fill( 0, count( self
::$allKeys ), null ) );
460 $coreData = $initialData;
463 # Load the primary localisation from the source file
464 $fileName = Language
::getMessagesFileName( $code );
465 if ( !file_exists( $fileName ) ) {
466 wfDebug( __METHOD__
.": no localisation file for $code, using fallback to en\n" );
467 $coreData['fallback'] = 'en';
469 $deps[] = new FileDependency( $fileName );
470 $data = $this->readPHPFile( $fileName, 'core' );
471 wfDebug( __METHOD__
.": got localisation for $code from source\n" );
473 # Merge primary localisation
474 foreach ( $data as $key => $value ) {
475 $this->mergeItem( $key, $coreData[$key], $value );
479 # Fill in the fallback if it's not there already
480 if ( is_null( $coreData['fallback'] ) ) {
481 $coreData['fallback'] = $code === 'en' ?
false : 'en';
484 if ( $coreData['fallback'] !== false ) {
485 # Guard against circular references
486 if ( isset( $recursionGuard[$code] ) ) {
487 throw new MWException( "Error: Circular fallback reference in language code $code" );
489 $recursionGuard[$code] = true;
491 # Load the fallback localisation item by item and merge it
492 $deps = array_merge( $deps, $this->getItem( $coreData['fallback'], 'deps' ) );
493 foreach ( self
::$allKeys as $key ) {
494 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
495 $fallbackValue = $this->getItem( $coreData['fallback'], $key );
496 $this->mergeItem( $key, $coreData[$key], $fallbackValue );
499 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
500 array_unshift( $fallbackSequence, $coreData['fallback'] );
501 $coreData['fallbackSequence'] = $fallbackSequence;
502 unset( $recursionGuard[$code] );
504 $coreData['fallbackSequence'] = array();
506 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
508 # Load the extension localisations
509 # This is done after the core because we know the fallback sequence now.
510 # But it has a higher precedence for merging so that we can support things
511 # like site-specific message overrides.
512 $allData = $initialData;
513 foreach ( $wgExtensionMessagesFiles as $fileName ) {
514 $data = $this->readPHPFile( $fileName, 'extension' );
516 foreach ( $data as $key => $item ) {
517 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
522 $deps[] = new FileDependency( $fileName );
526 # Load deprecated $wgExtensionAliasesFiles
527 foreach ( $wgExtensionAliasesFiles as $fileName ) {
528 $data = $this->readPHPFile( $fileName, 'aliases' );
529 if ( !isset( $data['aliases'] ) ) {
532 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
533 $allData['specialPageAliases'], $data['aliases'] );
535 $deps[] = new FileDependency( $fileName );
539 # Merge core data into extension data
540 foreach ( $coreData as $key => $item ) {
541 $this->mergeItem( $key, $allData[$key], $item );
544 # Add cache dependencies for any referenced globals
545 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
546 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
547 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
549 # Add dependencies to the cache entry
550 $allData['deps'] = $deps;
552 # Replace spaces with underscores in namespace names
553 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
555 # And do the same for special page aliases. $page is an array.
556 foreach ( $allData['specialPageAliases'] as &$page ) {
557 $page = str_replace( ' ', '_', $page );
559 # Decouple the reference to prevent accidental damage
562 # Fix broken defaultUserOptionOverrides
563 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
564 $allData['defaultUserOptionOverrides'] = array();
567 # Set the preload key
568 $allData['preload'] = $this->buildPreload( $allData );
571 $allData['list'] = array();
572 foreach ( self
::$splitKeys as $key ) {
573 $allData['list'][$key] = array_keys( $allData[$key] );
577 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
579 if ( is_null( $allData['defaultUserOptionOverrides'] ) ) {
580 throw new MWException( __METHOD__
.': Localisation data failed sanity check! ' .
581 'Check that your languages/messages/MessagesEn.php file is intact.' );
584 # Save to the process cache and register the items loaded
585 $this->data
[$code] = $allData;
586 foreach ( $allData as $key => $item ) {
587 $this->loadedItems
[$code][$key] = true;
590 # Save to the persistent cache
591 $this->store
->startWrite( $code );
592 foreach ( $allData as $key => $value ) {
593 if ( in_array( $key, self
::$splitKeys ) ) {
594 foreach ( $value as $subkey => $subvalue ) {
595 $this->store
->set( "$key:$subkey", $subvalue );
598 $this->store
->set( $key, $value );
601 $this->store
->finishWrite();
603 wfProfileOut( __METHOD__
);
607 * Build the preload item from the given pre-cache data.
609 * The preload item will be loaded automatically, improving performance
610 * for the commonly-requested items it contains.
612 protected function buildPreload( $data ) {
613 $preload = array( 'messages' => array() );
614 foreach ( self
::$preloadedKeys as $key ) {
615 $preload[$key] = $data[$key];
617 foreach ( $data['preloadedMessages'] as $subkey ) {
618 if ( isset( $data['messages'][$subkey] ) ) {
619 $subitem = $data['messages'][$subkey];
623 $preload['messages'][$subkey] = $subitem;
629 * Unload the data for a given language from the object cache.
630 * Reduces memory usage.
632 public function unload( $code ) {
633 unset( $this->data
[$code] );
634 unset( $this->loadedItems
[$code] );
635 unset( $this->loadedSubitems
[$code] );
636 unset( $this->initialisedLangs
[$code] );
637 // We don't unload legacyData because there's no way to get it back
638 // again, it's not really a cache
639 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
640 if ( $fbCode === $code ) {
641 $this->unload( $shallowCode );
649 public function unloadAll() {
650 foreach ( $this->initialisedLangs
as $lang => $unused ) {
651 $this->unload( $lang );
656 * Add messages to the cache, from an extension that has not yet been
657 * migrated to $wgExtensionMessages or the LocalisationCacheRecache hook.
658 * Called by deprecated function $wgMessageCache->addMessages().
660 public function addLegacyMessages( $messages ) {
661 foreach ( $messages as $lang => $langMessages ) {
662 if ( isset( $this->legacyData
[$lang]['messages'] ) ) {
663 $this->legacyData
[$lang]['messages'] =
664 $langMessages +
$this->legacyData
[$lang]['messages'];
666 $this->legacyData
[$lang]['messages'] = $langMessages;
672 * Disable the storage backend
674 public function disableBackend() {
675 $this->store
= new LCStore_Null
;
676 $this->manualRecache
= false;
681 * Interface for the persistence layer of LocalisationCache.
683 * The persistence layer is two-level hierarchical cache. The first level
684 * is the language, the second level is the item or subitem.
686 * Since the data for a whole language is rebuilt in one operation, it needs
687 * to have a fast and atomic method for deleting or replacing all of the
688 * current data for a given language. The interface reflects this bulk update
689 * operation. Callers writing to the cache must first call startWrite(), then
690 * will call set() a couple of thousand times, then will call finishWrite()
691 * to commit the operation. When finishWrite() is called, the cache is
692 * expected to delete all data previously stored for that language.
694 * The values stored are PHP variables suitable for serialize(). Implementations
695 * of LCStore are responsible for serializing and unserializing.
700 * @param $code Language code
701 * @param $key Cache key
703 public function get( $code, $key );
706 * Start a write transaction.
707 * @param $code Language code
709 public function startWrite( $code );
712 * Finish a write transaction.
714 public function finishWrite();
717 * Set a key to a given value. startWrite() must be called before this
718 * is called, and finishWrite() must be called afterwards.
720 public function set( $key, $value );
725 * LCStore implementation which uses the standard DB functions to store data.
726 * This will work on any MediaWiki installation.
728 class LCStore_DB
implements LCStore
{
730 var $writesDone = false;
732 var $readOnly = false;
734 public function get( $code, $key ) {
735 if ( $this->writesDone
) {
736 $db = wfGetDB( DB_MASTER
);
738 $db = wfGetDB( DB_SLAVE
);
740 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
741 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__
);
743 return unserialize( $row->lc_value
);
749 public function startWrite( $code ) {
750 if ( $this->readOnly
) {
754 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
756 $this->dbw
= wfGetDB( DB_MASTER
);
759 $this->dbw
->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__
);
760 } catch ( DBQueryError
$e ) {
761 if ( $this->dbw
->wasReadOnlyError() ) {
762 $this->readOnly
= true;
763 $this->dbw
->rollback();
764 $this->dbw
->ignoreErrors( false );
770 $this->currentLang
= $code;
771 $this->batch
= array();
774 public function finishWrite() {
775 if ( $this->readOnly
) {
778 if ( $this->batch
) {
779 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
781 $this->dbw
->commit();
782 $this->currentLang
= null;
784 $this->batch
= array();
785 $this->writesDone
= true;
788 public function set( $key, $value ) {
789 if ( $this->readOnly
) {
792 if ( is_null( $this->currentLang
) ) {
793 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
795 $this->batch
[] = array(
796 'lc_lang' => $this->currentLang
,
798 'lc_value' => serialize( $value ) );
799 if ( count( $this->batch
) >= 100 ) {
800 $this->dbw
->insert( 'l10n_cache', $this->batch
, __METHOD__
);
801 $this->batch
= array();
807 * LCStore implementation which stores data as a collection of CDB files in the
808 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
809 * will throw an exception.
811 * Profiling indicates that on Linux, this implementation outperforms MySQL if
812 * the directory is on a local filesystem and there is ample kernel cache
813 * space. The performance advantage is greater when the DBA extension is
814 * available than it is with the PHP port.
816 * See Cdb.php and http://cr.yp.to/cdb.html
818 class LCStore_CDB
implements LCStore
{
819 var $readers, $writer, $currentLang, $directory;
821 function __construct( $conf = array() ) {
822 global $wgCacheDirectory;
823 if ( isset( $conf['directory'] ) ) {
824 $this->directory
= $conf['directory'];
826 $this->directory
= $wgCacheDirectory;
830 public function get( $code, $key ) {
831 if ( !isset( $this->readers
[$code] ) ) {
832 $fileName = $this->getFileName( $code );
833 if ( !file_exists( $fileName ) ) {
834 $this->readers
[$code] = false;
836 $this->readers
[$code] = CdbReader
::open( $fileName );
839 if ( !$this->readers
[$code] ) {
842 $value = $this->readers
[$code]->get( $key );
843 if ( $value === false ) {
846 return unserialize( $value );
850 public function startWrite( $code ) {
851 if ( !file_exists( $this->directory
) ) {
852 if ( !wfMkdirParents( $this->directory
) ) {
853 throw new MWException( "Unable to create the localisation store " .
854 "directory \"{$this->directory}\"" );
857 // Close reader to stop permission errors on write
858 if( !empty($this->readers
[$code]) ) {
859 $this->readers
[$code]->close();
861 $this->writer
= CdbWriter
::open( $this->getFileName( $code ) );
862 $this->currentLang
= $code;
865 public function finishWrite() {
867 $this->writer
->close();
868 $this->writer
= null;
869 unset( $this->readers
[$this->currentLang
] );
870 $this->currentLang
= null;
873 public function set( $key, $value ) {
874 if ( is_null( $this->writer
) ) {
875 throw new MWException( __CLASS__
.': must call startWrite() before calling set()' );
877 $this->writer
->set( $key, serialize( $value ) );
880 protected function getFileName( $code ) {
881 if ( !$code ||
strpos( $code, '/' ) !== false ) {
882 throw new MWException( __METHOD__
.": Invalid language \"$code\"" );
884 return "{$this->directory}/l10n_cache-$code.cdb";
889 * Null store backend, used to avoid DB errors during install
891 class LCStore_Null
implements LCStore
{
892 public function get( $code, $key ) {
896 public function startWrite( $code ) {}
897 public function finishWrite() {}
898 public function set( $key, $value ) {}
902 * A localisation cache optimised for loading large amounts of data for many
903 * languages. Used by rebuildLocalisationCache.php.
905 class LocalisationCache_BulkLoad
extends LocalisationCache
{
907 * A cache of the contents of data files.
908 * Core files are serialized to avoid using ~1GB of RAM during a recache.
910 var $fileCache = array();
913 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
914 * to keep the most recently used language codes at the end of the array, and
915 * the language codes that are ready to be deleted at the beginning.
917 var $mruLangs = array();
920 * Maximum number of languages that may be loaded into $this->data
922 var $maxLoadedLangs = 10;
924 protected function readPHPFile( $fileName, $fileType ) {
925 $serialize = $fileType === 'core';
926 if ( !isset( $this->fileCache
[$fileName][$fileType] ) ) {
927 $data = parent
::readPHPFile( $fileName, $fileType );
929 $encData = serialize( $data );
933 $this->fileCache
[$fileName][$fileType] = $encData;
935 } elseif ( $serialize ) {
936 return unserialize( $this->fileCache
[$fileName][$fileType] );
938 return $this->fileCache
[$fileName][$fileType];
942 public function getItem( $code, $key ) {
943 unset( $this->mruLangs
[$code] );
944 $this->mruLangs
[$code] = true;
945 return parent
::getItem( $code, $key );
948 public function getSubitem( $code, $key, $subkey ) {
949 unset( $this->mruLangs
[$code] );
950 $this->mruLangs
[$code] = true;
951 return parent
::getSubitem( $code, $key, $subkey );
954 public function recache( $code ) {
955 parent
::recache( $code );
956 unset( $this->mruLangs
[$code] );
957 $this->mruLangs
[$code] = true;
961 public function unload( $code ) {
962 unset( $this->mruLangs
[$code] );
963 parent
::unload( $code );
967 * Unload cached languages until there are less than $this->maxLoadedLangs
969 protected function trimCache() {
970 while ( count( $this->data
) > $this->maxLoadedLangs
&& count( $this->mruLangs
) ) {
971 reset( $this->mruLangs
);
972 $code = key( $this->mruLangs
);
973 wfDebug( __METHOD__
.": unloading $code\n" );
974 $this->unload( $code );